洛谷 P2863 [USACO06JAN]牛的舞会The Cow Prom

洛谷 P2863 [USACO06JAN]牛的舞会The Cow Prom

Description

  • 这题废话贼多

    给出一个有向图G,问有多少个大小>1的强连通分量

Input

  • Line 1: Two space-separated integers: N and M

    Lines 2..M+1: Each line contains two space-separated integers A and B that describe a rope from cow A to cow B in the clockwise direction.

Output

  • Line 1: A single line with a single integer that is the number of groups successfully dancing the Round Dance.

Sample Input

5 4
2 4
3 5
1 2
4 1

Sample Output

1

题解:

  • tarjan裸题。
#include <iostream>
#include <cstdio>
#include <stack>
#define N 50005
using namespace std;

struct E {int next, to;} e[N];
int n, m, num, dex, ans;
int h[N], low[N], dfn[N];
bool vis[N];
stack<int> stk;

void add(int u, int v)
{
    e[++num].next = h[u];
    e[num].to = v;
    h[u] = num;
}

void tarjan(int x)
{
    low[x] = dfn[x] = ++dex;
    vis[x] = 1, stk.push(x);
    for(int i = h[x]; i != 0; i = e[i].next)
    {
        int now = e[i].to;
        if(!dfn[now])
            tarjan(now),
            low[x] = min(low[x], low[now]);
        else if(vis[now])
            low[x] = min(low[x], dfn[now]);
    }
    if(low[x] == dfn[x])
    {
        int cnt = 0;
        while(1)
        {
            int now = stk.top();
            stk.pop(), cnt++, vis[now] = 0;
            if(now == x) break;
        }
        if(cnt > 1) ans++;
    }
}

int main()
{
    cin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        int u, v;
        scanf("%d%d", &u, &v);
        add(u, v);
    }
    for(int i = 1; i <= n; i++)
        if(!dfn[i]) tarjan(i);
    cout << ans;
    return 0;
}

转载于:https://www.cnblogs.com/BigYellowDog/p/11236167.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值