ordered fractions_usaco2.1.2_codevs2042

53 篇文章 0 订阅
52 篇文章 0 订阅

DESCRIPTION

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.

OUTPUT FORMAT

One fraction per line, sorted in order of magnitude.

题意

给定n,求分母不大于n的所有真分数,从小到大输出

题解

双重枚举分子分母,同时算出分数值,排序去重然后输出,注意分子分母化简

代码

/*
ID:wjp13241
PROG:frac1
LANG:C++
*/

#include <stdio.h>
#include <algorithm>

using namespace std;

struct frac
{
    int x,y;
    double v;
};

frac f[13001];

bool cmp(frac x,frac y)
{
    return x.v<y.v;
}

int gcd(int x,int y)
{
    return !y?x:gcd(y,x%y);
}

int main()
{
    freopen("frac1.in","r",stdin);
    freopen("frac1.out","w",stdout);

    int n,count=0;
    scanf("%d",&n);

    for (int i=1;i<=n;i++)
        for (int j=0;j<=i;j++)
        {
            int tmp=gcd(i,j);
            f[++count]=(frac){i/tmp,j/tmp,(double)(j)/(double)(i)};
        }
    sort(f+1,f+count+1,cmp);

    int i=0;
    while (++i<=count)
    {
        while(f[i].v==f[i+1].v&&i<count)
            i++;
        printf("%d/%d\n",f[i].y,f[i].x);
    }

    fclose(stdin);
    fclose(stdout);

    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值