USACO有序分数

给定一个整数 N,请你求出所有分母小于或等于 N,大小在 [0,1] 范围内的最简分数,并按从小到大顺序依次输出。

例如,当 N=5 时,所有满足条件的分数按顺序依次为:

0/1,1/5,1/4,1/3,2/5,1/2,3/5,2/3,3/4,4/5,1/1

输入格式
共一行,包含一个整数 N。

输出格式
按照从小到大的顺序,输出所有满足条件的分数。

每个分数占一行,格式为 a/b,其中 a 为分子, b 为分母。

数据范围
1≤N≤160
输入样例:
5
输出样例:
0/1
1/5
1/4
1/3
2/5
1/2
3/5
2/3
3/4
4/5
1/1
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

int n;

void dfs(int a, int b, int c, int d)
{
    if (b + d > n) return;
    dfs(a, b, a + c, b + d);
    printf("%d/%d\n", a + c, b + d);
    dfs(a + c, b + d, c, d);
}

int main()
{
    cin >> n;
    puts("0/1");
    dfs(0, 1, 1, 1);
    puts("1/1");
    return 0;
}

#include<cstdio>
#include<algorithm>
#include<vector>

using namespace std;

struct Node{
    int up, down;
    bool operator< (const struct Node &T) const {
        return up * T.down < T.up * down;
    }
};

vector<Node> v;

int gcd(int a, int b)
{
    return b ? gcd(b, a % b) : a;
}

int main()
{
    int n;
    scanf("%d", &n);
    for(int down = 1; down <= n; down ++)
        for(int up = 0; up <= down; up ++)
            if(gcd(up, down) == 1)  v.push_back({up, down});

    sort(v.begin(), v.end());//按照值从小到大排序
    for(auto &p : v)  printf("%d/%d\n", p.up, p.down);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小王子y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值