Time Limit: 4000MS Memory Limit: 104857KB 64bit IO Format: %I64d & %I64u

Description

To prove two sets A and B are equivalent, we can first prove A is a subset of B, and then prove B is a subset of A, so finally we got that these two sets are equivalent.
You are to prove N sets are equivalent, using the method above: in each step you can prove a set X is a subset of another set Y, and there are also some sets that are already proven to be subsets of some other sets.
Now you want to know the minimum steps needed to get the problem proved.

Input

The input file contains multiple test cases, in each case, the first line contains two integers N <= 20000 and M <= 50000.
Next M lines, each line contains two integers X, Y, means set X in a subset of set Y.

Output

For each case, output a single integer: the minimum steps needed.

Sample Input

4 0
3 2
1 2
1 3

Sample Output

4
2

Hint

Case 2: First prove set 2 is a subset of set 1 and then prove set 3 is a subset of set 1.

Source

AC代码：

#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
const int maxn = 20010, maxm = 50010;
struct node
{
int v, next;
}e[maxm];
int k;
int dfn[maxn], belong[maxn], low[maxn];
int indegree[maxn], outdegree[maxn];
bool ins[maxn];
stack <int> s;
int n, m;
int idx, scc;
int in, out;
{
e[k].v = v;
}
void init()
{
k = 1;
memset(dfn, 0, sizeof(dfn));
memset(ins, 0, sizeof(ins));
memset(belong, 0, sizeof(belong));
memset(indegree, 0, sizeof(indegree));
memset(outdegree, 0, sizeof(outdegree));
idx = scc = in = out = 0;
}
void input()
{
int u, v;
for (int i = 0; i < m; i++)
{
cin >> u >> v;
}
}
void tarjan(int u)
{
int v;
low[u] = dfn[u] = ++idx;
s.push(u);
ins[u] = 1;
for (int i = head[u]; i != -1; i = e[i].next)
{
v = e[i].v;
if (!dfn[v])
{
tarjan(v);
low[u] = min(low[u], low[v]);
}
else if (ins[v])
low[u] = min(low[u], dfn[v]);
}
if (low[u] == dfn[u])
{
scc++;
do
{
v = s.top();
s.pop();
ins[v] = 0;
belong[v] = scc;
}
while (u != v);
}
}
void solve()
{
for (int i = 1; i <= n; i++)
if (!dfn[i])
tarjan(i);
if (scc == 1)
{
cout << "0\n";
return;
}
for (int u = 1; u <= n; u++)
for (int i = head[u]; i != -1; i = e[i].next)
{
int &v = e[i].v;
if (belong[u] != belong[v])
{
indegree[belong[v]]++;
outdegree[belong[u]]++;
}
}
for (int i = 1; i <= scc; i++)
{
if (!indegree[i])
in++;
if (!outdegree[i])
out++;
}
cout << max(in, out) << endl;
}
int main()
{
while (cin >> n >> m)
{
init();
input();
solve();
}
return 0;
}