2586.How far away ?
这个题以前写过在线LCA(ST)的,HDU2586.How far away ?-在线LCA(ST)
现在贴一个离线Tarjan版的
代码:
1 //A-HDU2586-LCA-tarjan离线版 2 #include<iostream> 3 #include<cstdio> 4 #include<cstring> 5 #include<algorithm> 6 #include<bitset> 7 #include<cassert> 8 #include<cctype> 9 #include<cmath> 10 #include<cstdlib> 11 #include<ctime> 12 #include<deque> 13 #include<iomanip> 14 #include<list> 15 #include<map> 16 #include<queue> 17 #include<set> 18 #include<stack> 19 #include<vector> 20 using namespace std; 21 typedef long long ll; 22 23 const double PI=acos(-1.0); 24 const double eps=1e-6; 25 const ll mod=1e9+7; 26 const int inf=0x3f3f3f3f; 27 const int maxn=4e4+10; 28 const int maxm=100+10; 29 #define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); 30 31 struct node{ 32 int x,y; 33 //node(int xx,int yy){ 34 // x=xx,y=yy; 35 //}node(){} 36 }; 37 38 vector<node> edge[maxn],q[maxn]; 39 int ans[maxn],dis[maxn],fa[maxn],vis[maxn]; 40 int n,m,aa,bb,cc; 41 42 int find(int x)//找父节点(祖先) 43 { 44 return x==fa[x]?x:fa[x]=find(fa[x]); 45 } 46 47 void unio(int x,int y)//并查集压缩路径 48 { 49 fa[find(y)]=find(x); 50 } 51 52 void init()//初始化 53 { 54 for(int i=1;i<=n;i++){ 55 edge[i].clear(); 56 q[i].clear(); 57 fa[i]=i;//初始化自己的父亲节点是自己 58 vis[i]=0; 59 ans[i]=0; 60 dis[i]=0; 61 } 62 } 63 64 void dfs(int x)//tarjan 65 { 66 vis[x]=1; 67 for(int i=0;i<edge[x].size();i++){ 68 int v=edge[x][i].x; 69 if(!vis[v]){ 70 dis[v]=dis[x]+edge[x][i].y; 71 dfs(v); 72 unio(x,v); 73 } 74 } 75 for(int i=0;i<q[x].size();i++){ 76 int v=q[x][i].x; 77 if(vis[v]) 78 ans[q[x][i].y]=dis[x]+dis[v]-2*dis[find(v)]; 79 } 80 } 81 82 int main() 83 { 84 int T; 85 scanf("%d",&T); 86 while(T--){ 87 scanf("%d%d",&n,&m); 88 init(); 89 for(int i=1;i<n;i++){ 90 scanf("%d%d%d",&aa,&bb,&cc); 91 //edge[aa].push_back(node(bb,cc)); 92 //edge[bb].push_back(node(aa,cc)); 93 edge[aa].push_back({bb,cc}); 94 edge[bb].push_back({aa,cc}); 95 } 96 for(int i=1;i<=m;i++){ 97 scanf("%d%d",&aa,&bb); 98 //q[aa].push_back(node(bb,i)); 99 //q[bb].push_back(node(aa,i)); 100 q[aa].push_back({bb,i}); 101 q[bb].push_back({aa,i}); 102 103 } 104 dfs(1); 105 for(int i=1;i<=m;i++) 106 printf("%d ",ans[i]); 107 } 108 }
溜了。