USACO [2.1] Ordered Fractions

Ordered Fractions

Consider the set of all reduced fractions between 0 and 1 inclusivewith 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
题好水。。暴力就可以过。本来还以为需要什么优化的。

思路:三重循环,第一重用来枚举分母,第二重枚举分子,第三重用来判断是否已经出现过分数值。

wa了一次原因是不能用记录的double去比较而应该用除法判断(没能做到去重)

<span style="color:#000000;">/*
ID: shhyzzu
PROG: frac1
LANG: C++
*/
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<cmath>
#include<iomanip>
using namespace std;
int n,countt=0;
struct node
{
    int up;
    int down;
    double val;
}a[30000];
bool mycmp(node a,node b){return a.val<b.val;}
void init()
{
    scanf("%d",&n);
}
void work()
{
    for(int j=1;j<=n;j++)//分母
    {
        for(int i=0;i<=j;i++)//分子
        {
            bool flag=false;
            for(int k=1;k<=countt;k++)
            {
                if((double)i/j==(double)a[k].up/a[k].down)//这里本来打算直接调用val的结果并不能判断重复,就改成除法了
                {
                    flag=true;
                    break;
                }
            }
            if(!flag)
            {
                a[++countt].val=(double)i/j;
                a[countt].up=i;
                a[countt].down=j;
            }

        }
    }
    //cout<<countt<<endl;
    sort(a+1,a+countt+1,mycmp);
    for(int i=1;i<=countt;i++)
    {
        //cout<<a[i].val<<' ';
        printf("%d/%d\n",a[i].up,a[i].down);
    }
}
int main()
{
    freopen("frac1.in","r",stdin);
    freopen("frac1.out","w",stdout);
    init();
    work();
    return 0;
}</span>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值