USACO 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/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 1/1
由于数据量很小的缘故,我们可以把所有的分数存下来,然后进行排序。
第一步,存下所有的已约分的分数。
第二步,对存下来的分数进行排序。
至此,此题完成。
/** ID: njuwz151 TASK: frac1 LANG: C++ */ #include <bits/stdc++.h> using namespace std; const int maxn = 165; int n; typedef struct { int x; int y; } Frac; Frac frac[maxn*maxn]; int cmp(Frac a, Frac b); int gcd(int a, int b); int main() { freopen("frac1.in", "r", stdin); freopen("frac1.out", "w", stdout); cin >> n; int count = 0; for(int i = 1; i <= n; i++) { for(int j = 0; j <= i; j++) { // cout << i << " " << j << " " << gcd(i, j) << endl; if(gcd(i, j) == 1) { frac[count].x = j; frac[count].y = i; count++; } } } sort(frac, frac + count, cmp); for(int i = 0; i < count; i++) { cout << frac[i].x << "/" << frac[i].y << endl; } } int cmp(Frac a, Frac b) { return a.x * b.y < b.x * a.y; } int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }