AtCoder Grand Contest 010 C - Cleaning
https://atcoder.jp/contests/agc010/tasks/agc010_c
這題的關鍵是每個點向上的路徑和兒子們自己匹配的路徑可以解方程解出來啊
沒想到啊= =
f[u]表示u向父節點的路徑,pr為子樹內部匹配的路徑
sum=所有子樹向上的路徑,其中有pr對自動配對了,f[u]+2*pr=sum,pr+f[u]=a[u]
能湊出pr對來的充要條件是最大的那個f[v]*2<=sum
然後要滿足f[rt]=0,pr>=0,f[u]>=0,a[u]>=0,就行了
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxl=3e5+10;
int n,m,k,cnt,tot,cas,ans;
int a[maxl],deg[maxl];ll dp[maxl],f[maxl];
bool vis[maxl];
vector<int> e[maxl];
char s[maxl];
inline void prework()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
for(int i=1;i<n;i++)
{
int u,v;scanf("%d%d",&u,&v);
e[u].push_back(v);deg[u]++;
e[v].push_back(u);deg[v]++;
}
}
inline void dfs(int u,int fa)
{
if(deg[u]==1)
{
f[u]=a[u];
return;
}
ll sum=0,mx=0;
for(int v:e[u])
if(v!=fa)
{
dfs(v,u);
sum+=f[v];mx=max(mx,f[v]);
}
ll pr=sum-a[u];
f[u]=sum-2*pr;
if(f[u]>a[u] || min(sum/2,sum-mx)<pr)
ans=0;
}
inline void mainwork()
{
if(n==2)
{
ans=(a[1]==a[2]);
return;
}
int rt;
for(int i=1;i<=n;i++)
if(deg[i]>1)
{
rt=i;
break;
}
ans=1;
dfs(rt,0);
if(f[rt]!=0) ans=0;
}
inline void print()
{
puts(ans?"YES":"NO");
}
int main()
{
int t=1;
//scanf("%d",&t);
for(cas=1;cas<=t;cas++)
{
prework();
mainwork();
print();
}
return 0;
}
相關文章
- AtCoder Grand Contest 001
- AtCoder題解 —— AtCoder Beginner Contest 183 —— C - Travel
- Atcoder Beginner Contest 367 C-F
- AtCoder Regular Contest 104——C區間dp
- AtCoder Beginner Contest 350
- AtCoder Beginner Contest 349
- AtCoder Beginner Contest 347
- AtCoder Beginner Contest 343
- AtCoder Regular Contest 171
- AtCoder Beginner Contest 344
- AtCoder Beginner Contest 346
- AtCoder Beginner Contest 353
- AtCoder Beginner Contest 354
- AtCoder Beginner Contest 352
- AtCoder Beginner Contest 351
- AtCoder Regular Contest 177
- 【AtCoder Beginner Contest 347】
- AtCoder Beginner Contest 348
- AtCoder Beginner Contest 204
- AtCoder Beginner Contest 345
- AtCoder Beginner Contest 355
- AtCoder Regular Contest 174
- AtCoder Beginner Contest 382
- AtCoder Beginner Contest 376
- AtCoder Beginner Contest 373
- AtCoder Beginner Contest 374
- AtCoder Beginner Contest 379
- AtCoder Beginner Contest 380
- AtCoder Beginner Contest 381
- AtCoder Beginner Contest 372
- AtCoder Beginner Contest 368
- AtCoder Beginner Contest 044
- AtCoder Beginner Contest 047
- AtCoder Beginner Contest 367
- AtCoder Beginner Contest 045
- AtCoder Beginner Contest 366
- AtCoder Beginner Contest 365
- AtCoder Beginner Contest 364