Popular Cows - Tarjan强连通分量缩点
Description
Every cow’s dream is to become the most popular cow in the herd. In a herd of N (1 <= N <= 10,000) cows, you are given up to M (1 <= M <= 50,000) ordered pairs of the form (A, B) that tell you that cow A thinks that cow B is popular. Since popularity is transitive, if A thinks B is popular and B thinks C is popular, then A will also think that C is
popular, even if this is not explicitly specified by an ordered pair in the input. Your task is to compute the number of cows that are considered popular by every other cow.
Input
-
Line 1: Two space-separated integers, N and M
-
Lines 2…1+M: Two space-separated numbers A and B, meaning that A thinks B is popular.
Output
- Line 1: A single integer that is the number of cows who are considered popular by every other cow.
Sample Input
3 3
1 2
2 1
2 3
Sample Output
1
Hint
Cow 3 is the only cow of high popularity.
分析
有向图强连通分量:在有向图G中,如果两个顶点vi,vj间(vi>vj)有一条从vi到vj的有向路径,同时还有一条从vj到vi的有向路径,则称两个顶点强连通(strongly connected)。如果有向图G的每两个顶点都强连通,称G是一个强连通图。有向图的极大强连通子图,称为强连通分量(strongly connected components)。(from 百度)
根据强连通分量的性质,同一个强连通分量里的点都是可以相互到达的。所以要看缩点后构成的有向无环图中点之间的关系。
缩点后构成的图是一个有向无环图(DAG)
- 如果DAG中只有一个出度为0的点,记做
p
,那么说明其他点都可以到达点p
,此时点p
中原来点的个数即为答案。 - 如果DAG中有多个出度为0的点(大于等于2个),那么这些出度为0的点之间就不能相互到达,也就不满足题目
每一头牛都喜欢的牛
这个条件了。
解题方法
Tarjian强连通分量缩点,缩点时可以记下每个强连通分量中的点的个数,统计每个强连通分量的出度,然后判断出度为0的个数就行了。
代码
#include <iostream>
#include <cstring>
#include <vector>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 1e4 + 10;
int n, m;
vector<int> e[N];
int num[N], low[N], idx;
int sta[N], cnt_sta;
bool vis[N];
int book[N], tot;
int out_degree[N];
int sum[N];
void dfs(int cur) {
num[cur] = low[cur] = ++idx;
sta[++cnt_sta] = cur;
vis[cur] = true;
for (int i = 0; i < e[cur].size(); ++i) {
int v = e[cur][i];
if (num[v] == 0) {
dfs(v);
low[cur] = min(low[cur], low[v]);
} else if (vis[v]) {
low[cur] = min(low[cur], num[v]);
}
}
if (low[cur] == num[cur]) {
tot++;
do {
book[sta[cnt_sta]] = tot;
vis[sta[cnt_sta]]=false;
sum[tot]++;
} while (sta[cnt_sta--] != cur);
}
}
int main() {
int A, B;
scanf("%d%d", &n, &m);
for (int i = 0; i < m; ++i) {
scanf("%d%d", &A, &B);
e[A].push_back(B);
}
for (int i = 1; i <= n; ++i) {
if (num[i] == 0) {
dfs(i);
}
}
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < e[i].size(); ++j) {
int v = e[i][j];
if (book[i] != book[v]) { //强连通分量编号不同,加出度数
out_degree[book[i]]++;
}
}
}
int ans = 0, cnt = 0;
for (int i = 1; i <= tot; ++i) { //一共tot个强连通分量
if (out_degree[i] == 0) {
cnt++;
ans = sum[i];
}
}
printf("%d\n", cnt == 1 ? ans : 0);
return 0;
}