标签:
Time Limit: 2000MS | Memory Limit: 30000K | |
Total Submissions: 4182 | Accepted: 2116 | |
Case Time Limit: 1000MS |
Description
Input
Output
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
第一道树的直径题
#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