记录编号 499228 评测结果 AAAAAAAAAAAAA
题目名称 [USACO Hol10] 政党 最终得分 100
用户昵称 Gravatar@@@ 是否通过 通过
代码语言 C++ 运行时间 1.221 s
提交时间 2018-07-01 17:40:35 内存使用 96.07 MiB
显示代码纯文本
  1. #include<iostream>
  2. #include "cstdio"
  3. #include <vector>
  4. #include <cmath>
  5. #include <queue>
  6. using namespace std;
  7. int n,k,N;
  8. int deep[200001];
  9. int mapa = 0;
  10. std::vector<int> e[200001],party[100001];
  11. int grand[200001][60],gw[200001][60];
  12. //void dfs(int r)
  13. //{
  14. // for (int i = 1; i <= N; ++i)
  15. // grand[r][i] = grand[grand[r][i-1]][i-1];
  16. // for (int i = 0; i < e[r].size(); ++i)
  17. // if(e[r][i] != grand[r][0])
  18. // {
  19. // deep[e[r][i]] = deep[r]+1;
  20. // dfs(e[r][i]);
  21. // }
  22. //}
  23. queue<int> q;
  24. void bfs(int r)
  25. {
  26. q.push(r);
  27. while(!q.empty())
  28. {
  29. int h = q.front();
  30. q.pop();
  31. for (int i = 1; (1<<i) <= deep[h]; ++i)
  32. grand[h][i] = grand[grand[h][i-1]][i-1];
  33. for (int i = 0; i < e[h].size(); ++i)
  34. {
  35. if(e[h][i] != grand[h][0])
  36. {
  37. deep[e[h][i]] = deep[h]+1;
  38. q.push(e[h][i]);
  39. }
  40. }
  41. }
  42. }
  43. int lca(int x,int y)
  44. {
  45. int ans = 0;
  46. if(deep[x] > deep[y])
  47. swap(x,y);
  48. for (int i = N; i >= 0; --i)
  49. if (deep[x]<deep[y]&&grand[y][i]&&deep[grand[y][i]] >= deep[x])
  50. {
  51. y = grand[y][i];
  52. ans+=(1<<i);
  53. }
  54. if(x == y)
  55. return ans;
  56. for (int i = N; i >= 0; --i)
  57. if (grand[x][i]!=grand[y][i])
  58. {
  59. ans+= 2*(1<<i);
  60. x = grand[x][i];y = grand[y][i];
  61. }
  62. if (x != y)
  63. ans+=2;
  64. return ans;
  65. }
  66. int main()
  67. {
  68.  
  69. int start;
  70. freopen("cowpol.in","r",stdin);
  71. freopen("cowpol.out","w",stdout);
  72. cin >> n >> k;
  73. N = floor(log(n + 0.0) / log(2.0));
  74. for (int i = 1; i <= n; ++i)
  75. {
  76. int t;
  77. cin >> t >> grand[i][0];
  78. if (grand[i][0] == 0)
  79. start = i;
  80. party[t].push_back(i);
  81. e[i].push_back(grand[i][0]);
  82. e[grand[i][0]].push_back(i);
  83. }
  84. int nkanscanc;
  85. bfs(start);
  86. for (int i = 1; i <= k; ++i)
  87. {
  88. int deeep = 0,jb,ans = 0;
  89. for (int j = 0; j < party[i].size(); ++j)
  90. if(deeep<deep[party[i][j]])
  91. {
  92. deeep = deep[party[i][j]];
  93. jb = party[i][j];
  94. }
  95. for (int j = 0; j < party[i].size(); ++j)
  96. ans = max(ans,lca(jb,party[i][j]));
  97. cout << ans << endl;
  98. }
  99. return 0;
  100. }