#貪心,樹#C 平衡的樹
阿新 • • 發佈:2020-11-30
分析
處理出子樹內剩餘刪減以及最大的剩餘\(a\)和,
如果刪了還是超過\(b\)輸出無解
程式碼
#include <cstdio> #include <cctype> #define rr register using namespace std; const int N=200011; typedef long long lll; struct rec{lll wt,ws;}; lll ans; int as[N],n,et,flag; struct node{int y,w1,w2,next;}e[N]; inline signed iut(){ rr int ans=0; rr char c=getchar(); while (!isdigit(c)) c=getchar(); while (isdigit(c)) ans=(ans<<3)+(ans<<1)+(c^48),c=getchar(); return ans; } rec dfs(int x){ rr lll wt=0,ws=0; for (rr int i=as[x];i;i=e[i].next){ if (flag) return (rec){wt,ws}; rr rec t=dfs(e[i].y); if (t.ws-t.wt>e[i].w2){flag=1; return (rec){wt,ws};} if (t.ws>e[i].w2) t.wt-=t.ws-e[i].w2,ans+=t.ws-e[i].w2,t.ws=e[i].w2; wt+=t.wt+(e[i].w1<e[i].w2?e[i].w1:e[i].w2),ws+=e[i].w1+t.ws; } return (rec){wt,ws}; } signed main(){ freopen("tree.in","r",stdin); freopen("tree.out","w",stdout); n=iut(); for (rr int i=1;i<n;++i){ rr int x=iut(),y=iut(),w1=iut(),w2=iut(); e[++et]=(node){y,w1,w2,as[x]},as[x]=et; } dfs(1); if (flag) printf("-1"); else printf("%lld",ans); return 0; }