USACO-Section2.1 Ordered Fractions(简单数据处理)

2017-8-6

题目描述

按分数值递增的顺序输出所有解

解答

求出所有情况再排序即可

代码

/*
ID: 18795871
PROG: frac1
LANG: C++
*/
#include<iostream>
#include<cstring>
#include<fstream>
#include<cstdlib>
using namespace std;
const int N = 10000;

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

int n;
struct fs{
    int x,y;
}s[N+1];

int cmp(const void *a,const void *b){
    struct fs *k1=(struct fs *)a;
    struct fs *k2=(struct fs *)b;
    return k1->x*k2->y-k1->y*k2->x;
}

int res(int p,int q){
    int r;
    while (q){
        r=p%q;
        p=q;
        q=r;
    }
    return p;
}

int main()
{
    int i,j,k;
    fin>>n;
    k=0;
    for (i=1;i<=n;i++){
        for (j=0;j<=i;j++){
            if (res(i,j)==1){
                s[k].x=j;
                s[k].y=i;
                k++;
            }
        }
    }
    qsort(s,k,sizeof(s[0]),cmp);
    for (i=0;i<k;i++){
        fout<<s[i].x<<"/"<<s[i].y<<endl;
    }
    return 0;
}

为了避免重复,应该把最大公约数不为1的给去掉,因为约去之后会发现我们已经有了,上面我是在cmp函数里面进行通分然后再排序的,或者你也可以将其计算出来然后再进行排序。

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

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

const int N = 160;
int n;

struct fs{
    int a,b;
    double p;
}x[N*N+1];

bool cmp(struct fs a,struct fs b){
    return a.p<b.p;
}

bool gcd(int i,int j){
    while (j){
        int t=i%j;
        i=j;
        j=t;
    }
    if (i==1) return true;
    return false;
}

int main(){
    int cnt=0;
    while (fin>>n){
        for (int i=0;i<=n;i++){
            for (int j=i+1;j<=n;j++){
                if (gcd(i,j)){
                    x[cnt].a=i;x[cnt].b=j;x[cnt].p=1.0*i/j;
                    cnt++;
                }
            }
        }
        sort(x,x+cnt,cmp);
        for (int i=0;i<cnt;i++){
            fout<<x[i].a<<"/"<<x[i].b<<endl;
        }
        fout<<1<<"/"<<1<<endl;
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值