tarjan缩点
由题意可以发现,其实最受欢迎的牛就是找出所有强联通分量,缩点之后,所有新点里出度为0的那个强联通分量里的所有点。。。
而且这中强联通分量只能有一个,假设大于1个的话,就会有两块不联通的区域,那就无法被所有牛喜欢。。
所以直接缩点计算一下出度就行啦
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define full(a, b) memset(a, b, sizeof a)
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
inline int read(){
int X = 0, w = 0; char ch = 0;
while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
return w ? -X : X;
}
inline int gcd(int a, int b){ return a % b ? gcd(b, a % b) : b; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template<typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template<typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template<typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
A ans = 1;
for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
return ans;
}
const int N = 10005;
int n, m, cnt, head[N], dfn[N], low[N], k, ins[N], tot, scc[N], d[N];
struct Edge { int v, next; } edge[N<<5];
stack<int> st;
vector<int> c[N];
void addEdge(int a, int b){
edge[cnt].v = b, edge[cnt].next = head[a], head[a] = cnt ++;
}
void tarjan(int s){
dfn[s] = low[s] = ++k;
ins[s] = true, st.push(s);
for(int i = head[s]; i != -1; i = edge[i].next){
int u = edge[i].v;
if(!dfn[u]){
tarjan(u);
low[s] = min(low[s], low[u]);
}
else if(ins[u])
low[s] = min(low[s], dfn[u]);
}
if(dfn[s] == low[s]){
tot ++; int cur = 0;
do{
cur = st.top(); st.pop();
ins[cur] = false, scc[cur] = tot, c[tot].push_back(cur);
}while(cur != s);
}
}
int main(){
full(head, -1);
n = read(), m = read();
for(int i = 0; i < m; i ++){
int a = read(), b = read();
addEdge(a, b);
}
for(int i = 1; i <= n; i ++){
if(!dfn[i]) tarjan(i);
}
for(int s = 1; s <= n; s ++){
for(int i = head[s]; i != -1; i = edge[i].next){
int u = edge[i].v;
if(scc[s] != scc[u]) d[scc[s]] ++;
}
}
int ans = 0;
for(int i = 1; i <= tot; i ++){
if(!d[i]){
if(ans) { printf("0
"); return 0;}
ans = i;
}
}
//printf(num != 1 ? "0" : "%d
", ans);
cout << c[ans].size() << endl;
return 0;
}