洛谷P2002 消息扩散

缩完点之后求有多少入度为0的点即可

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
#include<cstdio>
#include<vector>
#include<stack>
using namespace std;
const int N=100050;
int n,m,d[N],idx[N],cnt=0,ans=0;
int inq[N],dfn[N],low[N],num=0;
vector<int> e[N],g[N];
stack<int> S;
inline int read()
{
register int x=0,t=1;
register char ch=getchar();
while (ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
if (ch=='-') t=-1,ch=getchar();
while (ch>='0'&&ch<='9') x=x*10+ch-48,ch=getchar();
return x*t;
}
void tarjan(int o)
{
dfn[o]=low[o]=++num;
inq[o]=1,S.push(o);
for(int i=0;i<e[o].size();i++)
{
int to=e[o][i];
if (!dfn[to])
{
tarjan(to);
low[o]=min(low[o],low[to]);
}
else if (inq[to])
low[o]=min(low[o],dfn[to]);
}
if (low[o]==dfn[o])
{
int x;cnt++;
do{
x=S.top();
inq[x]=0,S.pop();
idx[x]=cnt;
} while(x!=o);
}
}
int main()
{
n=read(),m=read();
for(int i=1;i<=m;i++)
{
int u=read(),v=read();
if (u==v) continue;
e[u].push_back(v);
}
for(int i=1;i<=n;i++)
if (!dfn[i]) tarjan(i);
for(int i=1;i<=n;i++)
for(int j=0;j<e[i].size();j++)
{
int u=i,v=e[i][j];
if (idx[u]!=idx[v])
{
g[idx[u]].push_back(idx[v]);
d[idx[v]]++;
}
}
for(int i=1;i<=cnt;i++) if (!d[i]) ans++;
printf("%d\n",ans);
return 0;
}