HDU 2586 LCA
算是LCA裸题吧,d[x]记录从根节点到x节点的距离然后求出x,y的LCA z
结果就是d[x]+d[y]-2*d[z]
我是用Tarjan写的,麻烦的地方就是怎么离线ans
刚开是学LCA,cheerup!!
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 node(){} 13 node(int a,int b) 14 { 15 x = a;w = b; 16 } 17 }ans[maxn]; 18 vector<int>son[maxn]; 19 vector<node>f[maxn]; 20 vector<node>q[maxn]; 21 int d[maxn],vis[maxn],fa[maxn],anc[maxn]; 22 void dfs(int rt) 23 { 24 vis[rt] = 1; 25 int len = f[rt].size(); 26 for(int i = 0;i<len;++i) 27 { 28 int u = f[rt][i].x; 29 if(vis[u])continue; 30 son[rt].push_back(u); 31 d[u] = d[rt]+f[rt][i].w; 32 dfs(u); 33 } 34 } 35 int findd(int x) 36 { 37 int ret = x; 38 while(ret!=fa[ret])ret=fa[ret]; 39 while(x!=ret) 40 { 41 int t = fa[x]; 42 fa[x] = ret; 43 x = t; 44 } 45 return ret; 46 } 47 int cnt; 48 void lca(int rt) 49 { 50 for(int i = 0;i<son[rt].size();++i) 51 { 52 lca(son[rt][i]); 53 fa[son[rt][i]] = rt; 54 } 55 vis[rt] = 1; 56 for(int i = 0;i<q[rt].size();++i) 57 { 58 int u = q[rt][i].w; 59 if(vis[u]==0)continue; 60 ans[cnt].x = q[rt][i].x; 61 ans[cnt++].w = d[rt]+d[u]-2*d[anc[findd(u)]]; 62 } 63 } 64 bool cmp(node a,node b) 65 { 66 return a.x<b.x; 67 } 68 int main() 69 { 70 // freopen("in.txt","r",stdin); 71 int T;scanf("%d",&T); 72 while(T--) 73 { 74 int n,m;scanf("%d%d",&n,&m); 75 memset(f,0,sizeof(f)); 76 memset(son,0,sizeof(son)); 77 memset(vis,0,sizeof(vis)); 78 memset(q,0,sizeof(q)); 79 memset(ans,0,sizeof(ans)); 80 for(int i = 1;i<=n;++i)fa[i] = i,anc[i] = i; 81 for(int i = 1;i<n;++i) 82 { 83 int x,y,w;scanf("%d%d%d",&x,&y,&w); 84 f[x].push_back(node(y,w)); 85 f[y].push_back(node(x,w)); 86 } 87 d[0] = 0;dfs(1);memset(vis,0,sizeof(vis)); 88 for(int i = 1;i<=m;++i) 89 { 90 int x,y;scanf("%d%d",&x,&y); 91 q[x].push_back(node(i,y)); 92 q[y].push_back(node(i,x)); 93 } 94 cnt = 0; 95 lca(1); 96 sort(ans,ans+m,cmp); 97 for(int i = 0;i<cnt;++i) 98 printf("%d\n",ans[i].w); 99 } 100 return 0; 101 }
弱者究竟为何而战?!