标签:
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 3930 Accepted Submission(s): 700
#include<iostream> #include<cstdio> #include<cstring> #include<queue> using namespace std; const int N = 100005; const int M = 2000005; int father[N]; struct Edge { int v,w,next; } edge[M]; int head[N]; int n,m,tot; void addEdge(int u,int v,int w,int &k) { edge[k].v = v,edge[k].w = w,edge[k].next = head[u],head[u] = k++; } int _find(int x) { if(x!=father[x]) father[x] = _find(father[x]); return father[x]; } void init() { tot = 0; for(int i=1; i<=n; i++) { father[i] = i; head[i] = -1; } } int dis[N]; bool vis[N]; bool used[N]; void bfs(int s) { memset(vis,false,sizeof(vis)); queue<int>q; q.push(s); vis[s] = true; while(!q.empty()) { int u = q.front(); q.pop(); for(int k = head[u]; k!=-1; k=edge[k].next) { int w = edge[k].w,v = edge[k].v; if(!vis[v]) { used[v] = true; vis[v] = true; q.push(v); dis[v] = max(dis[v],dis[u]+w); } } } } int main() { while(scanf("%d%d",&n,&m)!=EOF) { if(n==0) { printf("0\n"); continue; } init(); bool flag = false; for(int i=1; i<=m; i++) { int u,v,w; scanf("%d%d%d",&u,&v,&w); addEdge(u,v,w,tot); addEdge(v,u,w,tot); if(!flag) { int ru = _find(u); int rv = _find(v); if(ru==rv) flag = true; else father[ru] = rv; } } if(flag) { printf("YES\n"); continue; } memset(used,false,sizeof(used)); int res = 0; for(int i=1; i<=n; i++) { if(used[i]) continue; int s=i,t; used[s] = true; memset(dis,0,sizeof(dis)); bfs(s); int len = 0; for(int i=1; i<=n; i++) { if(dis[i]>len) { len = dis[i]; t = i; } } memset(dis,0,sizeof(dis)); bfs(t); int MAX = 0; for(int i=1; i<=n; i++) { MAX = max(dis[i],MAX); } res = max(res,MAX); } printf("%d\n",res); } return 0; }
标签:
原文地址:http://www.cnblogs.com/liyinggang/p/5616453.html