POJ 1985 求树的直径 两边搜OR DP

Cow Marathon
Description

After hearing about the epidemic of obesity in the USA, Farmer John wants his cows to get more exercise, so he has committed to create a bovine marathon for his cows to run. The marathon route will include a pair of farms and a path comprised of a sequence of roads between them. Since FJ wants the cows to get as much exercise as possible he wants to find the two farms on his map that are the farthest apart from each other (distance being measured in terms of total length of road on the path between the two farms). Help him determine the distances between this farthest pair of farms.
Input

  • Lines 1…..: Same input format as “Navigation Nightmare”.
    Output

  • Line 1: An integer giving the distance between the farthest pair of farms.
    Sample Input

7 6
1 6 13 E
6 3 9 E
3 5 7 S
4 1 3 N
2 4 20 W
4 7 2 S
Sample Output

52
Hint

The longest marathon runs from farm 2 via roads 4, 1, 6 and 3 to farm 5 and is of length 20+3+13+9+7=52.
题意:给你一棵树,求树上的最长路(也就是直径)。


思路:一开始看见输入后面还有方向,顿时懵了。想了想,给了方向,但并没有路也是连不上的。剩下的两次BFS就OK了。(题目的数据范围在前一道题上),数组一定要开到数据范围的2倍!!(有向边,一开始没有注意到。G++无限RE,C++无限WA)


奉上代码。

#include <queue>
#include <cstdio>
#include <cstring>
using namespace std;
int tot=1,n,m,next[80005],first[40005],w[80005],vis[80005],v[80005],maxx,k;
void BFS()
{
    queue<int> q;
    memset(vis,0,sizeof(vis));maxx=0;
    q.push(k);
    while(!q.empty())
    {
        int t=q.front();q.pop();
        for(int i=first[t];i;i=next[i])
            if(!vis[v[i]]&&v[i]!=k)
                vis[v[i]]=vis[t]+w[i],q.push(v[i]);
    }
    for(int i=1;i<=n;i++)
        if(vis[i]>maxx)
            maxx=vis[i],k=i;
}
int main()
{
    int x;char s;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d%d %c",&x,&v[tot],&w[tot],&s);
        next[tot]=first[x];first[x]=tot++;w[tot]=w[tot-1];
        v[tot]=x;next[tot]=first[v[tot-1]];first[v[tot-1]]=tot++;
    }
    k=1,BFS(),BFS();
    printf("%d",maxx);
}

这里写图片描述
2016.10.23补充:
这里有一种DP做法
维护一个子树向下的最长链和次长链 (路径没有交)
f[x]表示最长链 g[x]表示次长链 ans=max(ans,f[x]+g[x]);

#include <queue>
#include <cstdio>
#include <cstring>
using namespace std;
int tot=1,n,m,next[80005],first[40005],w[80005],vis[80005],v[80005],ans;
int f[80005],g[80005];
void dfs(int x,int fa){
    for(int i=first[x];i;i=next[i]){
        if(v[i]==fa)continue;
        dfs(v[i],x);
        if(f[v[i]]+w[i]>f[x])g[x]=f[x],f[x]=f[v[i]]+w[i];
        else if(f[v[i]]+w[i]>g[x])g[x]=f[v[i]]+w[i];
    }
    ans=max(ans,f[x]+g[x]);
}
int main(){
    int x;char s;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++){
        scanf("%d%d%d %c",&x,&v[tot],&w[tot],&s);
        next[tot]=first[x];first[x]=tot++;w[tot]=w[tot-1];
        v[tot]=x;next[tot]=first[v[tot-1]];first[v[tot-1]]=tot++;
    }
    dfs(1,-1);
    printf("%d",ans);
}

这里写图片描述

原文地址:https://www.cnblogs.com/SiriusRen/p/6532489.html