洛谷 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;
}