Computer - HDU 2196 树形dp

来源:互联网 发布:如何进行数据备份 编辑:程序博客网 时间:2024/05/16 12:48

Computer

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2976    Accepted Submission(s): 1512


Problem Description
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
51 12 13 11 1
 

Sample Output
32344


题意:给你一个联通的电脑网络,问你每个电脑到另外的其他电脑的最远距离是多少。

思路:首先以电脑1作为根节点建立树形结构,然后dfs求出所有点向下的最大距离,然后求出所有点向上的最大距离,最终得出答案。

AC代码如下:

#include<cstdio>#include<cstring>#include<vector>#include<algorithm>using namespace std;struct node{ int len,from;};int up[10010],father[10010],len[10010];vector<node> com[10010];vector<int> vc[10010];bool cmp(node a,node b){ return a.len>b.len;}void dfs(int u){ int i,j,k,v;  for(i=0;i<vc[u].size();i++)  { v=vc[u][i];    dfs(v);    node c;    if(vc[v].size()==0)    c.len=len[v];    else    c.len=com[v][0].len+len[v];    c.from=v;    com[u].push_back(c);  }  sort(com[u].begin(),com[u].end(),cmp);}void solve(int u){ int i,j,k,fa,ans=0,s=vc[u].size();  fa=father[u];  if(s==0)   ans=up[u];  if(s>=1)   ans=max(com[u][0].len,up[u]);  printf("%d\n",ans);}int main(){ int n,i,j,k,l,u,v,fa;  while(~scanf("%d",&n))  { for(i=1;i<=n;i++)    { vc[i].clear();      com[i].clear();    }    memset(up,0,sizeof(up));    for(i=2;i<=n;i++)    { scanf("%d%d",&k,&l);      vc[k].push_back(i);      len[i]=l;      father[i]=k;    }    dfs(1);    for(i=2;i<=n;i++)    { fa=father[i];      for(j=0;j<vc[fa].size();j++)       if(com[fa][j].from!=i)        up[i]=max(up[i],com[fa][j].len+len[i]);      up[i]=max(up[i],up[fa]+len[i]);    }    for(i=1;i<=n;i++)     solve(i);  }}



0 0
原创粉丝点击