fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const long long MaxN = 1e6;
  5.  
  6. long long n;
  7. vector<long long> a[MaxN+5];
  8. bool visited[MaxN+5];
  9. long long depth[MaxN+5],color[MaxN+5];
  10. string s;
  11.  
  12. void input()
  13. {
  14. cin >> n >> s;
  15.  
  16. s=" "+s;
  17.  
  18. for(long long i=1;i<=n;i++)
  19. {
  20. if(s[i]=='1')
  21. {
  22. color[i]=-1;
  23. }
  24. else
  25. {
  26. color[i]=1;
  27. }
  28. }
  29.  
  30. for(long long i=1;i<=n-1;i++)
  31. {
  32. long long u,v;
  33. cin >> u >> v;
  34. a[u].push_back(v);
  35. a[v].push_back(u);
  36. }
  37. }
  38.  
  39. void dfs(long long i,vector<long long> a[],bool visited[],long long depth[],long long color[])
  40. {
  41. stack<long long> st;
  42.  
  43. st.push(i);
  44. visited[i]=true;
  45. depth[i]=color[i];
  46.  
  47. while(!st.empty())
  48. {
  49. long long u=st.top();
  50. st.pop();
  51.  
  52. for(long long v:a[u])
  53. {
  54. if(!visited[v])
  55. {
  56. visited[v]=true;
  57. depth[v]=depth[u]+color[v];
  58. st.push(v);
  59. }
  60. }
  61. }
  62. }
  63.  
  64. void solve()
  65. {
  66. memset(visited,false,sizeof(visited));
  67. memset(depth,0,sizeof(depth));
  68.  
  69. dfs(1,a,visited,depth,color);
  70.  
  71. long long res=0;
  72.  
  73. for(long long i=1;i<=n;i++)
  74. {
  75. if(depth[i]>0)
  76. {
  77. res++;
  78. }
  79. }
  80.  
  81. cout << res;
  82. }
  83.  
  84. int main()
  85. {
  86. ios_base::sync_with_stdio(0);
  87. cin.tie(0);
  88.  
  89. input();
  90. solve();
  91. }
Success #stdin #stdout 0.01s 37032KB
stdin
Standard input is empty
stdout
Standard output is empty