首页 > 代码库 > 【USACO 2.1】Ordered Fractions

【USACO 2.1】Ordered Fractions

/*TASK: frac1LANG: C++URL: http://train.usaco.org/usacoprob2?S=frac1&a=dbgwn5v2WLrSOLVE: 直接枚举,约分,排序,去重 */#include<cstdio>#include<algorithm>using namespace std;struct node{	int nu,deno;	double v;}a[40000];int n,cnt;int cmp(node a,node b){	return a.v<b.v;}int gcd(int a,int b){	return b?gcd(b,a%b):a;}int main(){	freopen("frac1.in","r",stdin);	freopen("frac1.out","w",stdout);	scanf("%d",&n);	for(int i=0;i<=n;i++)		for(int j=max(i,1);j<=n;j++){			int g=gcd(i,j);			a[cnt++]=(node){i/g,j/g,i*1.0/j};		}	sort(a,a+cnt,cmp);	for(int i=0;i<cnt;i++){		if(i==0||a[i].v-a[i-1].v>1e-6||a[i].v-a[i-1].v<-1e-6)		printf("%d/%d\n",a[i].nu,a[i].deno);	}	return 0;}

  

【USACO 2.1】Ordered Fractions