782C. Andryusha and Colored Balloons DFS
题意: 给出一棵树,要求为其染色,并且使任意节点都不与距离2以下的节点颜色相同
思路: 直接DFS。由某节点出发的DFS序列,对于其个儿子的cnt数+1,那么因为DFS遍历的性质可保证兄弟结点的颜色不同,只需考虑当前节点是否与父亲结点和父亲的父亲结点颜色是否相同。
/** @Date : 2017-05-09 22:37:25 * @FileName: 782C DFS.cpp * @Platform: Windows * @Author : Lweleth (SoundEarlf@gmail.com) * @Link : https://github.com/Lweleth * @Version : $Id$ */ #include <bits/stdc++.h> #define LL long long #define PII pair #define MP(x, y) make_pair((x),(y)) #define fi first #define se second #define PB(x) push_back((x)) #define MMG(x) memset((x), -1,sizeof(x)) #define MMF(x) memset((x),0,sizeof(x)) #define MMI(x) memset((x), INF, sizeof(x)) using namespace std; const int INF = 0x3f3f3f3f; const int N = 1e5+20; const double eps = 1e-8; vectorvt[2*N]; int ans[2*N]; int n, ma; int dfs(int x, int pre) { int l = vt[x].size(); int c = 0; for(int i = 0; i < l; i++) { int nw = vt[x][i]; if(ans[nw] || nw == pre) continue; c++; while(c == ans[pre] || c == ans[x]) c++; ans[nw] = c; ma = max(c, ma); dfs(nw, x); } } int main() { while(cin >> n) { MMF(ans); for(int i = 0; i <= n; i++) vt[i].clear(); for(int i = 0; i < n - 1; i++) { int x, y; scanf("%d%d", &x, &y); vt[x].PB(y); vt[y].PB(x); } ma = 0; ans[1] = 1; dfs(1, 1); printf("%d\n", ma); for(int i = 1; i <= n; i++) printf("%d%s", ans[i], i==n?"\n":" "); } return 0; }