zoukankan      html  css  js  c++  java
  • 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);
    }
  • 相关阅读:
    (转)一台服务器安装两个tomcat6 服务的解决方案
    目标的改变
    常用但易忘的sql语句及java程序
    数据可视化工具 Gephi
    R中library和require的区别
    python BeautifulSoup解决中文乱码问题
    【转载】MySQL全文检索笔记
    poj 1011
    Nest,很酷的东西
    H.264开源解码器评测
  • 原文地址:https://www.cnblogs.com/NJUWZ/p/7050594.html
Copyright © 2011-2022 走看看