[HAOI2006]受欢迎的牛

嘟嘟嘟

 

考虑建图:如果A喜欢B,那么从A 到B就有一条边。有因为牛之间的喜爱关系有传递性,所以如果途中存在一个环的话,那就说明这个环中的任意一头牛都会被喜爱。那么自然可以想到用tarjan缩点来简化图。这样在一个DAG中,会发现被该联通块喜爱的牛一定是没有出边的。因为这张图可能不连通,所以还有记录这个出边为0的点的个数,如果大于1,就说明图不连通,就输出0,否则输出这个点的大小。

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cmath>
 4 #include<algorithm>
 5 #include<cstring>
 6 #include<cstdlib>
 7 #include<cctype>
 8 #include<vector>
 9 #include<stack>
10 #include<queue>
11 using namespace std;
12 #define enter printf("\n")
13 #define space printf(" ")
14 #define Mem(a) memset(a, 0, sizeof(a))
15 typedef long long ll;
16 typedef double db;
17 const int INF = 0x3f3f3f3f;
18 const int eps = 1e-8;
19 const int maxn = 1e4 + 5;
20 inline ll read()
21 {
22     ll ans = 0;
23     char ch = getchar(), last = ' ';
24     while(!isdigit(ch)) {last = ch; ch = getchar();}
25     while(isdigit(ch))
26     {
27         ans = ans * 10 + ch - '0'; ch = getchar();
28     }
29     if(last == '-') ans = -ans;
30     return ans;
31 }
32 inline void write(ll x)
33 {
34     if(x < 0) x = -x, putchar('-');
35     if(x >= 10) write(x / 10);
36     putchar(x % 10 + '0');
37 }
38 
39 int n, m;
40 vector<int> v[maxn];
41 
42 int dfn[maxn], low[maxn], cnt = 0;
43 bool in[maxn];
44 stack<int> st;
45 int col[maxn], ccol = 0, val[maxn];
46 void tarjan(int now)
47 {
48     dfn[now] = low[now] = ++cnt;
49     st.push(now); in[now] = 1;
50     for(int i = 0 ; i < (int)v[now].size(); ++i)
51     {
52         if(!dfn[v[now][i]]) 
53         {
54             tarjan(v[now][i]);
55             low[now] = min(low[now], low[v[now][i]]);
56         }
57         else if(in[v[now][i]]) low[now] = min(low[now], dfn[v[now][i]]);
58     }
59     if(low[now] == dfn[now])
60     {
61         int x; ccol++;
62         do
63         {
64             x = st.top();
65             in[x] = 0; st.pop();
66             col[x] = ccol; val[ccol]++;
67         }while(x != now);
68     }
69     return;
70 }
71 
72 int out[maxn];
73 
74 int main()
75 {
76     n = read(); m = read();
77     for(int i = 1; i <= m; ++i)
78     {
79         int x = read(), y = read();
80         v[x].push_back(y);
81     }
82     for(int i = 1; i <= n; ++i) if(!dfn[i]) tarjan(i);
83     for(int i = 1; i <= n; ++i)
84         for(int j = 0; j < (int)v[i].size(); ++j)
85             if(col[i] != col[v[i][j]]) out[col[i]]++;
86     int tot = 0, pos;
87     for(int i = 1; i <= ccol; ++i)
88     {
89         if(!out[i]) tot++, pos = i;
90         if(tot > 1) {printf("0\n"); return 0;}
91     }
92     write(val[pos]); enter;
93     return 0;
94 }
View Code

 

posted @ 2018-08-27 17:33  mrclr  阅读(195)  评论(0编辑  收藏  举报