【AGC010 C】Cleaning

The meaning of problems

  There are a \ (n-\) points of the tree, the \ (I \) nodes have \ (a_i \) A stone.
  Every time you can choose a different pair of leaf nodes, which all points on the leaf node must have a gravel path. A stone is then removed (two leaf nodes are selected path points) on each node of the two leaf nodes in the path. The leaf nodes of degree \ (1 \) points.
  To determine whether it is possible to remove all the stones.
  \ (n-\ Le. 5 ^ 10 \)
  \ (a_i \ ^. 9 Le 10 \)

answer

  https://blog.csdn.net/zjznku/article/details/54948774

#include<bits/stdc++.h>
#define ll long long
#define N 100002
using namespace std;
inline int read(){
    int x=0; bool f=1; char c=getchar();
    for(;!isdigit(c); c=getchar()) if(c=='-') f=0;
    for(; isdigit(c); c=getchar()) x=(x<<3)+(x<<1)+(c^'0');
    if(f) return x;
    return 0-x;
}
int n,a[N],du[N];
struct edge{int v,nxt;}e[N<<1];
int hd[N],cnt;
inline void add(int u, int v){e[++cnt]=(edge){v,hd[u]}, hd[u]=cnt, ++du[u];}
void nosol(){
    puts("NO");
    exit(0);
}
void dfs(int u, int fa){
    if(du[u]==1) return;
    ll sum=0; int mx=0;
    for(int i=hd[u]; i; i=e[i].nxt) if(e[i].v!=fa){
        dfs(e[i].v,u);
        sum+=a[e[i].v];
        mx=max(mx,a[e[i].v]);
    }
    ll x=sum-a[u], y=2*a[u]-sum;
    if(x<0 || y<0 || x>min(sum-mx,sum/2) || (!fa && y)) nosol();
    a[u]=y;
}
int main(){
    n=read();
    for(int i=1; i<=n; i++) a[i]=read();
    if(n==2){
        if(a[1]==a[2]) puts("YES");
        else puts("NO");
        return 0;
    }
    int u,v;
    for(int i=1; i<n; i++){
        u=read(), v=read();
        add(u,v), add(v,u);
    }
    int rt=1;
    while(du[rt]==1) ++rt;
    dfs(rt,0);
    if(a[rt]) puts("NO");
    else puts("YES");
    return 0;
}

Guess you like

Origin www.cnblogs.com/scx2015noip-as-php/p/agc010c.html