Equivalent Sets
Time Limit: 12000/4000 MS (Java/Others) Memory Limit: 104857/104857 K (Java/Others)
Total Submission(s): 6145 Accepted Submission(s): 2202
Problem 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
2011 Multi-University Training Contest 1 - Host by HNU
问最少加几条边,使整个有向图强连通
先缩点,缩点之后形成的新图,出度为0的个数a和入度为0的个数b中较大的值为答案
注意特判该图本身就为强连通的情况
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 20005;
const int MAXM = 50005;
/*************************************/
struct Edge
{
int to,Next;
}edge[MAXM];
int head[MAXN],tot;
int Low[MAXN],DFN[MAXN],Stack[MAXN],Belong[MAXN];
int Index,top;
int scc;
bool Instack[MAXN];
int num[MAXN];
void addedge(int u,int v)
{
edge[tot].to = v;
edge[tot].Next = head[u];
head[u] = tot++;
}
void Tarjan(int u)
{
int v;
Low[u] = DFN[u] = ++Index;
Stack[top++] = u;
Instack[u] = true;
for(int i = head[u]; i != -1; i = edge[i].Next) {
v = edge[i].to;
if(!DFN[v]) {
Tarjan(v);
if(Low[u] > Low[v]) Low[u] = Low[v];
}
else if(Instack[v] && Low[u] > DFN[v])
Low[u] = DFN[v];
}
if(Low[u] == DFN[u]) {
scc++;
do {
v = Stack[--top];
Instack[v] = false;
Belong[v] = scc;
num[scc]++;
}
while(v != u);
}
}
void solve(int N)
{
memset(DFN,0,sizeof(DFN));
memset(Instack,false,sizeof(Instack));
memset(num,0,sizeof(num));
Index = scc = top = 0;
for(int i = 1; i <= N; i++) {
if(!DFN[i]) {
Tarjan(i);
}
}
}
int in[MAXN],out[MAXN];
void init()
{
tot = 0;
memset(in,0,sizeof(in));
memset(out,0,sizeof(out));
memset(head,-1,sizeof(head));
}
/************************************/
int main(void)
{
int n,m;
int u,v;
int T;
scanf("%d",&T);
while(T--) {
scanf("%d %d",&n,&m);
init();
for(int i = 1; i <= m; i++) {
scanf("%d %d",&u,&v);
addedge(u,v);
}
solve(n);
for(int i = 1; i <= n; i++) {
for(int j = head[i]; j != -1; j = edge[j].Next) {
u = Belong[i],v = Belong[edge[j].to];
if(u != v) {
out[u]++;
in[v]++;
}
}
}
int ans1 = 0,ans2 = 0;
for(int i = 1; i <= scc; i++) {
if(in[i] == 0) ans1++;
if(out[i] == 0) ans2++;
}
printf("%d\n",scc == 1 ? 0 : max(ans1,ans2));
}
return 0;
}