基准时间限制:1 秒 空间限制:131072 KB 分值: 40 难度:4级算法题
给出一个无向图G的顶点V和边E。进行Q次查询,查询从G的某个顶点V[s]到另一个顶点V[t],是否存在2条不相交的路径。(两条路径不经过相同的边)
(注,无向图中不存在重边,也就是说确定起点和终点,他们之间最多只有1条路)
Input
第1行:2个数M N,中间用空格分开,M是顶点的数量,N是边的数量。(2 <= M <= 25000, 1 <= N <= 50000)
第2 - N + 1行,每行2个数,中间用空格分隔,分别是N条边的起点和终点的编号。例如2 4表示起点为2,终点为4,由于是无向图,所以从4到2也是可行的路径。
第N + 2行,一个数Q,表示后面将进行Q次查询。(1 <= Q <= 50000)
第N + 3 - N + 2 + Q行,每行2个数s, t,中间用空格分隔,表示查询的起点和终点。
Output
共Q行,如果从s到t存在2条不相交的路径则输出Yes,否则输出No。
Input示例
4 4
1 2
2 3
1 3
1 4
5
1 2
2 3
3 1
2 4
1 4
Output示例
Yes
Yes
Yes
No
No
代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<map>
#define maxx 100050
#define maxn 25005
#define ll long long
#define mod 1000000007
#define INF 0x3f3f3f3f
using namespace std;
int head[maxn];
int to[maxx],_next[maxx];
int cnt=1;
void addEdge(int x,int y)
{
to[++cnt]=y,_next[cnt]=head[x],head[x]=cnt;
to[++cnt]=x,_next[cnt]=head[y],head[y]=cnt;
}
int dfn[maxn],low[maxn];
bool bridge[maxx];
int index;
void tarjan(int x,int edge)
{
dfn[x]=low[x]=++index;
for(int i=head[x];~i;i=_next[i])
{
int y=to[i];
if(!dfn[y])
{
tarjan(y,i);
low[x]=min(low[x],low[y]);
if(dfn[x]<low[y])
bridge[i]=bridge[i^1]=true;
}
else
if(i!=(edge^1))
low[x]=min(low[x],dfn[y]);
}
}
int be[maxn],deg[maxn];
int _count=0;
void dfs(int x)
{
be[x]=_count;
for(int i=head[x];~i;i=_next[i])
{
//cout<<i<<endl;
int y=to[i];
if(bridge[i]||be[y])
continue;
dfs(y);
}
}
void init()
{
memset(head,-1,sizeof(head));
}
int main()
{
int n,m;
cin>>n>>m;
int x,y;
init();
for(int i=0;i<m;i++)
{
scanf("%d%d",&x,&y);
addEdge(x,y);
}
for(int i=1;i<=n;i++)
if(!be[i])tarjan(i,0);
for(int i=1;i<=n;i++)
if(!be[i])
{
++_count;
dfs(i);
}
int q;
cin>>q;
while(q--)
{
scanf("%d%d",&x,&y);
if(be[x]==be[y])
cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
return 0;
}