Equivalent Sets
Time Limit: 12000/4000 MS (Java/Others) Memory Limit: 104857/104857 K (Java/Others)Total Submission(s): 1951 Accepted Submission(s): 659
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.
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.
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 2HintCase 2: First prove set 2 is a subset of set 1 and then prove set 3 is a subset of set 1.
题意:给出n个集合,要证明集合A和集合B是等价的,则要证明A是B的子集和B是A的子集。给出m个关系A B,表示已证明了A是B的子集,问要证明n个集合是等价的,还需要多少步。
思路:求将原图的强连通分量缩点,得到有向无环图,求至少加多少条边可以使这个图变成一幅强连通图,max(入度为0的点,出度为0的点)即为答案。这里用Kosaraju算法来缩点。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <vector>
#include <cmath>
#include <stack>
#include <cstdlib>
using namespace std;
const int maxn=20005;
vector<int> v[maxn],rev[maxn];
int n,m,snum,in[maxn],out[maxn],scc[maxn],fin[maxn],ans1,ans2;
bool vis[maxn];
void dfs1(int x)
{
vis[x]=true;
for(int i=0;i<(int)v[x].size();i++)
if(!vis[v[x][i]]) dfs1(v[x][i]);
fin[snum++]=x;
}
void dfs2(int x,int num)
{
vis[x]=true;
scc[x]=num;
for(int i=0;i<(int)rev[x].size();i++)
if(!vis[rev[x][i]]) dfs2(rev[x][i],num);
}
int main()
{
int a,b;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=1;i<=n;i++)
{
v[i].clear();
rev[i].clear();
}
memset(in,0,sizeof(in));
memset(out,0,sizeof(out));
while(m--)
{
scanf("%d%d",&a,&b);
v[a].push_back(b);
rev[b].push_back(a);
}
memset(vis,false,sizeof(vis));
snum=1;
for(int i=1;i<=n;i++)
if(!vis[i]) dfs1(i);
memset(vis,false,sizeof(vis));
snum=1;
for(int i=n;i>=1;i--)
if(!vis[fin[i]])
{
dfs2(fin[i],snum);
snum++;
}
snum--;
for(int i=1;i<=n;i++)
for(int j=0;j<(int)v[i].size();j++)
if(scc[i]!=scc[v[i][j]])
{
in[scc[v[i][j]]]++;
out[scc[i]]++;
}
ans1=ans2=0;
for(int i=1;i<=snum;i++)
{
if(!in[i]) ans1++;
if(!out[i]) ans2++;
}
if(snum==1)
printf("0\n");
else
printf("%d\n",max(ans1,ans2));
}
return 0;
}