Guest User

Untitled

a guest
Dec 14th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. /*
  2. A tree needs more than 10000 nodes to use the 7th color */
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <vector>
  6.  
  7. using namespace std;
  8. const int N = 1e4+5;
  9. const int M = 6;
  10. const int INF = 0x3f3f3f3f;
  11.  
  12. int n, dp[N][M+5];
  13. vector<int> g[N];
  14.  
  15. bool get () {
  16.  
  17. char s[N*M];
  18. gets(s);
  19.  
  20. if (s[0] == '\0') return false;
  21.  
  22. int len = strlen(s), i = 0;
  23.  
  24. int u = -1, v = -1;
  25. while (s[i] < '0' && s[i] > '9') i++;
  26.  
  27. for (; s[i] != ':'; i++) {
  28. if (u == -1) u = s[i] - '0';
  29. else u = u * 10 + s[i] - '0';
  30. }
  31.  
  32. for (; i <= len; i++) {
  33. if (s[i] >= '0' && s[i] <= '9') {
  34. if (v == -1) v = s[i] - '0';
  35. else v = v * 10 + s[i] - '0';
  36. } else {
  37. if (v != -1) {
  38. g[u].push_back(v);
  39. g[v].push_back(u);
  40. v = -1;
  41. }
  42. }
  43. }
  44.  
  45. return true;
  46. }
  47.  
  48. void dfs (int u, int f) { ///(cur_node,prev_node)
  49. for (int i = 1; i <= M; i++)
  50. dp[u][i] = i;
  51.  
  52. for (int i = 0; i < g[u].size(); i++) {
  53.  
  54. int v = g[u][i];
  55. if (v == f) continue;
  56.  
  57. dfs(v, u);
  58. /**Basically since x,y are colors, the condition if(x==y) signify that no two connected nodes can
  59. have same color, and what we are doing in the nested for loops is that if we choose to color parent
  60. node with 'x' then what is the minimum color we can assign to the children is the cur, so
  61. dp[u][x]+=cur (i.e. dp[u][x] is containing the minimum sum of colors of the parent and all its children when the parent u
  62. is colored x)**/
  63. for (int x = 1; x <= M; x++) {
  64. int cur = INF;
  65. for (int y = 1; y <= M; y++) {
  66. if (x == y) continue;
  67. cur = min(cur, dp[v][y]);
  68. }
  69. dp[u][x] += cur;
  70. }
  71. }
  72. }
  73.  
  74. int main () {
  75. while (scanf("%d%*c", &n), n) {
  76. for (int i = 0; i < n; i++)
  77. g[i].clear();
  78.  
  79. while (get()) ;
  80.  
  81. dfs(0, -1);
  82. int ans = INF;
  83. for (int i = 1; i <= M; i++)
  84. ans = min(ans, dp[0][i]);
  85. printf("%d\n", ans);
  86. }
  87. return 0;
  88. }
Add Comment
Please, Sign In to add comment