Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 2350 | Accepted: 1152 |
Description
Input
Output
Sample Input
5 1 6 1 4 5 6 3 9 2 6 8 6 1 7
Sample Output
22
题意:求树的直径。。。裸的不能再裸了!
思路:两次BFS,第一次找S-T端点,第二次求树的直径。
AC代码:
#include <cstdio> #include <cstring> #include <queue> #include <algorithm> #define MAXN 10000+10 #define MAXM 100000000+10 using namespace std; struct Edge { int from, to, val, next; }; Edge edge[MAXM]; int head[MAXN], edgenum; int dist[MAXN]; bool vis[MAXN]; int node;//S-T路径的一个端点 int ans;//结果 void init() { edgenum = 0; memset(head, -1, sizeof(head)); } void addEdge(int u, int v, int w) { Edge E = {u, v, w, head[u]}; edge[edgenum] = E; head[u] = edgenum++; } int SPFA(int sx) { queue<int> Q; memset(dist, 0, sizeof(dist)); memset(vis, false, sizeof(vis)); vis[sx] = true; Q.push(sx); node = sx; ans = 0; while(!Q.empty()) { int u = Q.front(); Q.pop(); for(int i = head[u]; i != -1; i = edge[i].next) { Edge E = edge[i]; if(!vis[E.to] && dist[E.to] < dist[u] + E.val) { dist[E.to] = dist[u] + E.val; vis[E.to] = true; Q.push(E.to); if(dist[E.to] > ans) { ans = dist[E.to]; node = E.to; } } } } } void solve() { SPFA(1); SPFA(node); printf("%d\n", ans); } int main() { int a, b, c; init(); while(scanf("%d%d%d", &a, &b, &c) != EOF) { addEdge(a, b, c); addEdge(b, a, c); } solve(); return 0; }