题目大意:有n个牛在一块, m条单项绳子, 有m个链接关系, 问有多少个团体内部任意两头牛可以相互可达
解题思路:有向图强连通分量模版图
代码如下:
#include<stdio.h>
#include<vector>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N = ; vector<int>G[N], DQ;
int low[N], dfn[N], tot;
bool mk[N];
int n, m, ans; void init()
{
ans = tot = ;
DQ.clear();
for(int i=; i<=n; ++ i)
{
G[i].clear();
low[i] = dfn[i] = -;
mk[i] = false;
}
} void tarjan(int u, int f)
{
dfn[u] = low[u] = ++ tot;
DQ.push_back(u);
mk[u] = true;
for(int i = ; i<G[u].size(); ++ i)
{
int v = G[u][i];
if(dfn[v] == -)
{
tarjan(v, u);
low[u] = min(low[u], low[v]);
}
else if(mk[v])
low[u] = min(low[u], dfn[v]);
} if(dfn[u] == low[u])
{
int s;
int k = ;
do
{
s = DQ.back();
k ++;
DQ.pop_back();
mk[s] = false;
}
while(u != s);
if(k > )
ans ++;
}
} void solve()
{
for(int i=; i<=n; ++ i)
{
if(dfn[i] == -)
tarjan(i, -);
}
printf("%d\n", ans);
} int main()
{
while(~scanf("%d%d", &n, &m))
{
init();
for(int i=; i<=m; ++ i)
{
int u, v;
scanf("%d%d", &u, &v);
G[u].push_back(v);
}
solve();
}
return ;
}