Computer HDU - 2196(树形dp)

    技术2024-11-14  10

    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

    题意: 树上求每个点离它最远点距离

    思路: 定义 d p [ u ] [ 0 / 1 / 2 ] dp[u][0/1/2] dp[u][0/1/2]代表 u u u节点往下的最大值,往下的次大值,往上的最大值。

    #include <cstdio> #include <cstring> #include <algorithm> #include <queue> #include <iostream> #include <string> #include <vector> using namespace std; typedef long long ll; const int maxn = 2e4 + 7; int pos[maxn]; int dp[maxn][3]; int head[maxn],nex[maxn],to[maxn],val[maxn],tot; void add(int x,int y,int z) { to[++tot] = y; nex[tot] = head[x]; val[tot] = z; head[x] = tot; } void init() { tot = 0; memset(head,0,sizeof(head)); memset(dp,0,sizeof(dp)); memset(pos,0,sizeof(pos)); } void dfs1(int x,int fa) { int w1 = 0,w2 = 0; for(int i = head[x];i;i = nex[i]) { int v = to[i],w = val[i]; if(v == fa) continue; dfs1(v,x); if(w1 < dp[v][0] + w) { w2 = w1; w1 = dp[v][0] + w; pos[x] = v; } else if(w2 < dp[v][0] + w) { w2 = dp[v][0] + w; } else if(w2 < dp[v][1] + w) { w2 = dp[v][1] + w; } } dp[x][0] = w1;dp[x][1] = w2; } void dfs2(int x,int fa) { for(int i = head[x];i;i = nex[i]) { int v = to[i],w = val[i]; if(v == fa) continue; if(pos[x] == v) { dp[v][2] = max(dp[x][1],dp[x][2]) + w; } else { dp[v][2] = max(dp[x][0],dp[x][2]) + w; } dfs2(v,x); } } int main() { int n; while(~scanf("%d",&n)) { init(); for(int i = 2;i <= n;i++) { int x,y;scanf("%d%d",&x,&y); add(i,x,y);add(x,i,y); } dfs1(1,-1); dfs2(1,-1); for(int i = 1;i <= n;i++) { printf("%d\n",max(dp[i][0],dp[i][2])); } } return 0; }
    Processed: 0.025, SQL: 12