[USACO06JAN] The Cow Prom S

CSP第2轮模板代码

Luogu P2863 [USACO06JAN] The Cow Prom S

题目描述

有一个 \(n\) 个点,\(m\) 条边的有向图,请求出这个图点数大于 \(1\) 的强连通分量个数。

输入格式

第一行为两个整数 \(n\) 和 \(m\)。

第二行至 \(m+1\) 行,每一行有两个整数 \(a\) 和 \(b\),表示有一条从 \(a\) 到 \(b\) 的有向边。

输出格式

仅一行,表示点数大于 \(1\) 的强连通分量个数。

输入输出样例 #1

输入 #1

5 4
2 4
3 5
1 2
4 1

输出 #1

1

说明/提示

数据规模与约定

对于全部的测试点,保证 \(2\le n \le 10^4\),\(2\le m\le 5\times 10^4\),\(1 \leq a, b \leq n\)。

Code

板题

#include <bits/stdc++.h>
#define maxn 10001
#define maxm 100001

using namespace std;

int n, m, cnt, ans, head[maxn], to[maxm], nxt[maxm];
int dfn[maxn], low[maxn], t;
stack<int> s;
bool ins[maxn];
int scccnt, sccsize[maxn];

void add(int u, int v)
{
    to[++cnt] = v;
    nxt[cnt] = head[u];
    head[u] = cnt;
}

void tarjan(int u)
{
    dfn[u] = low[u] = ++t;
    s.push(u);
    ins[u] = 1;
    for (int i = head[u]; i; i = nxt[i])
    {
        int v = to[i];
        if (!dfn[v])
        {
            tarjan(v);
            low[u] = min(low[u], low[v]);
        }
        else if (ins[v])
        {
            low[u] = min(low[u], dfn[v]);
        }
    }
    if (low[u] == dfn[u])
    {
        scccnt++;
        while (1)
        {
            int x = s.top();
            s.pop();
            ins[x] = 0;
            sccsize[scccnt]++;
            if (x == u)
            {
                break;
            }
        }
    }
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int a, b;
        cin >> a >> b;
        add(a, b);
    }
    for (int i = 1; i <= n; i++)
    {
        if (!dfn[i])
        {
            tarjan(i);
        }
    }
    for (int i = 1; i <= scccnt; i++)
    {
        if (sccsize[i] > 1)
        {
            ans++;
        }
    }
    cout << ans;
    return 0;
}
posted @ 2026-10-27 21:03  Accepted01  阅读(9)  评论(0)    收藏  举报