USACO Ordered Fractions

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
/*
ID: wcr19961
PROG: frac1
LANG: C++11
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;

typedef long long LL;
const int maxn = 165;
struct Frac {
int a, b;
bool operator < (const Frac& rhs) const {
return a * rhs.b < rhs.a * b;
}
} f[maxn * maxn];

int gcd(int a, int b) {
return b ? gcd(b, a % b) : a;
}

int main() {
freopen("frac1.in", "r", stdin);
freopen("frac1.out", "w", stdout);
int n, num = 0;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
for (int j = 0; j <= i; ++j) {
int g = gcd(i, j);
if (g == 1) {
f[num].a = j, f[num].b = i;
++num;
}
}
}
sort(f, f + num);
for (int i = 0; i < num; ++i) {
printf("%d/%d\n", f[i].a, f[i].b);
}
return 0;
}