【枚举】(零散刷题记录)

P1458 [USACO2.1]顺序的分数 Ordered Fractions

题目链接:P1458 [USACO2.1]顺序的分数 Ordered Fractions - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

枚举+排序:

#include 
#include 
using namespace std;

int gcd(int x, int y) {
	if (x % y == 0) {
		return y;
	} else {
		return gcd(y, x % y);
	}
}

struct P {
	int x, y;
	double val;
} a[10000];

bool cmp(P p1, P p2) {
	return p1.val < p2.val;
}

int main() {
	int n, cnt = 0;
	cin >> n;
	cout << "0/1" << endl;
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= i; j++) {
			if (gcd(i, j) == 1) {
				cnt++;
				a[cnt].x = i;
				a[cnt].y = j;
				a[cnt].val = j * 1.0 / i;
			}
		}
	}
	sort(a + 1, a + 1 + cnt, cmp);
	for (int i = 1; i <= cnt; i++) {
		cout << a[i].y << '/' << a[i].x << endl;
	}
	return 0;
}

 

你可能感兴趣的:(洛谷,c++,算法)