题意分析
给定 $n$ 个点,$m$ 条有向边,求有多少个点能够到达其他全部的点。
题目给出的类似于“奶牛 $A$ 喜欢奶牛 $B$”,我们可以从点 $B$ 向点 $A$ 连边,表示“$B$ 被 $A$ 喜欢”。
随后我们只需要看是否能够找到一个点,使其能够抵达所有的点即可。
但是会有环,因此我们可以用 Tarjan 缩点 来处理掉环,使得原图成为一个有向无环图。
只要此时新建的有向无环图连通,则肯定会存在一个点的入度为 $0$,该点在原图中所在的强连通分量的点的数量即答案。
判断是否连通也很简单,看入度为 $0$ 的点数是否为 $1$ 即可。
AC 代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
//#include<bits/stdc++.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<iomanip>
#include<cstdio>
#include<string>
#include<vector>
#include<cmath>
#include<ctime>
#include<deque>
#include<queue>
#include<stack>
#include<list>
#include<unordered_set>
using namespace std;
constexpr const int N=1e4,M=1e5;
struct graph{
struct edge{
int v,r;
}a[M+1];
int n,h[N+1],top;
void create(int u,int v){
a[++top]={v,h[u]};
h[u]=top;
}
}old,build;
int dfn[N+1],id[N+1],size[N+1];
void Tarjan(int x){
static bool flag[N+1];
static int top,cnt,s[N+1],low[N+1];
dfn[x]=low[x]=++cnt;//此处的top其实可以是双重含义(时间戳计数器&栈计数器),由于top--只会发生在递归之后,因此不会出错,但需要注意不要混用,求点双连通分量时混用会出错!!
s[++top]=x;
flag[x]=true;
for(int i=old.h[x];i;i=old.a[i].r){
if(!dfn[old.a[i].v]){
Tarjan(old.a[i].v);
low[x]=min(low[x],low[old.a[i].v]);
}else{
if(flag[old.a[i].v]){
low[x]=min(low[x],low[old.a[i].v]);
}
}
}
if(dfn[x]==low[x]){
build.n++;
while(s[top]!=x){
flag[s[top]]=false;
id[s[top]]=build.n;
size[build.n]++;
top--;
}flag[s[top]]=false;
id[s[top]]=build.n;
size[build.n]++;
top--;
}
}
void Build(){
for(int i=1;i<=old.n;i++){
for(int j=old.h[i];j;j=old.a[j].r){
int &u=id[i],&v=id[old.a[j].v];
if(u==v)continue;
build.create(u,v);
}
}
}
int order[N+1];
int topSort(){
static int in[N+1];
for(int i=1;i<=build.n;i++){
for(int j=build.h[i];j;j=build.a[j].r){
in[build.a[j].v]++;
}
}
int ans=0,cnt=0;
for(int i=1;i<=build.n;i++){
if(in[i]==0){
cnt++;
ans+=size[i];
}
}
if(cnt==1)return ans;
return 0;
}
int main(){
/*freopen("test.in","r",stdin);
freopen("test.out","w",stdout);*/
int n,m;
scanf("%d %d",&n,&m);
old.n=n;
for(int i=1;i<=m;i++){
int a,b;
scanf("%d %d",&a,&b);
old.create(b,a);
}
for(int i=1;i<=n;i++){
if(!dfn[i]){
Tarjan(i);
}
}
Build();
printf("%d\n",topSort());
/*fclose(stdin);
fclose(stdout);*/
return 0;
}