85求调,WA17,27,28,29
查看原帖
85求调,WA17,27,28,29
1019606
KouMoSir楼主2023/9/30 13:41
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<queue>
using namespace std;
typedef pair<int, int> ii;
const int N = 1e6 + 10;
int h[2 * N], to[2 * N], nxt[2 * N], used[N], d[N], n, ind, sum;
ii c[N];
bool cmp(ii a, ii b) {
	return a.second > b.second;
}
void append(int a, int b) {
	nxt[++ind] = h[a];
	h[a] = ind;
	to[ind] = b;
}
void bfs(int b) {
	queue<int> con;
	con.push(b);
	used[b] = 1;
	while (!con.empty()) {
		int tmp = h[con.front()];
		c[b] = ii(b, 1);
		while (tmp) {
			if (used[to[tmp]]) {
				tmp = nxt[tmp];
				continue;
			}
			used[to[tmp]] = 1;
			con.push(to[tmp]);
			c[to[tmp]] = ii(to[tmp], c[con.front()].second + 1);
			tmp = nxt[tmp];
		}
		con.pop();
	}
}
int main() {
	cin >> n;
	for (int i = 1; i < n; i++) {
		int a, b;
		cin >> a >> b;
		append(a, b);
		append(b, a);
	}
	bfs(1);
	sort(c + 1, c + 1 + n, cmp);
	for (int i = 1; i <= n; i++) sum += c[i].second;
	int le = sum / 2;
	if (sum % 2 == 1) {
		cout << -1;
		return 0;
	}
	for (int i = 1; i <= n; i++) {
		if (c[i].second <= le) {
			d[c[i].first] = 1;
			le -= c[i].second;
		}
	}
	if (le != 0) {
		cout << -1;
		return 0;
	}
	for (int i = 1; i <= n; i++)cout << d[i] << " ";
}

思路就是链式前进星建图,然后从1开始广度优先搜索,得到每个点到1的最短路径(长度),然后用贪心寻找是否存在一个方案使得黑白权值相等

2023/9/30 13:41
加载中...