呃 貌似这道题有很好的方法,不过我已经用笨方法一次过了,就没有再多研究了。我的方法就是枚举加排列,用结构体存分子分母和值,遇到可以约分的略过……下面贴出代码,以作纪念。
View Code
1 /*{ 2 ID:jzy3209981 3 PROG:frac1 4 LANG:C++ 5 }*/ 6 #include<stdio.h> 7 #include<iostream> 8 #include<string.h> 9 #include<math.h> 10 using namespace std; 11 12 13 struct fraction 14 { 15 int son; 16 int mum; 17 double result; 18 }; 19 int com(int a,int b) 20 { 21 int e; 22 while(a%b!=0) 23 { 24 e=b; 25 b=a%b; 26 a=e; 27 } 28 return b; 29 } 30 void paixu(fraction *first,int a,int b) 31 { 32 int i,j; 33 i=a;j=b; 34 fraction cha=first[a]; 35 if(i>=j) 36 return; 37 while(i<j) 38 { 39 while(first[j].result>=first[i].result&&i<j) 40 j--; 41 if(i<j) 42 { 43 first[i]=first[j]; 44 first[j]=cha; 45 i++; 46 } 47 while(first[i].result<=first[j].result&&i<j) 48 i++; 49 if(i<j) 50 { 51 first[j]=first[i]; 52 first[i]=cha; 53 j--; 54 } 55 } 56 paixu(first,a,i-1); 57 paixu(first,i+1,b); 58 } 59 60 int main() 61 { 62 freopen ("frac1.in","r",stdin); 63 freopen ("frac1.out","w",stdout); 64 int n,i,j,common,num=0; 65 fraction *all; 66 scanf("%d",&n); 67 all=new fraction[n*n+2*n+1]; 68 for(i=2;i<=n;i++) 69 for(j=1;j<i;j++) 70 { 71 if(j>1) 72 { 73 common=com(j,i); 74 if(common!=1) 75 continue; 76 } 77 all[num].son=j; 78 all[num].mum=i; 79 all[num].result=(double)j/i; 80 num++; 81 } 82 paixu(all,0,num-1); 83 printf("0/1\n"); 84 for(i=0;i<num;i++) 85 printf("%d/%d\n",all[i].son,all[i].mum); 86 printf("1/1\n"); 87 return 0; 88 } 89 90

浙公网安备 33010602011771号