zoukankan      html  css  js  c++  java
  • Computer (树形DP)

    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
    题目大意:
    给定n,代表n台电脑,编号为1的是最初始的电脑,下面n-1对数字,分别编号为2~n的电脑相连电脑的编号与长度。
    输出n行,求与第i台电脑最远的电脑的距离。
    #include <iostream>
    #include <algorithm>
    #include <cstring>
    using namespace std;
    int n,dp[20005],pre[10005];
    struct edge
    {
        int u,v,w,p;///u与v电脑相连,长度w,u对应的上一条边
        edge(){}
        edge(int u,int v,int w,int p):u(u),v(v),w(w),p(p){}
    }e[20005];
    int dfs(int u,int p)
    {
        int ans=0;
        for(int i=pre[u];i!=-1;i=e[i].p)
        {
            int v=e[i].v;
            if(v==p) continue;
            if(!dp[i])///没更新过
                dp[i]=dfs(v,u)+e[i].w;
            ans=max(ans,dp[i]);
    
        }
        return ans;
    }
    int main()
    {
        while(cin>>n)
        {
            memset(dp,0,sizeof dp);
            memset(pre,-1,sizeof pre);
            int x=0;
            for(int i=2,v,w;i<=n;i++)
            {
                cin>>v>>w;
                e[x]=edge(i,v,w,pre[i]);
                pre[i]=x++;
                e[x]=edge(v,i,w,pre[v]);
                pre[v]=x++;
            }
            for(int i=1;i<=n;i++)
                cout<<dfs(i,-1)<<'
    ';
        }
        return 0;
    }
     
  • 相关阅读:
    Root of AVL Tree
    04-树4 是否同一棵二叉搜索树
    03-树3 Tree Traversals Again
    03-树2 List Leaves
    283. Move Zeroes
    506. Relative Ranks
    492. Construct the Rectangle
    476. Number Complement
    461. Hamming Distance
    389. Find the Difference
  • 原文地址:https://www.cnblogs.com/zdragon1104/p/9201104.html
Copyright © 2011-2022 走看看