SGU 149 Computer Network(树形DP)

来源:互联网 发布:linux下载整个文件夹 编辑:程序博客网 时间:2024/05/18 08:47

Description
给出一个n个节点的树,问树上任一点i与树上其他点之间的最远距离
Input
第一行为一整数n表示树上节点数,之后n-1行第i行两个整数j,c表示树上和j之间有一条权值为c的边(1<=n<=10000)
Output
输出n个数表示每个点到其他点的最远距离
Sample Input
3
1 1
1 2
Sample Output
2
3
3
Solution
两遍dfs,第一遍dfs由前序遍历求得dp[i][0]和dpi][1],其中dp[i][0]表示i与以其为根的子树中点的最远距离,dp[i][1]表示i与以其为根的子树中点的次远距离,因为有
dp[u][0]=max(dp[v][0]+c[u][v])
dp[u][1]=second_max(dp[v][0]+c[u][v]),其中fa[v]=u
第二遍dfs由中序遍历去更新dp[i][0]和dp[i][1]的值使其变为i与所有其他点的最远距离和次远距离,因为根节点的dp[i][[0]和dp[i][1]已经求出,而每次如果已经知道节点v的父亲节点u的dp[u][0]和dp[u][1],令temp为i到树上其他节点的最远距离,通过判断dp[v][0]+c[u][v]=?dp[u][0]判断u到与其最远点的路径是否经过v,如果dp[v][0]+c[u][v]=dp[u][0]则temp=dp[u][1]+c[u][v],否则temp=dp[u][0]+c[u][v],之后由temp值去更新dp[v][0]和dp[v][1]
dp[v][0]=max(dp[v][0],dp[v][1],temp)
dp[v][1]=second_max(dp[v][0],dp[v][1],temp)
Code

#include<cstdio>#include<iostream>#include<algorithm>#include<cstring>using namespace std;#define maxn 11111#define INF 0x3f3f3f3ftypedef long long ll;struct Edge{    int to,next,c;}edge[2*maxn];int n,d[maxn][2],tot,head[maxn];void init(){    tot=0;    memset(head,-1,sizeof(head));    memset(d,0,sizeof(d));}void add(int u,int v,int c){    edge[tot].to=v;    edge[tot].c=c;    edge[tot].next=head[u];    head[u]=tot++;}void dfs1(int u,int fa){    for(int i=head[u];~i;i=edge[i].next)    {        int v=edge[i].to,c=edge[i].c;        if(v==fa)continue;        dfs1(v,u);        int temp=c+d[v][0];        if(temp>d[u][0])swap(temp,d[u][0]);        if(temp>d[u][1])d[u][1]=temp;    }}void dfs2(int u,int fa){    for(int i=head[u];~i;i=edge[i].next)    {        int v=edge[i].to,c=edge[i].c;        if(v==fa)continue;        int temp;        if(d[v][0]+c==d[u][0])temp=c+d[u][1];        else temp=c+d[u][0];        if(temp>d[v][0])swap(temp,d[v][0]);        if(temp>d[v][1])d[v][1]=temp;        dfs2(v,u);    }}int main(){    init();    scanf("%d",&n);    for(int i=2;i<=n;i++)    {        int u,c;        scanf("%d%d",&u,&c);        add(i,u,c),add(u,i,c);    }    dfs1(1,0);    dfs2(1,0);    for(int i=1;i<=n;i++)printf("%d\n",d[i][0]);    return 0;}
0 0
原创粉丝点击