POJ 2186 受欢迎的牛 Tarjan基础题

时间:2021-07-23 00:29:13
 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<vector>
 5 #include<stack>
 6 #define M 50010
 7 #define N 10010
 8 using namespace std;
 9 int n,m,u,v,head[N],cnt=1,ans,out[N],belong[N],dfn[N],low[N],indx,tar,miao;
10 bool inst[N];
11 stack <int> st;
12 struct edge
13 {
14     int u,v;
15 }e[M],tmp[M];
16 void add(int u,int v)
17 {
18     e[cnt].v=v;
19     e[cnt].u=head[u];
20     head[u]=cnt++;
21 }
22 void dfs(int u)
23 {
24     dfn[u]=low[u]=++indx;
25     inst[u]=1;
26     st.push(u);
27     for (int i=head[u];i;i=e[i].u)
28     {
29     int v=e[i].v;
30     if(!dfn[v])
31     {
32         dfs(v);
33         low[u]=min(low[u],low[v]);
34     }
35     else
36         if (inst[v])
37         low[u]=min(low[u],dfn[v]);
38     }
39     if (dfn[u]==low[u])
40     {
41     tar++;
42     while (1)
43     {
44         int t=st.top();
45         st.pop(),inst[t]=0;
46         belong[t]=tar;
47         if (t==u)
48         break;
49     }
50     }}
51 int main()
52 {
53     scanf("%d%d",&n,&m);
54     for (int i=1;i<=m;i++)
55     {
56     scanf("%d%d",&u,&v);
57     add(u,v);
58     tmp[i].u=u;
59     tmp[i].v=v;
60     }
61     for (int i=1;i<=n;i++)
62     if (dfn[i]==0) dfs(i);
63     for (int i=1;i<=m;i++)
64     {
65     u=tmp[i].u,v=tmp[i].v;
66     if (belong[u]!=belong[v])
67         ++out[belong[u]];
68     }
69     for (int i=1;i<=tar;i++)
70     if (out[i]==0)
71         if (miao==0)
72         miao=i;
73         else miao=-1;
74     for (int i=1;i<=n;i++)
75     if (belong[i]==miao) ans++;
76     printf("%d\n",ans);
77     return 0;
78 }