[树] cf 1388 C. Uncle Bogdan and Country Happiness

题目

[树] cf 1388 C. Uncle Bogdan and Country Happiness_第1张图片

题目链接:https://codeforces.com/contest/1388/problem/C

思路

设x为好心情 y为坏心情 x+y=p x-y=h =>y=(p-h)/2 p-h 一定为偶数

代码

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#if __cplusplus >= 201103L
#include 
#include 
#endif
#define ll long long
using namespace std;
const int INF = 0x3f3f3f3f;
int num[100010],h[100010],peo[100010],bad[100010],sum[100010];
vector<int> v[100010]; bool flag=0;
int dfs(int u,int fa){
	peo[u]=num[u];
	for(int i=0;i<v[u].size();i++){
		if(v[u][i]==fa) continue;
		peo[u]+=dfs(v[u][i],u);
	}
	return peo[u];
}
int dfs1(int u,int fa){
	sum[u]=0;
	for(int i=0;i<v[u].size();i++){
		if(v[u][i]==fa) continue;
		sum[u]+=dfs1(v[u][i],u);
	}
	return bad[u];
}
int main(){
	ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
	int t;
	cin>>t;
	while(t--){
		int n,m;
		cin>>n>>m;
		flag=0;
		for(int i=1;i<=n;i++) cin>>num[i],v[i].clear();
		for(int i=1;i<=n;i++) cin>>h[i];
		for(int i=1;i<=n-1;i++){
			int x,y;
			cin>>x>>y;
			v[x].push_back(y);
			v[y].push_back(x);
		}
		dfs(1,0);
		bool flag=1;
		for(int i=1;i<=n;i++){
			if((peo[i]-h[i])%2==0) bad[i]=(peo[i]-h[i])/2;
			else{
				flag=0;
				break;
			}
		}
		if(!flag){
			cout<<"NO"<<endl;
			continue;
		}
		dfs1(1,0);
		for(int i=1;i<=n;i++){
			if(bad[i]>num[i]+sum[i]||bad[i]<0) flag=0;
		}
		if(flag) cout<<"YES"<<endl;
		else cout<<"NO"<<endl;
	}
    return 0;
}

你可能感兴趣的:([树] cf 1388 C. Uncle Bogdan and Country Happiness)