HITOJ Ordered Fractions 1076 (分数排序)

来源:互联网 发布:ip交换网络拓扑的设计 编辑:程序博客网 时间:2024/06/05 04:01

Ordered Fractions

My Tags  (Edit)
 Source : Unknown Time limit : 3 sec Memory limit : 32 M

Submitted : 1510, Accepted : 496

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.

INPUT FORMAT

Several lines with a single integer N in each line. Process to the end of file.

SAMPLE INPUT

55

OUTPUT FORMAT

One fraction per line, sorted in order of magnitude. print a blank line after each testcase.

SAMPLE OUTPUT

0/11/51/41/32/51/23/52/33/44/51/10/11/51/41/32/51/23/52/33/44/51/1

#include<stdio.h>#include<string.h>#include<algorithm>#define N 1000010using namespace std;struct zz{int x;int y;double s;}q[N];int cmp(zz a,zz b){return a.s<b.s;}int gcd(int x,int y){return y?gcd(y,x%y):x;}int main(){int i,j,n;while(scanf("%d",&n)!=EOF){int k=0;for(i=1;i<=n;i++){for(j=0;j<=i;j++){if(gcd(i,j)==1){q[k].x=j;q[k].y=i;q[k].s=j*1.0/i;k++;}}}sort(q,q+k,cmp);for(i=0;i<k;i++)printf("%d/%d\n",q[i].x,q[i].y);printf("\n");}return 0;}


 

0 0
原创粉丝点击