Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <utility>
- #define fi first
- #define se second
- using namespace std;
- const int MAXN=200005;
- int n,a[MAXN],b[MAXN];
- vector<pair<int,int>> g[MAXN];
- int c,f;
- short used[MAXN];
- long long res,tmp,sum;
- long long sub[MAXN],all[MAXN];
- void Init()
- {
- ios::sync_with_stdio(false);
- cin.tie(NULL);cout.tie(NULL);
- cin>>n;
- char x;
- for(int i=1;i<=n;++i)
- cin>>x,a[i]=x-'a'+1;
- for(int i=1;i<=n;++i)
- cin>>b[i];
- int u,v,w;
- for(int i=1;i<n;++i)
- cin>>u>>v>>w,g[u].emplace_back(v, w),g[v].emplace_back(u, w);
- }
- void toZero()
- {
- res=1ll<<60;
- sum=0;
- for(int i=1;i<=n;++i)
- used[i]=0,sub[i]=all[i]=0;
- }
- void DFS(int u)
- {
- used[u]=f;
- if(f==1&&a[u]==c)
- sum+=b[u],sub[u]+=b[u];
- if(f==2)
- res=min(res,tmp);
- for(auto v:g[u])
- {
- if(used[v.fi]!=f)
- {
- if(f==1)
- DFS(v.fi),all[u]+=all[v.fi],all[u]+=sub[v.fi]*v.se,sub[u]+=sub[v.fi];
- if(f==2)
- 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;
- }
- }
- }
- int main()
- {
- Init();
- for(int i=1;i<=26;++i)
- c=i,toZero(),f=1,DFS(1),tmp=all[1],f=2,DFS(1),cout<<res<<' ';
- cout<<'\n';
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement