Categories

USACO 2.1.2 Ordered Fractions

简单题。

My code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
ID: tgh7281
LANG: C++
TASK: frac1
*/
#include <iostream>
#include <fstream>
using namespace std;
int gcd(int a,int b);
int cmp(const void*a,const void*b);
 
struct frac
{
    int a,b;
};
 
int main()
{
    ifstream fin("frac1.in");
    ofstream fout("frac1.out");
    frac f[160*160];
    int n,total;
 
    f[0].a=0;
    f[0].b=1;
    while (fin>>n)
    {
        total=1;
 
        int i,j,g;
        for (i=1;i<=n;i++)
        {
            for (j=i+1;j<=n;j++)
            {
                g=gcd(i,j);
                if (g>1) continue;
                f[total].a=i/g;
                f[total].b=j/g;
                total++;
            }
        }
 
        qsort(f,total,sizeof(f[0]),cmp);
        for (i=0;i<total;i++) fout<<f[i].a<<"/"<<f[i].b<<endl;
        fout<<"1/1"<<endl;
    }
 
    return 0;
}
 
int gcd(int a,int b)
{
    if (b==0) return a;
    return gcd(b,a%b);
}
 
int cmp(const void*a,const void*b)
{
    frac*c=(frac*)a;
    frac*d=(frac*)b;
    return c->a*d->b-d->a*c->b;
}

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

  

  

  

*