P2341 [HAOI2006]受欢迎的牛 - 缩点
费了半天时间玩拓扑排序,然而发现有结论可以直接用:
在一个DAG中,若有且仅有一个点的出度为0,则其他所有的点都可以遍历到这个点,否则图中不存在能被所有的点遍历到的点
证明。。。反证法什么的来一下,感性理解就好了
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <stack>
using namespace std;
#define debug(x) cerr << #x << "=" << x << endl;
const int MAXN = 10000 + 10;
const int MAXM = 50000 * 2 + 10;
int n,m,last[MAXN],edge_tot,scc_num,col_edge_tot,id[MAXN],pre[MAXN],cnt,col_last[MAXN];
int dfn[MAXN],low[MAXN],flg[MAXN],col[MAXN],num[MAXN],node_last,fina_flg,ans,od[MAXN];
struct Edge{
int u,v,to;
Edge(){}
Edge(int u, int v, int to) : u(u), v(v), to(to) {}
}e[MAXM],col_e[MAXM];
inline void add(int u, int v) {
e[++edge_tot] = Edge(u, v, last[u]);
last[u] = edge_tot;
}
stack<int> s;
queue<int> q;
inline void col_add(int u, int v) {
col_e[++col_edge_tot] = Edge(u, v, col_last[u]);
col_last[u] = col_edge_tot;
}
void tarjan(int x) {
dfn[x] = low[x] = ++cnt;
s.push(x);
flg[x] = 1;
for(int i=last[x]; i; i=e[i].to) {
int v = e[i].v;
if(!dfn[v]) {
tarjan(v);
low[x] = min(low[x], low[v]);
} else if(flg[v]){
low[x] = min(low[x], dfn[v]);
}
}
if(low[x] == dfn[x]) {
int j, scc_tot = 0;
scc_num++;
do{
j = s.top();
s.pop();
flg[j] = 0;
col[j] = scc_num;
scc_tot++;
}while(j != x);
num[scc_num] = scc_tot;
}
}
void topo() {
for(int i=1; i<=scc_num; i++) {
if(!id[i]) {
q.push(i);
}
}
while(!q.empty()) {
int x = q.front();
q.pop();
node_last = x;
bool flg = false;
for(int i=col_last[x]; i; i=col_e[i].to) {
flg = true;
int v = col_e[i].v;
id[v]--;
if(!id[v]) {
q.push(v);
}
}
if(!flg) {
if(!q.empty()) {
printf("0");
fina_flg = true;
}
}
}
}
int main() {
scanf("%d%d", &n, &m);
for(int i=1; i<=m; i++) {
int ai, bi;
scanf("%d%d", &ai, &bi);
add(ai, bi);
}
for(int i=1; i<=n; i++) {
if(!dfn[i]) {
tarjan(i);
}
}
for(int i=1; i<=m; i++) {
int ai = e[i].u, bi = e[i].v;
if(col[ai] != col[bi]) {
col_add(col[ai], col[bi]);
id[col[bi]]++;
od[col[ai]]++;
}
}
//topo();
//if(!fina_flg)
// printf("%d", num[node_last]);
int od_tot = 0;
for(int i=1; i<=scc_num; i++) {
if(!od[i]) {
ans = num[i];
od_tot++;
if(od_tot >= 2) ans = 0;
}
}
printf("%d", ans);
return 0;
}