upc-2021个人训练赛第27场 D: Values(思维+并查集)
问题 D: Values
时间限制: 1 Sec 内存限制: 128 MB
题目描述
Given is a simple undirected graph with N vertices and M edges. The i-th edge connects Vertex ci and Vertex di. Initially, Vertex i has the value ai written on it. You want to change the values on Vertex 1, …, Vertex N to b1, ⋯, bN, respectively, by doing the operation below zero or more times.
Choose an edge, and let Vertex x and Vertex y be the vertices connected by that edge. Choose one of the following and do it:
Decrease the value ax by 1, and increase the value ay by 1.
Increase the value ax by 1, and decrease the value ay by 1.
Determine whether it is possible to achieve the objective by properly doing the operation.
Constraints
1≤N≤2×105
0≤M≤2×105
−109≤ai,bi≤109
1≤ci,di≤N
The given graph is simple, that is, has no self-loops and no multi-edges.
All values in input are integers.
输入
Input is given from Standard Input in the following format:
N M
a1 ⋯ aN
b1 ⋯ bN
c1 d1
⋮
cM dM
输出
Print Yes if it is possible to achieve the objective by properly doing the operation, and No otherwise.
样例输入 Copy
【样例1】
3 2
1 2 3
2 2 2
1 2
2 3
【样例2】
1 0
5
5
【样例3】
2 1
1 1
2 1
1 2
【样例4】
17 9
-905371741 -999219903 969314057 -989982132 -87720225 -175700172 -993990465 929461728 895449935 -999016241 782467448 -906404298 578539175 9684413 -619191091 -952046546 125053320
-440503430 -997661446 -912471383 -995879434 932992245 -928388880 -616761933 929461728 210953513 -994677396 648190629 -530944122 578539175 9684413 595786809 -952046546 125053320
2 10
6 12
9 11
11 5
7 6
3 15
3 1
1 9
10 4
样例输出 Copy
【样例1】
Yes
【样例2】
Yes
【样例3】
No
【样例4】
Yes
提示
样例1解释:
You can achieve the objective by, for example, doing the operation as follows:
In the first operation, choose the edge connecting Vertex 1 , 2. Then, increase a1 by 1 , decrease a2 by 1.
In the second operation, choose the edge connecting Vertex 2 , 3. Then, increase a2 by 1 , decrease a3 by 1.
This sequence of operations makes a1=2, a2=2, a3=2.
样例2解释:
The objective may be achieved already in the beginning.
样例3解释:
There is no way to do the operation to achieve the objective.
思路:
考虑一个连通块里的权值是可以相互转化的,也就是说对于一个连通块来说,如果\(a\)的和等于\(b\)的和,说明该连通块里的点的权值都能够变成\(b\).
用并查集维护连通块信息的时候再维护一下\(a,b\)的和就好了。
代码:
const int maxn=3e5+7;
ll n,m,a[maxn],b[maxn];
ll sa[maxn],sb[maxn],root[maxn];
ll find(ll x){
if(x!=root[x]) root[x]=find(root[x]);
return root[x];
}
int main(){
n=read,m=read;
rep(i,1,n) a[i]=read,root[i]=i,sa[i]=a[i];
rep(i,1,n) b[i]=read,sb[i]=b[i];
while(m--){
ll u=read,v=read;
ll fu=find(u),fv=find(v);
if(fu==fv) continue;
root[fu]=fv;
sa[fv]+=sa[fu];sb[fv]+=sb[fu];
}
bool flag=1;
rep(i,1,n)
if(i==find(i)){
if(sa[i]!=sb[i]){
flag=0;break;
}
}
if(flag) puts("Yes");
else puts("No");
return 0;
}