牛客 华华和月月逛公园(Tarjan找桥)

如题,在一个无向连通图中,只有桥是必须走的,其余的都可以不走,找出所有的桥,然后边的数量减掉桥的数量就可以。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <sstream>
#include <cstring>
#include <set>
#include <cctype>
#include <bitset>
#define IO                       \
    ios::sync_with_stdio(false); \
    // cin.tie(0);                  \
    // cout.tie(0);
using namespace std;
typedef long long LL;
const int maxn = 1e5 + 100;
const int maxm = 1e6 + 10;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const LL mod = 1e9 + 7;
int dis[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, 1, -1, 1, 1, -1, 1, -1, -1};
struct edge
{
    int before, to;
} e[maxn * 6];
int head[maxn], low[maxn], dfn[maxn];
int tim, k, ans;
void add(int u, int v)
{
    e[k].before = head[u];
    e[k].to = v;
    head[u] = k++;
}
void Tarjan(int u, int fa)
{
    low[u] = dfn[u] = ++tim;
    for (int i = head[u]; i != -1; i = e[i].before)
    {
        int v = e[i].to;
        if (v == fa)
            continue;
        if (!dfn[v])
        {
            Tarjan(v, u);
            low[u] = min(low[u], low[v]);
            if (low[v] > dfn[u])
                ans++;
        }
        else
            low[u] = min(low[u], dfn[v]);
    }
}
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
#endif
    int n, m, x, y;
    memset(head, -1, sizeof head);
    cin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        cin >> x >> y;
        add(x, y);
        add(y, x);
    }
    Tarjan(1, 0);
    printf("%d", m - ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44115065/article/details/106229590
今日推荐