标签:
题目链接:
Time Limit: 8000/4000 MS (Java/Others)
Memory Limit: 200000/200000 K (Java/Others)
//#include <bits/stdc++.h> #include <vector> #include <iostream> #include <queue> #include <cmath> #include <map> #include <cstring> #include <algorithm> #include <cstdio> using namespace std; #define Riep(n) for(int i=1;i<=n;i++) #define Riop(n) for(int i=0;i<n;i++) #define Rjep(n) for(int j=1;j<=n;j++) #define Rjop(n) for(int j=0;j<n;j++) #define mst(ss,b) memset(ss,b,sizeof(ss)); typedef long long LL; template<class T> void read(T&num) { char CH; bool F=false; for(CH=getchar();CH<‘0‘||CH>‘9‘;F= CH==‘-‘,CH=getchar()); for(num=0;CH>=‘0‘&&CH<=‘9‘;num=num*10+CH-‘0‘,CH=getchar()); F && (num=-num); } int stk[70], tp; template<class T> inline void print(T p) { if(!p) { puts("0"); return; } while(p) stk[++ tp] = p%10, p/=10; while(tp) putchar(stk[tp--] + ‘0‘); putchar(‘\n‘); } const LL mod=1e9+7; const double PI=acos(-1.0); const LL inf=1e18; const int N=1e5+10; const int maxn=1005; int n,son[N],num,head[N],cnt; LL dis[N],ans,sum; struct Edge { int to,next,val; }edge[2*N]; void addedge(int s,int e,int va) { edge[cnt].to=e; edge[cnt].next=head[s]; edge[cnt].val=va; head[s]=cnt++; } void dfs(int x,int fa) { int mmax=0; sum=sum+dis[x]; son[x]=1; for(int i=head[x];i!=-1;i=edge[i].next) { int y=edge[i].to; if(y==fa)continue; dis[y]=dis[x]+edge[i].val; dfs(y,x); son[x]+=son[y]; } } void dfs1(int x,int fa,LL dist) { ans=min(ans,dist); for(int i=head[x];i!=-1;i=edge[i].next) { int y=edge[i].to; if(y==fa)continue; LL s=dist+(LL)(n-2*son[y])*(LL)edge[i].val; dfs1(y,x,s); } } int main() { int t; read(t); int Case=1; while(t--) { read(n); int x,y,z; cnt=0; ans=inf; sum=0; mst(head,-1); for(int i=1;i<n;i++) { read(x);read(y);read(z); addedge(x,y,z); addedge(y,x,z); } dis[1]=0; dfs(1,-1); dfs1(1,-1,sum); printf("Case #%d: %lld\n",Case++,2*ans); } return 0; }
hdu-4118 Holiday's Accommodation(树形dp+树的重心)
标签:
原文地址:http://www.cnblogs.com/zhangchengc919/p/5617712.html