description
solution
tarjan缩环,一个环贡献2^1,跑lca即可。
code
#include
#include
#include
#include
#include
#define LL long long
#define fo(i,j,k) for(int i=j;i<=k;i++)
#define fd(i,j,k) for(int i=j;i>=k;i--)
#define fr(i,j) for(int i=begin[j];i;i=next[i])
using namespace std;
int const mn=1e5+9,mm=3*1e5+9,mo=1e9+7;
int n,m,q,gra,u[mm],v[mm],begin[mn],to[mm],next[mm],tim,dfn[mn],low[mn],st[mn],ins[mn],
lg2,f[mn],dep[mn],bel[mn],fa[mn][18],Pow[mn];
void insert(int u,int v){
to[++gra]=v;
next[gra]=begin[u];
begin[u]=gra;
}
void dfs(int p,int q){
dfn[p]=low[p]=++tim;
ins[st[++st[0]]=p]=1;
fr(i,p)if(i!=(q^1)){
if(!dfn[to[i]]){
dfs(to[i],i);
low[p]=min(low[p],low[to[i]]);
}else if(ins[to[i]])low[p]=min(low[p],dfn[to[i]]);
}
if(dfn[p]==low[p]){
f[p]=st[st[0]]!=p;
while(st[st[0]]!=p)bel[st[st[0]]]=p,ins[st[st[0]--]]=0;
bel[st[st[0]]]=p,ins[st[st[0]--]]=0;
}
}
void df2(int p,int q){
dfn[p]=1;
f[p]+=f[q];
dep[p]=dep[q]+1;
fa[p][0]=q;
fr(i,p)if(to[i]!=q)df2(to[i],p);
}
int lc(int u,int v){
if(dep[u]int uu=u,vv=v;
fd(i,lg2,0)if(dep[fa[u][i]]>=dep[v])u=fa[u][i];
if(u==v)return Pow[f[uu]-f[fa[vv][0]]];
fd(i,lg2,0)if(fa[u][i]!=fa[v][i])u=fa[u][i],v=fa[v][i];
return Pow[f[uu]+f[vv]-f[fa[u][0]]-f[fa[u][1]]];
}
int main(){
freopen("d.in","r",stdin);
freopen("d.out","w",stdout);
scanf("%d%d",&n,&m);
gra=1;
fo(i,1,m){
scanf("%d%d",&u[i],&v[i]);
insert(u[i],v[i]);
insert(v[i],u[i]);
}
fo(i,1,n)if(!dfn[i])dfs(i,0);
gra=1;
fo(i,1,n)begin[i]=dfn[i]=0;
fo(i,1,m)if(bel[u[i]]!=bel[v[i]]){
insert(bel[u[i]],bel[v[i]]);
insert(bel[v[i]],bel[u[i]]);
}
fo(i,1,n)if(!dfn[i])df2(i,0);
lg2=log(n)/log(2);
fo(j,1,lg2)fo(i,1,n)fa[i][j]=fa[fa[i][j-1]][j-1];
scanf("%d",&q);
Pow[0]=1;
fo(i,1,n)Pow[i]=Pow[i-1]*2%mo;
fo(cas,1,q){
int u,v;
scanf("%d%d",&u,&v);
printf("%d\n",lc(bel[u],bel[v]));
}
return 0;
}