Codeforces Round #660 (Div. 2) C - Uncle Bogdan and Country Happiness

题意: 一共 n n n个城市, m m m个上班族。城市之间的联通图是一棵树。给定每个城市的总人数 p i p_i pi和幸福指数 h i h_i hi,每个人都在首都 1 1 1号点上班,每个人下班时的心情也不尽相同,在下班回家的路上,每个人都可能在回家路上的任意一个地点时,心情从开心变成不开心,但是不可能从不开心变成开心。问是否存在一种情况使得每个城市的幸福指数都与给定的 h i h_i hi相同。其中 h i h_i hi等于下班路上经过该点时开心的人数减去下班路上经过该点时不开心的人数。
数据范围: 1 ≤ n ≤ 1 0 5 , 0 ≤ m ≤ 1 0 9 , ∑ i = 1 n p i = m , − 1 0 9 ≤ h i ≤ 1 0 9 1\leq n\leq 10^5,0\leq m\leq 10^9,\overset{n}{\underset{i=1}{\sum}}p_i=m,-10^9\leq h_i\leq 10^9 1n105,0m109,i=1npi=m,109hi109

题解:
对于每个城市,设下班路上经过该城市的人数为 s i z [ u ] siz[u] siz[u],其中开心的人数为 g o o d [ u ] good[u] good[u],不开心的人数是 b a d [ u ] bad[u] bad[u]

  • g o o d [ u ] good[u] good[u]是整数, b a d [ u ] bad[u] bad[u]是整数
  • g o o d [ u ] ≥ 0 , b a d [ u ] ≥ 0 good[u]\geq0,bad[u]\geq0 good[u]0,bad[u]0
  • ∑ g o o d [ u s o n ] ≤ g o o d [ u ] \sum good[uson]\leq good[u] good[uson]good[u]

代码:

#include
using namespace std;

typedef long long ll;

template<typename T>
inline T Read(){
    T s = 0, f = 1; char ch = getchar();
    while(!isdigit(ch)) {if(ch == '-') f = -1; ch = getchar();}
    while(isdigit(ch)) {s = (s << 3) + (s << 1) + ch - '0'; ch = getchar();}
    return s * f;
}

#define read() Read()
#define readl() Read()

const int N = 1e5 + 10;
const int M = N << 1;

ll p[N], ha[N];
bool ans;
int h[N], e[M], ne[M], idx;
void add(int a, int b) {
	e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

ll siz[N];
ll good[N];

void dfs(int u, int fa) {
	siz[u] = p[u];
	for(int i = h[u]; i != -1; i = ne[i]) {
		int v = e[i];
		if(v == fa) continue;
		dfs(v, u);
		siz[u] += siz[v];
	} 
	good[u] = siz[u] + ha[u];
	if(good[u] & 1) ans = false; //小数 
	
	good[u] >>= 1;
	if(good[u] < 0 || good[u] > siz[u]) ans = false; //两者均不为负数 
	 
	ll sgood = 0;
	for(int i = h[u]; i != -1; i = ne[i]) {
		int v = e[i];
		if(v == fa) continue;
		sgood += good[v];
	}
	if(good[u] < sgood) ans = false; //good/bad都不小于子树 
}

void solve() {
	idx = 0;
	int n = read(), m = read();	
	for(int i = 1; i <= n; ++i) h[i] = -1;
	for(int i = 1; i <= n; ++i) p[i] = readl();
	for(int i = 1; i <= n; ++i) ha[i] = readl();
	for(int i = 1; i < n; ++i) {
		int a = read(), b = read();
		add(a, b), add(b, a);
	}
	
	ans = true;
	dfs(1, 0);
	puts(ans ? "YES" : "NO");
}

int main()
{
	int T = read();
	for(int i = 1; i <= T; ++i) {
		solve();
	}
}

你可能感兴趣的:(Codeforces Round #660 (Div. 2) C - Uncle Bogdan and Country Happiness)