1363E - Tree Shuffling - CodeForces Solution


dfs and similar dp greedy trees *2000

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
#define int long long
using namespace std;
typedef pair<int,int> PII;
#define ft first
#define sd second
const int N=1e6+10;
const int mod=1e9+7;
int n,m,a[N],b[N],p[N],cnt1[N],cnt2[N],res;
vector<int>g[N];
void dfs(int u,int fa,int mn){
	for(auto v:g[u]){
		if(v==fa)continue;
		dfs(v,u,min(mn,p[u]));
		cnt1[u]+=cnt1[v];cnt2[u]+=cnt2[v];
	}
	if(p[u]<mn){
		int x=min(cnt1[u],cnt2[u]);
		cnt1[u]-=x;cnt2[u]-=x;
		res+=p[u]*x*2;
	}
}
void solve(){
	cin>>n;
	int cnt=0;
	for(int i=1;i<=n;i++){
		cin>>p[i]>>a[i]>>b[i];
		if(a[i]==1&&b[i]==0)cnt++,cnt1[i]++;
		else if(a[i]==0&&b[i]==1)cnt--,cnt2[i]++;
	}
	if(cnt){
		cout<<"-1\n";
		return;
	}
	for(int i=1;i<=n-1;i++){
		int x,y;cin>>x>>y;
		g[x].push_back(y);
		g[y].push_back(x);
	}
	dfs(1,0,0x3f3f3f3f);
	cout<<res<<'\n';
}
signed main(){
	ios::sync_with_stdio(false);cin.tie(0);
	int Case=1;
	//cin>>Case;
	while(Case--)solve();
}


Comments

Submit
0 Comments
More Questions

43A - Football
50A - Domino piling
479A - Expression
1480A - Yet Another String Game
1216C - White Sheet
1648A - Weird Sum
427A - Police Recruits
535A - Tavas and Nafas
581A - Vasya the Hipster
1537B - Bad Boy
1406B - Maximum Product
507B - Amr and Pins
379A - New Year Candles
1154A - Restoring Three Numbers
750A - New Year and Hurry
705A - Hulk
492B - Vanya and Lanterns
1374C - Move Brackets
1476A - K-divisible Sum
1333A - Little Artem
432D - Prefixes and Suffixes
486A - Calculating Function
1373B - 01 Game
1187A - Stickers and Toys
313B - Ilya and Queries
579A - Raising Bacteria
723A - The New Year Meeting Friends
302A - Eugeny and Array
1638B - Odd Swap Sort
1370C - Number Game