1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| #include<bits/stdc++.h> using namespace std; #define il inline #define ll long long #pragma comment(linker, "/STACK:1024000000,1024000000") il ll read(){char c=getchar();ll f=1,x=0;while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}while(c>='0'&&c<='9'){x=(x<<1)+(x<<3)+(c^'0');c=getchar();}return x*f;} const int N =2e5+5; const int MAX=1e9; const int mod = 1e9+7; #define db double #define eps 1e-8 #define int long long int d[N],sz[N]; struct edge{ int u,v,w,nxt; }e[N*2]; int head[N],cnt,dif1[N],dif2[N]; void add(int u,int v,int w){ e[cnt]={u,v,w,head[u]}; head[u]=cnt++; } struct node{ int a,b,c; }tr[N]; int work[N]; void dfs(int x,int fa){ if(tr[x].b>tr[x].c){ dif1[x]++; }else if(tr[x].b<tr[x].c){ dif2[x]++; } tr[x].a=min(tr[fa].a,tr[x].a); for (int i = head[x]; i !=-1 ; i=e[i].nxt) { int v=e[i].v; if(v!=fa){ dfs(v,x); dif1[x]+=dif1[v]; dif2[x]+=dif2[v]; } }
work[x]=2*min(dif1[x],dif2[x]); if(tr[x].a<tr[fa].a){ dif1[fa]-=work[x]/2; dif2[fa]-=work[x]/2; }else{ work[x]=0; } } signed main() { memset(head,-1, sizeof(head)); int n=read(),l=0,r=0; for (int i = 1; i <=n ; ++i) { tr[i].a=read();tr[i].b=read();tr[i].c=read(); if(tr[i].b>tr[i].c)l++; else if(tr[i].c>tr[i].b)r++; }
if(l!=r){cout<<"-1";return 0;} for (int j = 0; j <n-1 ; ++j) { int u=read();int v=read(); add(u,v,1); add(v,u,1); } tr[0].a=100000000000; dfs(1,0); int ans=0; for (int k = 1; k <=n ; ++k) { ans+=work[k]*tr[k].a; } cout<<ans; return 0; }
|