How far away ?Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 23857 Accepted Submission(s): 9506 Problem Description There are n houses in the village and some bidirectional roads connecting them. Every day peole always like to ask like this "How far is it if I want to go from house A to house B"? Usually it hard to answer. But luckily int this village the answer is always unique, since the roads are built in the way that there is a unique simple path("simple" means you can't visit a place twice) between every two houses. Yout task is to answer all these curious people. Input First line is a single integer T(T<=10), indicating the number of test cases. Output For each test case,output m lines. Each line represents the answer of the query. Output a bland line after each test case. Sample Input 2 3 2 1 2 10 3 1 15 1 2 2 3 2 2 1 2 100 1 2 2 1 Sample Output 10 25 100 100 |
LCA离线做法的板子 Tarjan算法(DFS+并查集)
#include<cstdio>
#include<cmath>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<map>
#include<vector>
#define N 100005
using namespace std;
int father[40010*2],vis[40010*2],dir[40010*2];
int head[40010*2],head1[40010*2];
int z,zz;
int n,m;
struct ac
{
int u,v,w,lca;
int next;
}r[40010*2],rr[40010*2];
// 数组模拟邻接表
void add(int u,int v,int w)
{
r[z].v=v;
r[z].u=u;
r[z].w=w;
r[z].next=head[u];
head[u]=z++;
}
void add1(int u,int v)
{
rr[zz].v=v;
rr[zz].u=u;
rr[zz].lca=-1;
rr[zz].next=head1[u];
head1[u]=zz++;
}
void init()
{
z=zz=0;
memset(vis,0,sizeof(vis));
memset(dir,0,sizeof(dir));
memset(head,-1,sizeof(head));
memset(head1,-1,sizeof(head1));
for(int i=1;i<=n;i++)
father[i]=i;
}
// 并查集
int find(int w)
{
if(w==father[w])
return w;
return father[w]=find(father[w]);
}
void link(int x,int y)
{
int nx=find(x);
int ny=find(y);
if(nx!=ny)
father[ny]=nx;
}
void tarjan(int cur)
{
vis[cur]=1;
for(int i=head[cur];i+1;i=r[i].next)
{
int v=r[i].v;
int w=r[i].w;
if(!vis[v])
{
dir[v]=dir[cur]+w;//子节点距离=父节点距离+w ;
tarjan(v); // 递归
link(cur,v);// 建图
}
}
//访问所有和u有询问关系的e
for(int i=head1[cur];i+1;i=rr[i].next)
{
int v=rr[i].v;
if(vis[v])// 如果e被访问过;
{
// 最近公共祖先
rr[i].lca=find(v);//rr[i].lca=rr[i^1].lca=find(v);
//u,e的最近公共祖先为find(v)
}
}
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>n>>m;
init();
// 输入建树
for(int i=1;i<n;i++)
{
int u,v,w;
cin>>u>>v>>w;
add(u,v,w);
add(v,u,w);
}
// 询问
for(int i=0;i<m;i++)
{
int u,v;
cin>>u>>v;
add1(u,v);
add1(v,u);
}
dir[1]=0;
tarjan(1);
for(int i=0;i<m;i++)
{
int s=i*2,u=rr[s].u,v=rr[s].v,lca=rr[s].lca;
// 路途
printf("%d\n",dir[u]+dir[v]-2*dir[lca]);
}
}
return 0;
}