fork(2) download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define sz 200100
  4. #define MOD 1000000007
  5. #define ll long long
  6. unordered_map<int, int>um;
  7. int cnt[sz];
  8. vector<int> adj[sz];
  9. int tin[sz];
  10. int tout[sz];
  11. int tim;
  12. int par[20][sz];
  13. int dep[sz];
  14. void dfs(int s, int p)
  15. {
  16. par[0][s] = p;
  17. dep[s] = dep[p] + 1;
  18. tin[s] = tim++;
  19. for (auto it : adj[s])
  20. {
  21. if (it != p)
  22. dfs(it, s);
  23. }
  24. tout[s] = tim++;
  25. }
  26. void pre(int n)
  27. {
  28. for (int i = 1; i < 20; i++)
  29. {
  30. for (int j = 1; j <= n; j++)
  31. {
  32. if (par[i - 1][j] != -1)
  33. par[i][j] = par[i - 1][par[i - 1][j]];
  34. }
  35. }
  36. }
  37. int lca(int u, int v)
  38. {
  39. if (dep[u] > dep[v])
  40. swap(u, v);
  41. for (int i = 0; i < 20; i++)
  42. {
  43. if (((dep[v] - dep[u]) >> i) & 1)
  44. v = par[i][v];
  45. }
  46. if (u == v)
  47. return u;
  48. for (int i = 19; i > -1; i--)
  49. {
  50. if (par[i][u] != par[i][v])
  51. {
  52. u = par[i][u];
  53. v = par[i][v];
  54. }
  55. }
  56. return par[0][u];
  57. }
  58. int calc(int s, int p)
  59. {
  60. cnt[s] = um[s];
  61. for (auto it : adj[s])
  62. {
  63. if (it != p)
  64. cnt[s] += calc(it, s);
  65. }
  66. return cnt[s];
  67. }
  68. int main()
  69. {
  70. ios::sync_with_stdio(0);
  71. cin.tie(0); cout.tie(0);
  72. int n, m, a, b; cin >> n >> m;
  73. for (int i = 0; i < n - 1; i++)
  74. {
  75. cin >> a >> b;
  76. adj[a].push_back(b);
  77. adj[b].push_back(a);
  78. }
  79. memset(par, -1, sizeof(par));
  80. dfs(1, 0);
  81. par[0][1] = -1;
  82. pre(n);
  83. unordered_map<int, int>forlca;
  84. while (m--)
  85. {
  86. cin >> a >> b;
  87. int l = lca(a, b);
  88. um[l] -= 2;
  89. um[a] += 1;
  90. um[b] += 1;
  91. forlca[l]++;
  92. }
  93. calc(1, 0);
  94. for (int i = 1; i <= n; i++)
  95. cout << cnt[i] + forlca[i] << " ";
  96. return 0;
  97. }
Success #stdin #stdout 0.01s 23788KB
stdin
5 3
1 2
1 3
3 4
3 5
1 3
2 5
1 4

3 1 3 1 1
stdout
3 1 3 1 1