【LOJ6413】「ICPC World Finals 2018」无线光纤

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39972971/article/details/88715023

【题目链接】

【思路要点】

  • 首先,若 M = N 1 M=N-1 ,那么直接输出原图即可。
  • 否则,必然会有一个点度数不同,考虑贪心,尽可能将度为 1 1 的点连向度不为 1 1 ,且度数最小的点,制造更多度为 1 1 的点。
  • 若不存在度为 1 1 的点,则选取度最大的点当做度为 1 1 的点,连向度数最小的点。
  • 使用 T w o P o i n t e r s TwoPointers 进行模拟即可。
  • 需要排序,时间复杂度 O ( N L o g N + M ) O(NLogN+M)

【代码】

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 2e5 + 5;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
template <typename T> void chkmax(T &x, T y) {x = max(x, y); }
template <typename T> void chkmin(T &x, T y) {x = min(x, y); } 
template <typename T> void read(T &x) {
	x = 0; int f = 1;
	char c = getchar();
	for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
	for (; isdigit(c); c = getchar()) x = x * 10 + c - '0';
	x *= f;
}
template <typename T> void write(T x) {
	if (x < 0) x = -x, putchar('-');
	if (x > 9) write(x / 10);
	putchar(x % 10 + '0');
}
template <typename T> void writeln(T x) {
	write(x);
	puts("");
}
int n, m, res, d[MAXN], a[MAXN];
vector <pair <int, int>> ans;
int main() {
	read(n), read(m);
	if (m == n - 1) {
		printf("%d\n%d %d\n", 0, n, n - 1);
		for (int i = 1; i <= m; i++) {
			int x, y; read(x), read(y);
			printf("%d %d\n", x, y);
		}
		return 0;
	}
	for (int i = 1; i <= m; i++) {
		int x, y; read(x), read(y);
		d[x]++, d[y]++;
	}
	for (int i = 1; i <= n; i++)
		a[i] = i - 1;
	sort(a + 1, a + n + 1, [&] (int x, int y) {return d[x] < d[y]; });
	int j = 1, k = n;
	for (int i = 1; i < k; i++) {
		while (d[a[j]] <= 1) j++;
		if (d[a[i]] == 1) {
			d[a[i]]--, d[a[j]]--;
			ans.emplace_back(a[i], a[j]);
			if (i + 1 == k) res++;
		} else {
			d[a[i]]--, d[a[k]]--, res++;
			ans.emplace_back(a[i], a[k]);
			if (i + 1 == k) res++; k--, i--;
		}
	}
	printf("%d\n%d %d\n", res, n, n - 1);
	for (auto x : ans) printf("%d %d\n", x.first, x.second);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39972971/article/details/88715023