#include <iostream>
#include <cstring>
#include <cstdlib>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <iomanip>
#include <list>
#include <deque>
#include <stack>
#define ull unsigned long long
#define ll long long
#define mod 90001
#define INF 0x3f3f3f3f
#define maxn 40000+10
#define cle(a) memset(a,0,sizeof(a))
const ull inf = 1LL << 61;
const double eps=1e-5;
using namespace std;
bool cmp(int a,int b){
return a>b;
}
int fa[maxn],n,m,pre[maxn],l;
int lca[1000][1000];
struct node{
int v,next;
}edge[maxn+100];
void add(int u,int v){
edge[l].v=v;
edge[l].next=pre[u];
pre[u]=l++;
}
int findfa(int x){
if(x==fa[x])return x;
else return fa[x]=findfa(fa[x]);
}
void Union(int x,int y){
x=findfa(x);
y=findfa(y);
fa[y]=x;
}
void dfs(int u){
int v;
fa[u]=u;
for(int i=pre[u];i+1;i=edge[i].next){
v=edge[i].v;
if(fa[v]==-1){
dfs(v);
Union(u,v);
}
}
for(v=1;v<=n;v++){
if(fa[v]!=-1){
lca[u][v]=lca[v][u]=findfa(v);
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
//freopen("out.txt","w",stdout);
int t;
cin>>t;
int x,y,k;
while(t--){
scanf("%d%d%d",&n,&m,&k);
l=0;
memset(fa,-1,sizeof fa);
memset(pre,-1,sizeof pre);
for(int i=1;i<=m;i++){
cin>>x>>y;
add(x,y);
add(y,x);
}
dfs(1);
for(int i=1;i<=k;i++){
cin>>x>>y;
cout<<lca[x][y]<<endl;
}
}
return 0;
}
LCA模板
最新推荐文章于 2024-04-01 21:48:50 发布