Poj 1985 Cow Marathon ( 树的直径

来源:互联网 发布:mac 安装java环境 编辑:程序博客网 时间:2024/06/05 07:26

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

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 61 6 13 E6 3 9 E3 5 7 S4 1 3 N2 4 20 W4 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.

题意

N个点M条边,每条边都有权值,让你找到两点,使得这两点间所有边的权值之和最长,

题解:

裸的树的直径 ZZ了 纠结后面那个方向半天 其实并不用TAT
vector存图真的很方便哈哈哈

###AC代码
#include <cstdio>#include <iostream>#include <vector>#include <queue>#include <cstring>#include <algorithm>using namespace std;#define LL long long#define CLR(a, b) memset(a, (b), sizeof(a))const int N = 5e5;struct node {    int t, val;};vector<node> v[N];bool vis[N];int dis[N];int ans, res;void bfs(int x){    CLR(dis,0);    CLR(vis,false);    res = 0;    queue<int> q;    q.push(x);    vis[x] = true;    while(!q.empty()) {        int p = q.front();        q.pop();        if(dis[p] > ans) {            ans = dis[p];            res = p;        }        for(int i = 0;i < v[p].size(); i++) {            node x = v[p][i];            if(!vis[x.t]) {                vis[x.t] = true;                dis[x.t] = dis[p] + x.val;                q.push(x.t);            }        }    }}int main(){    //ios::sync_with_stdio(false);    int n, m;    while(~scanf("%d%d",&n,&m)) {        for(int i = 0; i<= n; i++) v[i].clear();        int x, y, z; char c;        for(int i = 0;i < m; i++) {            scanf("%d%d%d %c",&x,&y,&z,&c);            v[x].push_back((node){y,z});            v[y].push_back((node){x,z});        }        ans = 0;        bfs(1);        ans = 0;        bfs(res);        printf("%d\n",ans);    }return 0;}
原创粉丝点击