Advertisement
a53

f_l_o_r_i_4

a53
Jul 22nd, 2018
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <utility>
  4. #define fi first
  5. #define se second
  6. using namespace std;
  7. const int MAXN=200005;
  8.  
  9. int n,a[MAXN],b[MAXN];
  10. vector<pair<int,int>> g[MAXN];
  11.  
  12. int c,f;
  13. short used[MAXN];
  14. long long res,tmp,sum;
  15. long long sub[MAXN],all[MAXN];
  16.  
  17. void Init()
  18. {
  19. ios::sync_with_stdio(false);
  20. cin.tie(NULL);cout.tie(NULL);
  21. cin>>n;
  22. char x;
  23. for(int i=1;i<=n;++i)
  24. cin>>x,a[i]=x-'a'+1;
  25. for(int i=1;i<=n;++i)
  26. cin>>b[i];
  27. int u,v,w;
  28. for(int i=1;i<n;++i)
  29. cin>>u>>v>>w,g[u].emplace_back(v, w),g[v].emplace_back(u, w);
  30. }
  31.  
  32. void toZero()
  33. {
  34. res=1ll<<60;
  35. sum=0;
  36. for(int i=1;i<=n;++i)
  37. used[i]=0,sub[i]=all[i]=0;
  38. }
  39.  
  40. void DFS(int u)
  41. {
  42. used[u]=f;
  43. if(f==1&&a[u]==c)
  44. sum+=b[u],sub[u]+=b[u];
  45. if(f==2)
  46. res=min(res,tmp);
  47. for(auto v:g[u])
  48. {
  49. if(used[v.fi]!=f)
  50. {
  51. if(f==1)
  52. DFS(v.fi),all[u]+=all[v.fi],all[u]+=sub[v.fi]*v.se,sub[u]+=sub[v.fi];
  53. if(f==2)
  54. tmp-=sub[v.fi]*v.se,tmp+=(sum-sub[v.fi])*v.se,DFS(v.fi),tmp+=sub[v.fi]*v.se,tmp-=(sum-sub[v.fi])*v.se;
  55. }
  56. }
  57. }
  58.  
  59. int main()
  60. {
  61. Init();
  62. for(int i=1;i<=26;++i)
  63. c=i,toZero(),f=1,DFS(1),tmp=all[1],f=2,DFS(1),cout<<res<<' ';
  64. cout<<'\n';
  65. return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement