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
题目大意:
这道题是说,让你输出0~1之间的所有真分式。给你了一个n,这个n表示的最大的分母。
解题思路:
由于n最大只有160,那么直接O(n^2)暴力就可以了,把所有的分子和分母满足条件的组合全部记录下来,然后,从小到大排序后,在一个一个输出就OK了。
代码:
/* ID:wikioi_2 PROG:frac1 LANG:C++ */ # include<cstdio> # include<iostream> # include<algorithm> using namespace std; # define MAX 12345 struct node { int x,y;// x/y; }a[MAX]; int gcd ( int a,int b ) { if ( b==0 ) return a; else return gcd(b,a%b); } int cmp ( const struct node & a,const struct node & b ) { return ( (double)a.x/a.y < (double)b.x/b.y ); } int main(void) { freopen("frac1.in","r",stdin); freopen("frac1.out","w",stdout); int n; scanf("%d",&n); int cnt = 0; for ( int i = 1;i <= n;i++ ) { for ( int j = 0;j <= i;j++ ) { int t1 = j; int t2 = i; if ( gcd(t1,t2)==1 ) { a[cnt].x = j; a[cnt].y = i; cnt++; } } } sort(a,a+cnt,cmp); for ( int i = 0;i < cnt;i++ ) { printf("%d/%d ",a[i].x,a[i].y); } return 0; }