给出一个无向图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 <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <map>
#include <cmath>
#include <ctime>
using namespace std;
typedef long long ll;
typedef pair<ll, int> P;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-10;
const int maxn = 3e4+7;
const int mod = 1e9+7;
vector<int> g[maxn];
int dfn[maxn],low[maxn],vis[maxn],cnt,n,m;
stack<int> sta;
int u[maxn],sum;
void tarjan(int x,int bef){
sta.push(x);
vis[x] = 1;
dfn[x] = ++cnt;
low[x] = dfn[x];
for(int i = 0;i < g[x].size();i++){
int to = g[x][i];
if(to==bef) continue;
if(!dfn[to]){
tarjan(to,x);
low[x] = min(low[x],low[to]);
}
else if(vis[x]){
low[x] = min(low[x],dfn[to]);
}
}
if(dfn[x]==low[x]){
int now;
do{
now = sta.top();
sta.pop();
vis[now] = 0;
u[now] = sum;
}while(now!=x);
sum++;
}
}
void init()
{
cnt = 0,sum = 1;
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
memset(vis,0,sizeof(vis));
for(int i = 1;i <= n;i++){
if(!dfn[i]){
tarjan(i,-1);
}
}
}
int main()
{
int q,a,b;
scanf("%d %d",&n,&m);
for(int i = 0;i < m;i++){
scanf("%d %d",&a,&b);
g[a].push_back(b);
g[b].push_back(a);
}
init();
scanf("%d",&q);
while(q--){
scanf("%d %d",&a,&b);
if(u[a]==u[b]){
puts("Yes");
}
else puts("No");
}
return 0;
}
涉及的算法:
tarjan。很好解决了强连通问题,注意dfn和low数组。
经验:跑tarjan的时候要注意给出的图是否一定是联通图。