1076 2条不相交的路径

本文介绍了如何使用Tarjan算法有效地解决寻找图中两条不相交路径的问题。强调了在应用算法时需要注意图是否为联通图,并提及dfn和low数组在算法中的关键作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给出一个无向图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
题解:tarjan跑强连通。因为没有重边所以只需要保证dfs的时候不要回到结点的父亲结点就可以了。

代码:

#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的时候要注意给出的图是否一定是联通图。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值