USACO Training 2.1 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

Compiling...
Compile: OK

Executing...
   Test 1: TEST OK [0.004 secs limit:1s, 1740 KB]
   Test 2: TEST OK [0.007 secs limit:1s, 1704 KB]
   Test 3: TEST OK [0.007 secs limit:1s, 1724 KB]
   Test 4: TEST OK [0.007 secs limit:1s, 1688 KB]
   Test 5: TEST OK [0.007 secs limit:1s, 1676 KB]
   Test 6: TEST OK [0.011 secs limit:1s, 1716 KB]
   Test 7: TEST OK [0.011 secs limit:1s, 1744 KB]
   Test 8: TEST OK [0.028 secs limit:1s, 1780 KB]
   Test 9: TEST OK [0.074 secs limit:1s, 1736 KB]
   Test 10: TEST OK [0.119 secs limit:1s, 1716 KB]
   Test 11: TEST OK [0.308 secs limit:1s, 1684 KB]

All tests OK.
YOUR PROGRAM ('frac1') WORKED FIRST TIME!  That's fantastic
-- and a rare thing.  Please accept these special automated
congratulations.
那么接下来看代码
/*
ID: choiyin1
TASK:frac1
LANG:C++
*/
#include <bits/stdc++.h> 
using namespace std;
int n, bt;
struct PII
{
	int f, s;
}b[7810];
 
inline bool operator < (PII A, PII B)
{
	return ((double)A.f/(double)A.s) < ((double)B.f/(double)B.s);
}
inline int gcd(int x, int y)
{
	int tmp;
	do{
		tmp = x % y;
		x = y;
		y = tmp;	
	}while(tmp);
	return x;	
}
int main(){
	freopen("frac1.in", "r", stdin);
	freopen("frac1.out", "w", stdout); 
	cin >> n;
	for (int i = 2; i <= n; ++ i)
		for (int j = 1; j < i; ++ j)
			if (gcd(i, j) == 1)	
			{
				++ bt;
				b[bt].f = j;
				b[bt].s = i;	
			}
	sort(b + 1, b + 1 + bt);
	cout<<"0/1"<<endl;
	for (int i = 1; i <= bt; ++ i)	cout<<b[i].f<<"/"<<b[i].s<<endl;
	cout<<"1/1"<<endl; 
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值