POJ 2631 Roads in the North 树上最长路 树型DP

来源:互联网 发布:keep 知乎 编辑:程序博客网 时间:2024/06/04 18:50

Building and maintaining roads among communities in the far North is an expensive business. With this in mind, the roads are build such that there is only one route from a village to a village that does not pass through some other village twice. 
Given is an area in the far North comprising a number of villages and roads among them such that any village can be reached by road from any other village. Your job is to find the road distance between the two most remote villages in the area. 

The area has up to 10,000 villages connected by road segments. The villages are numbered from 1. 
Input
Input to the problem is a sequence of lines, each containing three positive integers: the number of a village, the number of a different village, and the length of the road segment connecting the villages in kilometers. All road segments are two-way.
Output
You are to output a single integer: the road distance between the two most remote villages in the area.
Sample Input
5 1 61 4 56 3 92 6 86 1 7
Sample Output
22

        其实也是一个树型DP的板题。。

        两次DFS/BFS也是可以的,这里特用了DP的方法做的

        首先任意选择一个节点为根,就变成了一个有根树,然后定义状态dp[i]表示节点i到节点i的子树的最深距离

        对于每一个节点i,通过i的最长路径就是dp[u]+dp[v]+cost(i,u)+cost(i,v)其中u和v是i的儿子且dp[u]和dp[v]是i的的所有儿子中dp最大的那两个,假若i仅仅由一个儿子,那么dp[v]和cost(i,v)都是0

        其基本思想是转化。。。把最长路转化为两条最长路然后相加。

        因为比较简单,所以不算100道动态规划

#include <iostream>#include <algorithm>#include <cstring>using namespace std;const int maxm=1E4+10;struct Edge{    int nt,v,c;    explicit Edge(int a=0,int b=0,int d=0):nt(a),v(b),c(d){};}edge[maxm<<1];int fi[maxm],dp[maxm],ind,x,y,cost,ans;void addeage(),dfs(int i,int fa);int main(){    ios_base::sync_with_stdio(0);    while(cin>>x>>y>>cost)addeage();    dfs(1,0);    cout<<ans<<endl;    return 0;}void addeage(){    edge[++ind]=Edge(fi[x],y,cost);    fi[x]=ind;    edge[++ind]=Edge(fi[y],x,cost);    fi[y]=ind;}void dfs(int i,int fa){    int max1=0,max2=0;    for(int j=fi[i];j;j=edge[j].nt)    if(edge[j].v!=fa){        dfs(edge[j].v,i);        if(dp[i]==0||dp[i]<dp[edge[j].v]+edge[j].c)            dp[i]=dp[edge[j].v]+edge[j].c;        if(edge[j].c+dp[edge[j].v]>max1)            max2=max1,max1=edge[j].c+dp[edge[j].v];        else if(edge[j].c+dp[edge[j].v]>max2)            max2=edge[j].c+dp[edge[j].v];    }    ans=max(ans,max1+max2);}



0 0
原创粉丝点击