您的位置:首页 > 其它

usaco2.1.2(frac1)

2012-07-24 21:02 369 查看
题目:

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/51/4
1/3
2/51/2
3/52/3
3/4
4/51/1

题意是说输入N,输出分母小于N的所有真分数,见样例
题目分类是图论,但始终想不通与图论有毛线关系
代码:


/*
ID:614433244
PROG: frac1
LANG: C++
*/
#include"iostream"
#include"cstdio"
#include"algorithm"
#include"cstring"
using namespace std;
struct M
{
int fenzi,fenmu;
}fenshu[160*160];
bool cmp( M a,M b )
{
return a.fenzi*b.fenmu < b.fenzi*a.fenmu;
}
int gcd(int a,int b)
{
if( b==0 )
return a;
else
return gcd( b,a%b );
}
int t;
bool vis[160][160];
int main()
{
freopen("frac1.in","r",stdin);
freopen("frac1.out","w",stdout);
memset(vis,0,sizeof(vis));
int n;
scanf("%d",&n);
int i,j;
t=0;
for( i=1;i<=n;i++ )
for( j=i+1;j<=n;j++ )
{
if( vis[ i/gcd(i,j) ][ j/gcd(i,j) ] )
continue;
else
{
fenshu[t].fenzi=i/gcd(i,j);
fenshu[t].fenmu=j/gcd(i,j);
vis[i/gcd(i,j)][j/gcd(i,j)]=1;
t++;
}
}
sort( fenshu,fenshu+t,cmp );
printf("0/1\n");
for( i=0;i<t;i++ )
printf("%d%c%d\n",fenshu[i].fenzi,'/',fenshu[i].fenmu);
printf("1/1\n");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: