The diameter of the tree, the tree DP, DFS - POJ1958

Topic Link

Title meaning

It is to build a tree, so that you seek the maximum diameter

The following methods were used with the DFS and DP

Topic Code

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int maxn=5e4+7;
int n,m,tot,a,b,c,ans;
char cc;
int head[maxn],d[maxn];
struct node{
    int to,w,next;
}edge[maxn*2];
void add(int u,int v,int w){
    edge[tot].to=v;
    edge[tot].w=w;
    edge[tot].next=head[u];
    head[u]=tot++;
}
void dfs(int u,int fa){
    for(int i=head[u];i!=-1;i=edge[i].next){
        int v=edge[i].to;
        if(v==fa)continue;
        dfs(v,u);
        ans=max(ans,d[u]+d[v]+edge[i].w);
        d[u]=max(d[u],d[v]+edge[i].w);
    }
}
int main(){
    scanf("%d%d",&n,&m);
    tot=0;
    memset(d,0,sizeof(d));
    memset(head,-1,sizeof(head));
    for(int i=1;i<=m;i++){
        scanf("%d%d%d %c",&a,&b,&c,&cc);
        add(a,b,c);add(b,a,c);
    }
    ans=0;
    dfs(1,0);
    printf("%d\n",ans);
    return 0;
}
DP tree

DP is thought arbitrary tree node as a root

Then find the deepest roots of the two sub-tree

Depth is the sum of the maximum diameter of the two sub-trees

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int maxn=5e4+7;
int n,m,tot,a,b,c,ans;
char cc;
int head[maxn],dis[maxn];
struct node{
    int to,w,next;
}edge[maxn*2];
void add(int u,int v,int w){
    edge[tot].to=v;
    edge[tot].w=w;
    edge[tot].next=head[u];
    head[u]=tot++;
}
void dfs(int u,int fa){
    for(int i=head[u];i!=-1;i=edge[i].next){
        int v=edge[i].to;
        if(v==fa)continue;
        dis[v]=dis[u]+edge[i].w;
        dfs(v,u);
    }
}
int main(){
    scanf("%d%d",&n,&m);
    tot=0;
    memset(head,-1,sizeof(head));
    for(int i=1;i<=m;i++){
        scanf("%d%d%d %c",&a,&b,&c,&cc);
        add(a,b,c);add(b,a,c);
    }
    int ans_max=0,ans_index=0;
    memset(dis,0,sizeof(dis));
    dfs(1,0);
    for(int i=1;i<=n;i++){
        if(dis[i]>ans_max){
            ans_max=dis[i];
            ans_index=i;
        }
    }
    memset(dis,0,sizeof(dis));
    dfs(ans_index,0);
    for(int i=1;i<=n;i++)
        if(dis[i]>ans_max)
            ans_max=dis[i];
    printf("%d\n",ans_max);
    return 0;
}
Two DFS

DFS is thinking twice before using any node as a root

Found from the depth of this node ANS_MAX and his farthest node position ANS_INDEX

And then to find this node as the root

Find out the depth of the node from his farthest, compared with ANS_MAX, we will be able to find the maximum diameter

 

Guess you like

Origin www.cnblogs.com/helman/p/11271948.html