码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 1985--Cow Marathon【树的直径 && 模板】

时间:2015-08-17 19:40:01      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

Cow Marathon
Time Limit: 2000MS   Memory Limit: 30000K
Total Submissions: 4182   Accepted: 2116
Case Time Limit: 1000MS

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. 

第一道树的直径题

#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <queue>
#define maxn 40000+10
#define maxm 80000+10
#define INF 0x3f3f3f3f
using namespace std;

struct node{
    int u, v, w, next;
};

node edge[maxm];
int head[maxn], cnt;
int dist[maxn], vis[maxn];
int n, m;
int sum, ed ;

void init(){
    cnt = 0;
    memset(head, -1, sizeof(head));
}

void add(int u, int v, int w){
    edge[cnt] = {u, v, w, head[u]};
    head[u] = cnt++;
    edge[cnt] = {v, u, w, head[v]};
    head[v] = cnt++;
}

void getmap(){
    char str[5];
    while(m--){
        int a, b, c;
        scanf("%d%d%d%s", &a, &b, &c, str);
        add(a, b, c);
    }
}

void bfs(int sx){
    queue<int>q;
    for(int i = 1; i <= n; ++i){
        vis[i] = 0;
        dist[i] = 0;
    }
    vis[sx] = 1;
    sum = 0;
    ed = sx;
    q.push(sx);
    while(!q.empty()){
        int u = q.front();
        q.pop();
        for(int i = head[u]; i != -1 ;i = edge[i].next){
            int v = edge[i].v;
            if(!vis[v]){
                dist[v] = dist[u] + edge[i].w;
                if(sum < dist[v]){
                    ed = v;
                    sum = dist[v];
                }
                vis[v] = 1;
                q.push(v);
            }
        }
    }
}

int main (){
    while(scanf("%d%d", &n, &m) != EOF){
        init();
        getmap();
        bfs(1);
        bfs(ed);
        printf("%d\n", sum);
    }
    return 0;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

POJ 1985--Cow Marathon【树的直径 && 模板】

标签:

原文地址:http://blog.csdn.net/hpuhjh/article/details/47728205

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!