题目描述:
149. Computer Network
time limit per test: 0.5 sec.
memory limit per test: 4096 KB
memory limit per test: 4096 KB
input: standard input
output: standard output
output: standard output
A school bought the first computer some time ago. During the recent years the school bought N-1 new computers. Each new computer was connected to one of settled earlier. Managers of school are anxious about slow
functioning of the net and want to know for each computer number Si - maximum distance, for which i-th computer needs to send signal (i.e. length of cable to the most distant computer). You need to provide this information.
Input
There is natural number N (N<=10000) in the first line of input, followed by (N-1) lines with descriptions of computers. i-th line contains two natural numbers - number of computer, to which i-th computer is connected
and length of cable used for connection. Total length of cable does not exceed 10^9. Numbers in lines of input are separated by a space.
Output
Write N lines in output file. i-th line must contain number Si for i-th computer (1<=i<=N).
Sample test(s)
Input
3
1 1
1 2
1 1
1 2
Output
2
3
3
3
3
sum[u] 表示从u开始的之树的最大值。
dfs(u , fa ) 表示走父亲的最大值 。
两遍dfs就可以了 。
贴代码时间:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<set>
#include<algorithm>
#include<vector>
#include<cstdlib>
#define inf 0xfffffff
#define CLR(a,b) memset((a),(b),sizeof((a)))
#define FOR(a,b) for(int a=1;a<=(b);(a)++)
using namespace std;
int const nMax = 20010;
int const base = 10;
typedef int LL;
typedef pair<LL,LL> pij;
// std::ios::sync_with_stdio(false);
int dp[nMax],sum[nMax],vis[nMax];
int fi[nMax],next[nMax],w[nMax],u[nMax],v[nMax],E;
int n;
void init(){
FOR(i,n)fi[i]=-1,vis[i]=0;
E=0;
}
void insert(int a,int b,int c){
u[E]=a,v[E]=b,w[E]=c;
next[E]=fi[a],fi[a]=E;
E++;
}
void dfs(int a){
sum[a]=0;
vis[a]=1;
int b;
for(int e=fi[a];e!=-1;e=next[e])if(!vis[b=v[e]]){
dfs(b);
sum[a]=max(sum[a],sum[b]+w[e]);
}
return ;
}
int cmp(pij a,pij b){
return sum[a.first]>sum[b.first];
}
void dfs(int a,int fa){
dp[a]=fa;
vis[a]=1;
int b;
vector<pij> Q;
Q.clear();
int max1,u1,max2,u2;
for(int e=fi[a];e!=-1;e=next[e])if(!vis[b=v[e]]){
sum[b]+=w[e];
if(sum[b]>dp[a])dp[a]=sum[b];
Q.push_back(pij(b,w[e]));
}
sort(Q.begin(),Q.end(),cmp);
for(int i=0;i<Q.size();i++){
if(i==0){
if(Q.size()==1){
dfs(Q[i].first,fa+Q[i].second);
}else{
dfs(Q[i].first,max(fa,sum[Q[1].first])+Q[i].second);
}
}else{
dfs(Q[i].first,max(fa,sum[Q[0].first])+Q[i].second);
}
}
return ;
}
int main(){
scanf("%d",&n);
init();
for(int a=2,b,c;a<=n;a++){
scanf("%d%d",&b,&c);
insert(a,b,c);
insert(b,a,c);
}
dfs(1);
CLR(vis,0);
dfs(1,0);
for(int i=1;i<=n;i++)printf("%d\n",dp[i]);
return 0;
}