USACO SECTION 2.1 Ordered Fractions

Ordered Fractions

Consider the set of all reduced fractions between 0 and 1 inclusive with denominators less than or equal to N.

Here is the set when N = 5:

0/1 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 1/1

Write a program that, given an integer N between 1 and 160 inclusive, prints the fractions in order of increasing magnitude.

PROGRAM NAME: frac1

INPUT FORMAT

One line with a single integer N.

SAMPLE INPUT (file frac1.in)

5

OUTPUT FORMAT

One fraction per line, sorted in order of magnitude.

SAMPLE OUTPUT (file frac1.out)

0/1
1/5
1/4
1/3
2/5
1/2
3/5
2/3
3/4
4/5
1/1
/*
ID: conicoc1
LANG: C
TASK: frac1
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>


struct Number
{
	int a;
	int b;
	float c;
};

int comp(const void*a,const void *b)
{
	struct Number *p1,*p2;
	p1=(struct Number*)a;
	p2=(struct Number*)b;
	
	if(p1->c-p2->c>0)
		return 1;
	else
		return 0;
}

int judge(int a,int b)    //默认b>=a 
{
	if(a==0&&b==1)
		return 1;
	while(b!=0&&a!=0)
	{
		if(b>a)
			b=b%a;
		else
			a=a%b;
	}
	if((a==0&&b==1)||(a==1&&b==0))
		return 1;
	
	return 0;
	
}


int main()
{
	FILE *fin,*fout;
	fin=fopen("frac1.in","r");
	fout=fopen("frac1.out","w");
	
	struct Number A[25600];
	
	int N;
	
	fscanf(fin,"%d",&N);
	
	int i,j;
	int k=0;
	for(i=1;i<=N;i++)
	{
		for(j=0;j<=i;j++)
		{
			if(judge(j,i))
			{
				A[k].a=j;
				A[k].b=i;
				A[k++].c=(float)j/(float)i;
			}
		}
	}
	
	qsort(A,k,sizeof(struct Number),comp);
	
	for(i=0;i<k;i++)
		fprintf(fout,"%d/%d\n",A[i].a,A[i].b);
		
	return 0;
}


关于qsort的comp函数

分析是这样写的:

int fraccompare (struct fraction *p, struct fraction *q) {
   return p->numerator * q->denominator - p->denominator *q->numerator;
}


 

好吧,这道是超级水题吗。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值