tarjan——双连通

首先建立模型:

给定一个连通的无向图G,至少要添加几条边,才能使其变为边-双连通图

在去找边双连通分量的时候,运用low值相同会处于同一边双连通分量中,用割点式的tarjan算法

void tarjan(int x, int p)
{
    dfn[x] = low[x] = ++cnt;
    vis[x] = 1;
    for (int i = 0; i < vc[x].size(); ++i)
    {
        int y = vc[x][i];
        if (y == p)
            continue;
        if (!vis[y])
        {
            tarjan(y, x);
            low[x] = min(low[x], low[y]);
        }
        else
            low[x] = min(low[x], dfn[y]);
    }
}

总结分析就是,缩点,将所有叶子节点成对连接即可:ans=(x+1)/2

对于一个例题:http://poj.org/problem?id=3352

一个分析得很好的博客:https://blog.csdn.net/qq_37862149/article/details/79639257

自己的代码和分析:

//#include <bits/stdc++.h>
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
#define N 2021
#define mt(x) memset(x, 0, sizeof x)
typedef long long ll;
void cn(ll x) { cout << x << endl; }
void cs(string x) { cout << x << endl; }
vector<int> vc[N];
int dfn[N], low[N], vis[N], cnt;
int du[N];
void tarjan(int x, int p)
{
    dfn[x] = low[x] = ++cnt;
    vis[x] = 1;
    for (int i = 0; i < vc[x].size(); ++i)
    {
        int y = vc[x][i];
        if (y == p)
            continue;
        if (!vis[y])
        {
            tarjan(y, x);
            low[x] = min(low[x], low[y]);
        }
        else
            low[x] = min(low[x], dfn[y]);
    }
}
void solve()
{
    /*
    analyse:
    问:在缺少目前任意一条路的情况下,保证连通的最少添加边数
    无向图,连通
    在一个强连通块中,是可以满足缺少任意一边仍然连通的,
    也即
    添加最少边,构造双连通图
    缩点,对于所有叶子节点成对连接
    */
    int n, r;
    cin >> n >> r;
    cnt = 0;
    for (int i = 1; i <= r; ++i)
    {
        int x, y;
        cin >> x >> y;
        vc[x].push_back(y);
        vc[y].push_back(x);
    }
    tarjan(1, -1); //保证连通直接tarjan一次图
    for (int i = 1; i <= n; ++i)
    {
        for (int j = 0; j < vc[i].size(); ++j)
        {
            int y = vc[i][j];
            if (low[i] != low[y])
                du[low[i]]++;
        }
    }
    int ans = 0;
    for (int i = 1; i <= n; ++i)
        if (du[i] == 1)
            ans++;
    cn((ans + 1) / 2);//叶节点成对加边
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    solve();
    return 0;
}

 

posted @ 2021-07-20 18:05  Renhr  阅读(78)  评论(0)    收藏  举报