USACO-2.1.2- Ordered Fractions

题目链接
题目大意
给定一个数字N,按照从小到大的顺序输出所有分母小于等于N的,小于1的真分数。
样例输入

样例输出
0/1
1/5
1/4
1/3
2/5
1/2
3/5
2/3
3/4
4/5
1/1

解题思路
这道题的规模很小,可以直接遍历找出所有的分母小于等于N的真分数,排序后输出。
代码

/*
ID: 
LANG: C++
PROG: frac1
*/
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;

struct frac
{
        int num, den;
};

bool coprime(int i, int j)
{
        while( i % j != 0 )
        {
                int t = i % j;
                i = j;
                j = t;
        }
        if(j == 1)
                return 1;
        else
                return 0;
}

bool fraccmp(const frac &a, const frac &b)
{
        int val1, val2;
        val1 = a.num * b.den;
        val2 = a.den * b.num;
        return (val1 < val2);
}

int main()
{
        ifstream fin("frac1.in");
        ofstream fout("frac1.out");

        int n;
        struct frac ans[40000];
        int count = 0;
        fin >> n;

        for(int i = 2; i <= n; ++i)
        {
                for(int j = 1; j < i; ++j)
                {
                        if( coprime(i, j) )
                        {
                                ans[count].num = j;
                                ans[count].den = i;
                                ++count;
                        }
                }
        }

        sort(ans, ans + count, fraccmp);
        fout << "0/1" << endl;
        for(int i = 0; i < count; ++i)
        {
                fout << ans[i].num << '/' << ans[i].den << endl;
        }
        fout << "1/1" << endl;
        return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值