标签:
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8041 Accepted Submission(s): 1994
#include <cstdio> #include <cstring> #define N 10010 #define M 20010 #define C 2000010 struct Edge{ int to, next, dis; Edge() {} Edge(int to, int dis, int next): to(to), dis(dis), next(next){}; }E[M]; struct Edge2{ int to, next, w; Edge2() {} Edge2(int to, int w, int next): to(to), w(w), next(next) {}; }E2[C]; int n, m, c, tot, tot2; int head[N], head2[N], dis[N], f[N], vis[N]; void addEdge(int u, int v, int dis){ E[tot]= Edge(v, dis, head[u]); head[u]=tot++; E[tot]= Edge(u, dis, head[v]); head[v]=tot++; } void addEdge2(int u, int v){ E2[tot2]= Edge2(v, -1, head2[u]); head2[u]=tot2++; E2[tot2]= Edge2(u, -1, head2[v]); head2[v]=tot2++; } /*void addEdge(int u, int v, int dis) { E[tot].to = v; E[tot].next = head[u]; E[tot].dis = dis; head[u] = tot++; u = u ^ v; v = u ^ v; u = u ^ v; E[tot].to = v; E[tot].next = head[u]; E[tot].dis = dis; head[u] = tot++; } void addEdge2(int u, int v) { E2[tot2].to = v; E2[tot2].next = head2[u]; E2[tot2].w = -1; head2[u] = tot2++; u = u ^ v; v = u ^ v; u = u ^ v; E2[tot2].to = v; E2[tot2].next = head2[u]; E2[tot2].w = -1; head2[u] = tot2++; }*/ void init() { memset(head, -1, sizeof(head)); memset(head2, -1, sizeof(head2)); tot=tot2=0; int u, v, d; for(int i=0; i< m; i++) { scanf("%d%d%d", &u, &v, &d); addEdge(u, v, d); } for(int i=0; i<c; i++) { scanf("%d%d", &u, &v); addEdge2(u, v); } memset(vis, 0, sizeof(vis)); } int find(int x){ return x==f[x]? x: f[x]=find(f[x]); } void tarjan(int u, int time) { vis[u]= time; f[u]= u; int v; for(int i=head[u]; ~i; i=E[i].next) { v=E[i].to; if(vis[v]) continue; dis[v]= dis[u]+ E[i].dis; tarjan(v, time); f[v]= u; } for(int i= head2[u]; ~i; i=E2[i].next) { v=E2[i].to; if(vis[v]== time) E2[i].w= E2[i^1].w = dis[u]+dis[v]- 2*dis[find(v)]; } } void solve() { int cnt=1; for(int i=1; i<=n; i++){ if(!vis[i]){ dis[i]= 0; tarjan(i, cnt); } cnt++; } for(int i=0; i< tot2; i +=2){ if(E2[i].w == -1) printf("Not connected\n"); else printf("%d\n", E2[i].w) ; } } int main() { while(scanf("%d%d%d", &n, &m, &c) != EOF) { init(); solve(); } return 0; }
hdoj2874 -- Connections between cities(LCA--tarjan离线)
标签:
原文地址:http://www.cnblogs.com/fengshun/p/5369609.html