# Equivalent Sets

Time Limit: 12000/4000 MS (Java/Others)    Memory Limit: 104857/104857 K (Java/Others)
Total Submission(s): 3621    Accepted Submission(s): 1264

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.

ac代码：
#include<stdio.h>
#include<string.h>
#include<stack>
#include<vector>
#include<algorithm>
#define INF 0x3f3f3f
#define MAXN 20000+10
using namespace std;
vector<int>mp[MAXN];//存储图
vector<int>sccno[MAXN];//存储每个强连通分量；
vector<int>NEW[MAXN];
stack<int>q;//将遍历过得节点记录在栈里
bool Instack[MAXN];//记录是否在栈里。
int  In[MAXN],Out[MAXN];//记录入度，出度。
int low[MAXN],dfn[MAXN],scc[MAXN];//sccno记录每个节点 属于哪个强连通分量
int dfs_clock,scc_cnt;
int n,m;
void get_map(){
for(int i=1;i<=n;i++)
mp[i].clear();
for(int i=0;i<m;i++){
int u,v;
scanf("%d%d",&u,&v);
mp[u].push_back(v);
}
}
void tarjan(int u){
int v;//下一个节点；
low[u]=dfn[u]=++dfs_clock;
Instack[u]=true;
q.push(u);
for(int j=0;j<mp[u].size();j++){//遍历U节点的每一条边。
v=mp[u][j];
if(!dfn[v]){
tarjan(v);
low[u]=min(low[u],low[v]);//更新low数组
}
else	if(Instack[v])
low[u]=min(low[u],dfn[v]);//建立反向边。
}
if(dfn[u]==low[u]){
scc_cnt++;
while(1){
v=q.top();
q.pop();
scc[v]=scc_cnt;
sccno[scc_cnt].push_back(v);
Instack[v]=false;
if(u==v)
break;
}
}
}
void find_cut(){
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
memset(Instack,false,sizeof(Instack));
dfs_clock=scc_cnt=0;
for(int i=1;i<=n;i++)
if(!dfn[i])
tarjan(i);
}
void SCC(){
memset(In,0,sizeof(In));
memset(Out,0,sizeof(Out));
for(int i=1;i<=scc_cnt;i++)
NEW[i].clear();
for(int i=1;i<=n;i++){
for(int j=0;j<mp[i].size();j++){//遍历所有边，构建新图。
int u=scc[i];//找到这两个点是否是同一个强连通分量
int v=scc[mp[i][j]];
if(u!=v) {//如果不是，构建新边。
NEW[u].push_back(v);
In[v]++;
Out[u]++;
}
}
}
}
void solve(){
int sumin=0,sumout=0;
if(scc_cnt==1){
printf("0\n");
}
else{
for(int i=1;i<=scc_cnt;i++){
if(In[i]&&Out[i])
continue;
if(!In[i])
sumin++;
if(!Out[i])
sumout++;
}
int ans=max(sumin,sumout);
printf("%d\n",ans);
}
}
int main(){
while(scanf("%d%d",&n,&m)!=EOF){
get_map();
find_cut();
SCC();
solve();
}

return 0;
} 

• 本文已收录于以下专栏：

举报原因： 您举报文章：HDOJ--3836--Equivalent Sets(tarjan算法)//求连接几个SCC最少的边 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)