题意,你网上搜搜吧。。。
解法就是LCA 离线模版变形题
#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#include<string>
#include<cstdlib>
#include<algorithm>
using namespace std;
const int maxn=100012;//node
const int maxm=422222;//query
int n,m,head[maxn],Head[maxn],dis[maxn],vis[maxn],fa[maxn],ans[maxm],id[maxn],in[maxn],NE,cnt;
struct node
{
int v,d,next,pre;
} Edge[maxm],edge[maxm];
void addEdge(int u,int v,int d)
{
Edge[NE].v=v,Edge[NE].d=d,Edge[NE].next=head[u];
head[u]=NE++;
}
void addedge(int u,int v,int d,int pre)
{
edge[NE].v=v,edge[NE].d=d,edge[NE].pre=pre,edge[NE].next=Head[u];
Head[u]=NE++;
}
int find(int i)
{
return (fa[i]==i?i:fa[i]=find(fa[i]));
}
void Tarjan(int u)
{
vis[u] = 1;
fa[u] = u;
for (int i = Head[u]; i!=-1; i=edge[i].next)
{
int v=edge[i].v;
if(vis[v])
{
int rt=find(v); // 存的是最近公共祖先结点
if(edge[i].pre)
{
ans[edge[i].d]=dis[u]-dis[rt]+(v==rt?0:1);
}
else
{
ans[edge[i].d]=dis[v]-dis[rt]+(u==rt?0:1);
}
// cout<<"OK "<<edge[i].d<<" "<<ans[edge[i].d]<<endl;
}
}
for(int i= head[u]; i!=-1; i=Edge[i].next)
{
int v=Edge[i].v;
if(!vis[v])
{
dis[v] = dis[u] + Edge[i].d;
Tarjan(v);
fa[v] = u;
}
}
}
int main()
{
//freopen("//media/学习/ACM/input.txt","r",stdin);
int i,j,u,v,d,T;
cin>>T;
map<string,int> tar;
while(T--)
{
scanf("%d%d",&n,&m);
memset(head,-1,sizeof(int)*(n+1));
memset(Head,-1,sizeof(int)*(n+1));
memset(vis,0,sizeof(int)*(n+1));
memset(dis,0,sizeof(int)*(n+1));
memset(ans,0,sizeof(int)*(n+1));
memset(in,0,sizeof(int)*(n+1));
tar.clear();
string a,b;
int pos=1;
for(i=1; i<n; i++)
{
fa[i]=i;
cin>>a>>b;
if(tar[a]==0) tar[a]=pos++;
if(tar[b]==0) tar[b]=pos++;
u=tar[a];
v=tar[b];
in[u]++;
addEdge(v,u,1);
addEdge(u,v,1);
}
fa[n]=n;
for(NE=0,i=1; i<=m; i++)
{
cin>>a>>b;
u=tar[a];
v=tar[b];
addedge(u,v,i,1);
addedge(v,u,i,0);
}
for(cnt=1,i=1; i<=n; i++,cnt++)
{
if(!in[i])
{
Tarjan(i);
}
}
for(i=1; i<=m; i++)
{
printf("%d\n",ans[i]);
}
}
return 0;
}
/*
2
3 2
B A
C B
A C
C A
1 B
rt 2 A
3 C
*/