usaco2.1Ordered Fractions( 枚举, 数学)
这道题是给出一个n 求出分子分母<=n 且 gcd(u,d) = 1 , (u代表分子,d代表分母) 0<=u/d<=1
常规方法就是枚举n平方个数字。。然后进行比较排序等。。看了解答后发现一种数学方法比较神奇。 代码也非常短,递归版本
大致思路是 0/0 -------------------------1/1
0/0 ----------1/2----------1/1
0/0---1/4---1/2----2/3----1/1
如此这样递归下去。。具体数学证明我就不搬运了。。
题目:
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:doubles3 3 PROB:frac1 4 LANG:C++ 5 */ 6 #include<iostream> 7 #include<cstdlib> 8 #include<stdio.h> 9 #include<fstream> 10 #include<math.h> 11 #include <algorithm> 12 #include<string.h> 13 #include<string> 14 #include<vector> 15 #include <queue> 16 #include <set> 17 using namespace std; 18 19 int N; 20 21 int print(int au,int ad,int bu,int bd) 22 { 23 if(ad+bd<=N) 24 { 25 print(au,ad,au+bu,ad+bd); 26 cout<<au+bu<<"/"<<ad+bd<<endl; 27 print(au+bu,ad+bd,bu,bd); 28 } 29 else 30 return 0; 31 } 32 33 int main() 34 { 35 freopen("frac1.in","r",stdin); 36 freopen("frac1.out","w",stdout); 37 38 cin>>N; 39 40 cout<<"0/1"<<endl; 41 print(0,1,1,1); 42 cout<<"1/1"<<endl; 43 44 return 0; 45 }