Equivalent Sets
Time Limit: 12000/4000 MS (Java/Others) Memory Limit: 104857/104857 K (Java/Others)
Total Submission(s): 3597 Accepted Submission(s): 1252
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
Hint
Case 2: First prove set 2 is a subset of set 1 and then prove set 3 is a subset of set 1.
//和hdoj2767题一样,求最少添加多少条边使图强连通。
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<stack>
#include<vector>
#define N 20010
using namespace std;
int n,m;
int low[N];
int dfn[N],dfs_clock;
int sccon[N],scc_cnt;
bool instack[N];
vector<int>g[N];
vector<int>scc[N];
stack<int>s;
void tarjan(int u,int fa)
{
int v;
low[u]=dfn[u]=++dfs_clock;
s.push(u);
instack[u]=true;
for(int i=0;i<g[u].size();i++)
{
v=g[u][i];
if(!dfn[v])
{
tarjan(v,u);
low[u]=min(low[u],low[v]);
}
else if(instack[v])
low[u]=min(low[u],dfn[v]);
}
if(low[u]==dfn[u])
{
scc_cnt++;
scc[scc_cnt].clear();
while(1)
{
v=s.top();
s.pop();
sccon[v]=scc_cnt;
scc[scc_cnt].push_back(v);
instack[v]=false;
if(v==u)
break;
}
}
}
void find(int l,int r)
{
memset(low,0,sizeof(low));
memset(dfn,0,sizeof(dfn));
memset(sccon,0,sizeof(sccon));
memset(instack,false,sizeof(instack));
scc_cnt=dfs_clock=0;
for(int i=l;i<=r;i++)
if(!dfn[i])
tarjan(i,-1);
}
int in[N],out[N];
void suodian()
{
int i,j;
for(i=1;i<=scc_cnt;i++)
in[i]=out[i]=0;
for(i=1;i<=n;i++)
{
for(j=0;j<g[i].size();j++)
{
int u=sccon[i];
int v=sccon[g[i][j]];
if(u!=v)
{
out[u]++;
in[v]++;
}
}
}
}
void solve()
{
find(1,n);
suodian();
if(scc_cnt==1)
{
printf("0\n");
return ;
}
int sumin=0,sumout=0;
for(int i=1;i<=scc_cnt;i++)
{
if(in[i]==0)
sumin++;
if(out[i]==0)
sumout++;
}
printf("%d\n",max(sumin,sumout));
}
int main()
{
int x,y;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=1;i<=n;i++)
g[i].clear();
while(m--)
{
scanf("%d%d",&x,&y);
g[x].push_back(y);
}
solve();
}
return 0;
}