就是一个简单的树形DP啦~但是问题是到底要几种颜色
我一开始写了25中颜色交上去,发现好慢啊。。。于是做了个死改成了三种交了上去竟然过了。。。过了。。。(要知道2种颜色肯定是不对的啊。。。)
1 /************************************************************** 2 Problem: 1369 3 User: rausen 4 Language: C++ 5 Result: Accepted 6 Time:12 ms 7 Memory:1820 kb 8 ****************************************************************/ 9 10 #include <cstdio> 11 #include <algorithm> 12 13 using namespace std; 14 const int N = 1e4 + 5; 15 const int inf = 1e9; 16 const int C = 3; 17 18 struct edge { 19 int next, to; 20 edge() {} 21 edge(int _n, int _t) : next(_n), to(_t) {} 22 } e[N << 1]; 23 24 int n, ans; 25 int first[N], tot; 26 int f[N][21]; 27 28 inline int read() { 29 int x = 0; 30 char ch = getchar(); 31 while (ch < '0' || '9' < ch) 32 ch = getchar(); 33 while ('0' <= ch && ch <= '9') { 34 x = x * 10 + ch - '0'; 35 ch = getchar(); 36 } 37 return x; 38 } 39 40 41 inline void Add_Edges(int x, int y) { 42 e[++tot] = edge(first[x], y), first[x] = tot; 43 e[++tot] = edge(first[y], x), first[y] = tot; 44 } 45 46 #define y e[x].to 47 void work(int p, int fa) { 48 int x, i, j, mn; 49 for (i = 1; i <= C; ++i) f[p][i] = i; 50 for (x = first[p]; x; x = e[x].next) 51 if (y != fa) work(y, p); 52 for (i = 1; i <= C; ++i) { 53 for (x = first[p]; x; x = e[x].next) 54 if (y != fa) { 55 for (j = 1, mn = inf; j <= C; ++j) 56 if (i != j) mn = min(mn, f[y][j]); 57 f[p][i] += mn; 58 } 59 } 60 } 61 #undef y 62 63 int main() { 64 int i; 65 n = read(); 66 for (i = 1; i < n; ++i) 67 Add_Edges(read(), read()); 68 work(1, 0); 69 for (i = 1, ans = inf; i <= C; ++i) 70 ans = min(ans, f[1][i]); 71 printf("%d\n", ans); 72 return 0; 73 }
By Xs酱~ 转载请说明
博客地址:http://www.cnblogs.com/rausen