USACO Section 2.1 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
分析:枚举、排序
心得:排序的时候起初用的是除,最后搞得出现精度问题,切记能不除就尽量不除。

1 /* 2 ID: dizzy_l1 3 LANG: C++ 4 TASK: frac1 5 */ 6 #include<iostream> 7 #include<algorithm> 8 #include<cstdio> 9 #include<cmath> 10 #define MAXN 40000 11 12 using namespace std; 13 14 struct ANS 15 { 16 int a,b; 17 }ans[MAXN]; 18 19 bool cmp(ANS A,ANS B) 20 { 21 if(A.a*B.b<A.b*B.a) return true; 22 if(A.a*B.b==A.b*B.a&&A.a<B.a) return true; 23 return false; 24 } 25 26 int main() 27 { 28 // freopen("frac1.in","r",stdin); 29 // freopen("frac1.out","w",stdout); 30 int n,i,j,k; 31 while(scanf("%d",&n)==1) 32 { 33 k=0; 34 ans[k].a=0;ans[k].b=1; 35 k++; 36 for(i=1;i<=n;i++) 37 { 38 for(j=i;j<=n;j++) 39 { 40 ans[k].a=i;ans[k].b=j; 41 k++; 42 } 43 } 44 sort(ans,ans+k,cmp); 45 printf("%d/%d\n",ans[0].a,ans[0].b); 46 for(i=1;i<k;i++) 47 { 48 if(ans[i].a*ans[i-1].b==ans[i].b*ans[i-1].a) 49 continue; 50 printf("%d/%d\n",ans[i].a,ans[i].b); 51 } 52 } 53 return 0; 54 }