HDU - 2196 Computer 樹形dp 兩邊dfs 典型
A school bought the first computer some time ago(so this computer's id is 1). 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 the maximum distance Si 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.
Hint: the example input is corresponding to this graph. And from the graph, you can see that the computer 4 is farthest one from 1, so S1 = 3. Computer 4 and 5 are the farthest ones from 2, so S2 = 2. Computer 5 is the farthest one from 3, so S3 = 3. we also get S4 = 4, S5 = 4.
Input
Input file contains multiple test cases.In each case there is natural number N (N<=10000) in the first line, 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
For each case output N lines. i-th line must contain number Si for i-th computer (1<=i<=N).
Sample Input
5
1 1
2 1
3 1
1 1
Sample Output
3
2
3
4
4
題意:給出一顆樹,求樹中的每個頂點到其他所有頂點的最大值。
題解:一個節點的最大距離有兩種情況:
1. 到子節點的最大距離
2.父節點的最大距離(除了該節點分支)+ 根節點到該節點的距離
所以我們兩邊dfs 即可解決
第一遍,我們記錄下每個節點到子節點的最大距離和次大距離,並記錄最大距離的子代
第二遍,更新每個節點經過父節點這個路徑的最大距離
最後輸出,經過父節點最大距離和到子節點最大距離較大一個即可
#include<iostream>
#include<cstdio>
#include<vector>
#include<cstring>
using namespace std;
const int N=1e4+10;
vector<int> v[N];
int n,lm[N],head[N],dp[N][3],len;
struct node{
int to,d,nex;
}e[N*2];
void add(int x,int y,int d)
{
e[len].to=y;
e[len].d=d;
e[len].nex=head[x];
head[x]=len++;
}
int dfs(int f,int u)
{
dp[u][0]=dp[u][1]=dp[u][2]=0;
for(int i=head[u];i!=-1;i=e[i].nex)
{
int to=e[i].to;
if(to==f) continue;
int dis=dfs(u,to)+e[i].d;
// cout<<dis<<endl;
if(dis>dp[u][0]) dp[u][1]=dp[u][0],dp[u][0]=dis,lm[u]=to;
else if(dis>dp[u][1]) dp[u][1]=dis;
}
// cout<<u<<" "<<dp[u][0]<<" "<<dp[u][1]<<endl;
return dp[u][0];
}
void dfs2(int f,int u)
{
for(int i=head[u];i!=-1;i=e[i].nex)
{
int to=e[i].to;
if(to==f) continue;
if(to==lm[u]) dp[to][2]=max(dp[u][1],dp[u][2])+e[i].d;
else dp[to][2]=max(dp[u][0],dp[u][2])+e[i].d;
// cout<<to<<" "<<dp[to][2]<<endl;
dfs2(u,to);
}
}
int main()
{
int u,d;
while(~scanf("%d",&n))
{
memset(head,-1,sizeof(head));
len=0;
memset(lm,-1,sizeof(lm));
for(int i=2;i<=n;i++)
{
scanf("%d%d",&u,&d);
add(u,i,d);
add(i,u,d);
}
dfs(0,1);
dfs2(0,1);
for(int i=1;i<=n;i++)
printf("%d\n",max(dp[i][0],dp[i][2]));
}
return 0;
}