1852. Ordered Fractions

单点时限: 2.0 sec

内存限制: 256 MB

Consider the set of all reduced fractions between 0 and 1 inclusive with denominators less than or equal to .

Here is the set when :

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 between and inclusive, prints the fractions in order of increasing magnitude.

输入格式
One line with a single integer .

输出格式
One fraction per line, sorted in order of magnitude.

样例
input
5
output
0/1
1/5
1/4
1/3
2/5
1/2
3/5
2/3
3/4
4/5
1/1

/*
思路:sort+set
*/
#include<iostream>
#include<algorithm>
#include<set>
#define Pair pair<int,int>
using namespace std;
struct g {
	int x,y;
	friend bool operator <(g a,g b) {
		return a.x*b.y<a.y*b.x;
	}
};
int main() {
	int n;
	cin>>n;
	g G[n*n];
	int index=0;
	set<g>s;
	for(int i  = 1; i <= n; i++) {
		for(int j = 1; j < i; j++) {
			g m;
			int gcd=__gcd(i,j);
			m.x=j/gcd;
			m.y=i/gcd;
			s.insert(m);
		}
	}
	cout<<"0/1"<<endl;
	for(auto it=s.begin();it!=s.end(); it++)
		cout<<(*it).x<<"/"<<(*it).y<<endl;
	cout<<"1/1";
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40394960/article/details/105903478