POJ 1986 Distance Queries LCA
求两节点之间的距离,直接上Tarjan跑一遍。和上一题差不多就不说了。。
主要就是这里询问很多,用vector跑的很慢,无奈还不会邻接表,赶紧去学。。
1 #include <cstdio> 2 #include <cstring> 3 #include <vector> 4 #include <algorithm> 5 #include <iostream> 6 using namespace std; 7 const int maxn = 100005; 8 typedef long long LL; 9 struct node 10 { 11 int x,w; 12 }ans[maxn]; 13 vector<int>son[maxn]; 14 vector<node>f[maxn]; 15 vector<node>q[maxn]; 16 int d[maxn],vis[maxn],vis1[maxn],fa[maxn],anc[maxn]; 17 //void dfs(int rt) 18 //{ 19 // vis[rt] = 1; 20 // int len = f[rt].size(); 21 // for(int i = 0;i<len;++i) 22 // { 23 // int u = f[rt][i].x; 24 // if(vis[u])continue; 25 // son[rt].push_back(u); 26 // d[u] = d[rt]+f[rt][i].w; 27 // dfs(u); 28 // } 29 //} 30 int findd(int x) 31 { 32 int ret = x; 33 while(ret!=fa[ret])ret=fa[ret]; 34 while(x!=ret) 35 { 36 int t = fa[x]; 37 fa[x] = ret; 38 x = t; 39 } 40 return ret; 41 } 42 int cnt; 43 void lca(int rt) 44 { 45 vis1[rt] = 1; 46 int len = f[rt].size(); 47 for(int i = 0;i<len;++i)if(!vis1[f[rt][i].x]) 48 { 49 d[f[rt][i].x] = d[rt]+f[rt][i].w; 50 lca(f[rt][i].x); 51 fa[f[rt][i].x] = rt; 52 } 53 vis[rt] = 1;len = q[rt].size(); 54 for(int i = 0;i<len;++i) 55 { 56 int u = q[rt][i].w; 57 if(vis[u]==0)continue; 58 ans[cnt].x = q[rt][i].x; 59 ans[cnt++].w = d[rt]+d[u]-2*d[anc[findd(u)]]; 60 } 61 } 62 bool cmp(node a,node b) 63 { 64 return a.x<b.x; 65 } 66 int main() 67 { 68 int n,m; 69 scanf("%d%d",&n,&m); 70 memset(f,0,sizeof(f)); 71 memset(son,0,sizeof(son)); 72 memset(vis,0,sizeof(vis)); 73 memset(vis1,0,sizeof(vis1)); 74 memset(q,0,sizeof(q)); 75 memset(ans,0,sizeof(ans)); 76 for(int i = 1;i<=n;++i)fa[i] = i,anc[i] = i; 77 for(int i = 1;i<=m;++i) 78 { 79 char s[2]; 80 int x,y,w;scanf("%d%d%d%s",&x,&y,&w,s); 81 node a,b; 82 a.x = x;a.w = w; 83 b.x = y;b.w = w; 84 f[x].push_back(b); 85 f[y].push_back(a); 86 } 87 cnt = 0;scanf("%d",&m); 88 for(int i = 1;i<=m;++i) 89 { 90 int x,y;scanf("%d%d",&x,&y); 91 node a,b; 92 a.x = i;a.w = x;b.x = i;b.w = y; 93 if(x==y){ans[cnt].x = i;ans[cnt++].w = 0;continue;} 94 q[x].push_back(b); 95 q[y].push_back(a); 96 } 97 98 lca(1); 99 sort(ans,ans+m,cmp); 100 for(int i = 0;i<m;++i) 101 printf("%d\n",ans[i].w); 102 return 0; 103 }
弱者究竟为何而战?!