제출 #698053

#제출 시각아이디문제언어결과실행 시간메모리
698053vjudge1구슬과 끈 (APIO14_beads)C++17
100 / 100
84 ms28404 KiB
#include<bits/stdc++.h> using namespace std; template <typename T> inline void read(T &x) { x=0;T f=1;char c=getchar(); for(;!isdigit(c);c=getchar()) if(c=='-')f=-1; for(;isdigit(c);c=getchar()) x=(x<<1)+(x<<3)+(c^48); x*=f; } template <typename T,typename ...Args>void read(T &x,Args&...args){read(x),read(args...);} template <typename T> void print(T x) { if(x<0) x=-x,putchar('-'); if(x>9) print(x/10); putchar(x%10+48); } template <typename T> void print(T x,char c){print(x); putchar(c);} template<typename T>inline void output(T x){print(x,' ');} template<typename T,typename ...Arg>inline void output(T x,Arg ...arg){output(x);output(arg...);} const int N=200007; const long long inf=0x3f3f3f3f3f3f3f3f; int n,cnt,h[N],vfa[N],v[2][N]; long long ans,f[N][2],g[N][2],dp[N][2],mx[2][N]; struct edge{int to,nxt,w;}mp[N<<1]; void add(int x,int y,int z) { cnt++; mp[cnt].nxt=h[x]; mp[cnt].to=y; mp[cnt].w=z; h[x]=cnt; } void solve1(int x,int fa) { mx[0][x]=mx[1][x]=-inf; v[0][x]=v[1][x]=0; for(int i=h[x];i;i=mp[i].nxt) { int y=mp[i].to,w=mp[i].w; if(y==fa) continue; vfa[y]=w; solve1(y,x); f[x][0]+=max(f[y][0],f[y][1]+w); long long val=f[y][0]+w-max(f[y][0],f[y][1]+w); if(mx[0][x]<val) v[1][x]=v[0][x], mx[1][x]=mx[0][x], v[0][x]=y,mx[0][x]=val; else if(mx[1][x]<val) v[1][x]=y,mx[1][x]=val; } f[x][1]=f[x][0]+mx[0][x]; } void solve2(int x,int fa) { for(int i=h[x];i;i=mp[i].nxt) { int y=mp[i].to,w=mp[i].w; if(y==fa) continue; if(v[0][x]==y) swap(mx[0][x],mx[1][x]), swap(v[0][x],v[1][x]); dp[x][0]=g[x][0]-max(f[y][0],f[y][1]+w); dp[x][1]=dp[x][0]+mx[0][x]; if(x>1) dp[x][1]=max(dp[x][1],dp[x][0]+dp[fa][0]+vfa[x]-max(dp[fa][0],dp[fa][1]+vfa[x])); g[y][0]=f[y][0]+max(dp[x][0],dp[x][1]+w); if(mx[0][x]<mx[1][x]) swap(mx[0][x],mx[1][x]), swap(v[0][x],v[1][x]); solve2(y,x); } } int main() { read(n); for(int i=1,x,y,z;i<n;i++) read(x,y,z),add(x,y,z),add(y,x,z); solve1(1,0); g[1][0]=f[1][0]; solve2(1,0); for(int i=1;i<=n;i++) ans=max(ans,g[i][0]); print(ans,'\n'); return 0; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...