With each node as the hospital, the distances are enumerated.(floyd?)
Incidental adjacency table.
//Writer:GhostCai && His Yellow Duck #include<iostream> #include<cstring> #define MAXN 2000 using namespace std; // struct edge{ int to,next; }e[MAXN]; int cnt,head[MAXN]; void add(int x,int y){ e[++cnt].to = y; e[cnt].next = head[x]; head[x]=cnt; } // int n,ans=1<<30; int dis[MAXN],num[MAXN]; bool vis[MAXN]; void dfs(int id,int dp){ int i; for(i=head[id];i!=-1;i=e[i].next){ if(!e[i].to || vis[e[i].to ]) continue; vis[e[i].to ]=1; dis[e[i].to] = dp+1; dfs(e[i].to , dp+1); } } int main(){ cin>>n; int i,j,x,y; memset(head,-1,sizeof(head)); for(i=1;i<=n;i++){ cin>>num[i]>>x>>y; add(i,x);add(x,i); add(i,y);add(y,i); } for(i=1;i<=n;i++){ memset(dis,0,sizeof(dis)); memset(vis,0,sizeof(vis)); vis[i]=1;//!!! dfs(i,0); int sum=0; for(j=1;j<=n;j++){ sum+=num[j]*dis[j]; } ans=min(sum,ans); } cout<<ans<<endl; return 0; }