USACO——Ordered Fractions

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
思路:枚举各种可能化简后放入set容器中输出即可



/*
ID: youqihe1
PROG: frac1
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
#include <set>
using namespace std;
int gcd(int a,int b)
{
    return b==0?a:gcd(b,a%b);
}
struct fraction
{
    int chi;
    int mom;
    float val;
    bool operator <(const fraction &A)const
    {
        return val<A.val;
    }
};
int main() {
    FILE *fin  = fopen ("frac1.in", "r");
    FILE *fout = fopen ("frac1.out", "w");
    int n;
    fscanf(fin,"%d",&n);
    int i,j,k;
    set<fraction>A;
    for(i=0;i<=n;i++)
    {
        for(j=i+1;j<=n;j++)
        {
            int a=gcd(i,j);
            fraction fra;
            fra.chi=i/a;
            fra.mom=j/a;
            fra.val=(float(fra.chi))/(float(fra.mom));
            A.insert(fra);
        }
    }
    set<fraction>::iterator it;
    for(it=A.begin();it!=A.end();it++)
    {
        fprintf(fout,"%d/%d\n",it->chi,it->mom);
    }
    fprintf(fout,"1/1\n");
    return 0;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值