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

Status

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


给定一个图,求最少加多少条边能使其成为强连通图。先用Tarjan缩点,然后计算新图每个点的出度和入度,遍历每个点,统计总的出/入度数,大的那个即为答案。

AC代码:

#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
const int maxn = 20010, maxm = 50010;
struct node
{
	int v, next;
}e[maxm];
int head[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;
void adde(int u, int v)
{
	e[k].v = v;
	e[k].next = head[u];
	head[u] = k++;
}
void init()
{
	k = 1;
	memset(head, -1, sizeof(head));
	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;
		adde(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;
}

 

分类: ACM/ICPC

发表评论

电子邮件地址不会被公开。 必填项已用*标注