USACO [2.1] Ordered Fractions

来源:互联网 发布:历史软件有哪些 编辑:程序博客网 时间:2024/04/29 17:08

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/11/51/41/32/51/23/52/33/44/51/1
题好水。。暴力就可以过。本来还以为需要什么优化的。

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

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

<span style="color:#000000;">/*ID: shhyzzuPROG: frac1LANG: 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
原创粉丝点击