1. 程式人生 > >USACO Ordered Fractions

USACO Ordered Fractions

pri per class amp const rac bsp ++ name

首先看一下題目

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); }

USACO Ordered Fractions