UVA10972 RevolC FaeLoN

题目链接

给定一个无向图,问最少添加多少条边,使得这个图成为连通图

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;
const int maxn = 1111;
vector<int> G[maxn], P[maxn];
int pre[maxn], bccno[maxn], dfs_clock, bcc_cnt;
int dfs1(int u, int fa){
    int lowu = pre[u] = ++dfs_clock;
    for (int i = 0; i < G[u].size(); i++){
        int v = G[u][i];
        if (!pre[v]){
            int lowv = dfs1(v, u);
            lowu = min(lowu, lowv);
            if (lowv > pre[u]){
                P[u].push_back(v);
                P[v].push_back(u);
            }
        }
        else if (pre[v] < pre[u] && v != fa)
            lowu = min(lowu, pre[v]);
    }
    return lowu;
}
void dfs2(int u, int fa){
    bccno[u] = bcc_cnt;
    for (int i = 0; i < G[u].size(); i++){
        int v = G[u][i];
        bool f = 1;
        for (int j = 0; j < P[u].size(); j++){
            int vv = P[u][j];
            if (v == vv){
                f = 0; break;
            }
        }
        if (!f || bccno[v]) continue;
        dfs2(v, u);
    }
}
void find_bcc(int n){
    memset(pre, 0, sizeof(pre));
    memset(bccno, 0, sizeof(bccno));
    dfs_clock = bcc_cnt = 0;
    for (int i = 0; i < n; i++)
        if (!pre[i]) dfs1(i, -1);
    for (int i = 0; i < n; i++)
        if (!bccno[i]){
            bcc_cnt += 1;
            dfs2(i, -1);
        }
}
int dg[maxn];
int main(){
    //freopen("in.txt", "r", stdin);
    int n, m;
    while(~scanf("%d%d", &n, &m)){
        for (int i = 0; i <= n; i++){
            G[i].clear(); P[i].clear();
        }
        for (int i = 0; i < m; i++){
            int x, y;
            scanf("%d%d", &x, &y);
            x -= 1; y -= 1;
            G[x].push_back(y);
            G[y].push_back(x);
        }
        find_bcc(n);
        memset(dg, 0, sizeof(dg));
        for (int u = 0; u < n; u++)
            for (int i = 0; i < G[u].size(); i++){
                int v = G[u][i];
                if (bccno[u] != bccno[v]) dg[bccno[u]] += 1;
            }
        int a = 0;
        for (int i = 1; i <= bcc_cnt; i++){
            if (dg[i] == 1) a += 1;
            if (dg[i] == 0) a += 2;
        }
        int ans = (a + 1) / 2;
        if (bcc_cnt == 1) ans = 0;
        printf("%d\n", ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值