先求强连通,再缩点。然后再DAG图上求出入度为0的点的个数,和出度为0的点的个数,取最大就是答案了。。两个坑...一个是缩点以后自己指向自己的边要删掉。。一个是本来图就强连通要特判。。。
#include <iostream>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <climits>
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 20005
#define maxm 50005
#define eps 1e-10
#define mod 1000000009
#define INF 99999999
#define lowbit(x) (x&(-x))
//#define lson o<<1, L, mid
//#define rson o<<1 | 1, mid+1, R
typedef long long LL;
//typedef int LL;
using namespace std;
int H[maxn], NEXT[maxm], V[maxm];
int h[maxn], next[maxm], v[maxm];
int dfn[maxn], low[maxn], id[maxn];
int out[maxn], in[maxn], ins[maxn];
stack<int> s;
int n, m, top, scc_cnt;
void init(void)
{
top = scc_cnt = 0;
memset(H, -1, sizeof H);
memset(h, -1, sizeof h);
memset(in, 0, sizeof in);
memset(out, 0, sizeof out);
memset(ins, 0, sizeof ins);
memset(dfn, 0, sizeof dfn);
}
void scanf(int &x)
{
x = 0;
char ch = getchar();
while(ch == ' ' || ch == '\n') ch = getchar();
while(ch >= '0' && ch <= '9') x=x*10+ch-'0', ch = getchar();
}
void read(void)
{
int cnt = 0, a, b;
while(m--) {
//scanf("%d%d", &a, &b);
scanf(a), scanf(b);
NEXT[cnt] = H[a], H[a] = cnt, V[cnt] = b, cnt++;
}
}
void narrow(void)
{
int cnt = 0;
for(int i = 1; i <= n; i++)
for(int e = H[i]; ~e; e = NEXT[e])
next[cnt] = h[id[i]], h[id[i]] = cnt, v[cnt] = id[V[e]], cnt++;
}
void tarjan(int u)
{
dfn[u] = low[u] = ++top;
s.push(u), ins[u] = 1;
for(int e = H[u]; ~e; e = NEXT[e]) {
if(!dfn[V[e]]) {
tarjan(V[e]);
low[u] = min(low[u], low[V[e]]);
}
else if(ins[V[e]]) low[u] = min(low[u], dfn[V[e]]);
}
if(dfn[u] == low[u]) {
int tmp = s.top(); s.pop(), ins[tmp] = 0;
++scc_cnt;
while(tmp != u) {
id[tmp] = scc_cnt;
tmp = s.top();
s.pop();
ins[tmp] = 0;
}
id[tmp] = scc_cnt;
}
}
void work(void)
{
int k1 = 0, k2 = 0, i;
for(i = 1; i <= n; i++)
if(!dfn[i]) tarjan(i);
narrow();
for(i = 1; i <= scc_cnt; i++)
for(int e = h[i]; ~e; e = next[e])
if(i != v[e])
out[i]++, in[v[e]]++;
for(i = 1; i <= scc_cnt; i++) if(!in[i]) k1++;
for(i = 1; i <= scc_cnt; i++) if(!out[i]) k2++;
if(scc_cnt == 1) printf("0\n");
else printf("%d\n", max(k1, k2));
}
int main(void)
{
while(scanf("%d%d", &n, &m)!=EOF) {
init();
read();
work();
}
return 0;
}