2017.10.12. DFS求树的直径

DFS求树的直径

适用题型:
1.求树的直径
2.求数的最长琏

样题:

Cow Marathon【树的直径模板】
题目背景
POJ1985

题目描述
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.

输入格式
* Line 1: Two space-separated integers: N and M.

  • Lines 2..M+1: Each line contains four space-separated entities, F1,F2,L,and D that describe a
    road.F1 and F2 are numbers of two farms connected by a road, L is its length, and D is a character
    that is either ‘N’, ‘E’, ‘S’, or ‘W’ giving the direction of the road from F1 to F2.

输出格式
* Line 1: An integer giving the distance between the farthest pair of farms.

样例数据 1
输入  [复制]

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
输出

52
备注
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.

std.cpp:

#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;

const int kkk = 1000050;

int n,k,x,u,v,val;
int first[kkk];
struct node{int u,v,val,next;}side[2*kkk];

int cnt=0;
void addedge(int u,int v,int val)
{
    side[++cnt].u = u;
    side[cnt].v = v;
    side[cnt].val = val;
    side[cnt].next = first[u];
    first[u] = cnt;
}

bool visit[kkk];
int head=0,tail=0;
int p[kkk],dis[kkk];
int s1,t1,s[kkk],t[kkk];
void spfa()
{
    memset(visit,0,sizeof(visit));
    memset(dis,127,sizeof(dis));

    for(int i=1;i<=s1;i++)
    {
        dis[s[i]]=0;                      
        p[++tail]=s[i];                      
        visit[s[i]]=true;
    }

    while(headfalse;
        for(int i=first[p[head]];i;i=side[i].next)
        {
            u = side[i].u;
            v = side[i].v;
            if(dis[v]>dis[u]+side[i].val)               
            {
                dis[v] = dis[u]+side[i].val;                
                if(!visit[v])   
                {
                    tail++;             
                    p[tail]=v;  
                    visit[v]=true;  
                }
            }
        }
    }   
}

int main() //主程序,SPFA
{
    cin >> n >> k;
    for(int i=1;i<=k;i++)
    {
        char c;
        cin >> u >> v >> val >> c;
        addedge(u,v,val);
        addedge(v,u,val);
    }

    s1=1;   s[1]=1; spfa();

    int jud=0;
    for(int i=1;i<=n;i++)if(dis[i]>jud)
        s[1]=i,jud=dis[i];

    spfa();

    int ans=0;
    for(int i=1;i<=n;i++)ans=max(ans,dis[i]);

    cout << ans << endl;
    return 0;
}

你可能感兴趣的:(dfs,NOIP常用模板)