Codeforces Round #547 (Div. 3) G. Privatization of Roads in Treeland
二分找出r的大小,然后dfs对图染色。
#include "bits/stdc++.h" using namespace std; const int maxn = 2e5 + 100; int n, k; int ans[maxn]; int cnt[maxn]; int l, r, mid; vector<pair<int, int> > e[maxn]; int vis[maxn]; bool check(int num) { int ret = 0; for (int i = 1; i <= n; i++) { if (cnt[i] > num) ret++; } return ret <= k; } void dfs(int now, int fa, int facolor) { int co = 1; if (co == facolor) co++; bool flag = (cnt[now] <= r); for (auto p:e[now]) { if (p.first != fa) { if (flag) ans[p.second] = co++; else ans[p.second] = 1; dfs(p.first, now, ans[p.second]); if (co == facolor) co++; } } } int main() { // freopen("input.txt", "r", stdin); cin >> n >> k; int a, b; for (int i = 1; i < n; i++) { cin >> a >> b; e[a].push_back(make_pair(b, i)); e[b].push_back(make_pair(a, i)); cnt[a]++; cnt[b]++; } l = 1, r = n - 1; while (l < r) { mid = (l + r) >> 1; if (check(mid)) { r = mid; } else { l = mid + 1; } } dfs(1, 0, 0); cout << r << endl; int space = 0; for (int i = 1; i < n; i++) { if (space) cout << " "; space = 1; cout << ans[i]; } cout << endl; return 0; }