2021-01-07 USACO Ordered Fractions

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.

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

亏我还想了半天用图论怎么做,结果换个脑子一想这个数据范围干嘛不打暴力。。。。不明白为什么USACO官方要把这题放在Chapter2

/*
ID: traysen1
TASK: frac1
LANG: C++
*/
#include <bits/stdc++.h>
using namespace std;

struct Fraction {
	int x, y;
	
	bool operator < (const Fraction& fr) const {
		return x * fr.y < fr.x * y;
	}
}frac[160 * 160];
int num, N;

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

int main() {
	ifstream fin("frac1.in");
	fin >> N;
	fin.close();
	
	//Generate fractions: x/y
	frac[num++] = {0, 1};
	
	for (int y = 1; y <= N; y++)
		for (int x = 1; x <= y; x++)
			if (gcd(x, y) == 1) {
				Fraction fr = {x, y};
				frac[num++] = fr;
			}
	
	sort(frac, frac + num);
	
	ofstream fout("frac1.out");
	for (int i = 0; i < num; i++)
		fout << frac[i].x << "/" << frac[i].y << endl;
	fout.close();
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值