【USACO 2.1.2】法雷序列

【问题描述

    对任意给定的一个自然数 n(n<=160), 将分母小于等于 n 的不可约的真分数按上升的次序排序 , 并且在第一个分数前加上 0/1, 而在最后一个分数后加上 1/1, 这个序列称为 n 级法雷序列 , 以 Fn 表示 . 例如 ,F8 为 :
0/1,1/8,1/7,1/6,1/5,1/4,2/7,1/3,3/8,2/5,3/7,1/2,4/7,3/5,5/8,2/3,5/7,3/4,4/5,5/6,6/7,7/8,1/1.

编程求出 n 级法雷序列 , 每行输出 1 个分数 .

【输入格式】

    输入只有一行,一个整数n(1≤n≤160);

【输出格式】

    输出有若干行,每行一个分数。

【分析】

直接枚举就行了,注意判重,排序的时候注意分数处理。

 1 #include <cstdlib>
 2 #include <iostream>
 3 #include <cstdio>
 4 #include <cstring>
 5 #include <cmath>
 6 #include <queue>
 7 #include <algorithm>
 8 const int maxn=160+10;
 9 using namespace std;
10 struct Ans
11 {
12        int fz,fm;
13        bool operator < (const Ans&b)const
14        {
15             return double((double)fz/fm)<(double)((double)b.fz/b.fm);
16        }
17 }ans[maxn*maxn];
18 bool hash[maxn][maxn];
19 int gcd(int a,int b) {return b==0?a:gcd(b,a%b);}
20 int main()
21 {
22     int n,i,j,point=0;
23     //文件操作
24     freopen("frac1.in","r",stdin);
25     freopen("frac1.out","w",stdout);  
26     printf("0/1\n");
27     scanf("%d",&n);
28     for (i=1;i<=n;i++)
29     for (j=i+1;j<=n;j++)
30     {
31         int a=i,b=j,temp=gcd(i,j);
32         a=a/temp;b=b/temp;
33         if (hash[a][b]==0)
34         {
35             hash[a][b]=1;
36             ans[point].fz=a;ans[point++].fm=b;
37         }
38     }
39     sort(ans,ans+point);
40     for (i=0;i<point;i++) printf("%d/%d\n",ans[i].fz,ans[i].fm);
41     printf("1/1\n");
42     return 0;
43 }

 

posted @ 2014-06-14 20:07  TCtower  阅读(453)  评论(0编辑  收藏  举报