题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=3836
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 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
Recommend
xubiao
求强连通分量,然后统计每一个分量的入读和初读
这两个量中较大的那一个就是答案了。
#include<stdio.h> #include<vector> #include<string.h> #include<algorithm> #include<stack> #define MAXN 20005 using namespace std; int n,m,cnt,Index; int belong[MAXN],dfn[MAXN],low[MAXN]; bool used[MAXN],instack[MAXN]; int in[MAXN],out[MAXN]; stack<int>s; vector<int>map[MAXN]; void init() { int i; for(i=0;i<=n;i++) map[i].clear(); while(!s.empty()) s.pop(); memset(in,0,sizeof(in)); memset(out,0,sizeof(out)); memset(used,0,sizeof(used)); memset(instack,0,sizeof(instack)); memset(dfn,-1,sizeof(dfn)); memset(low,0,sizeof(low)); memset(belong,0,sizeof(belong)); cnt=0; Index=0; } int min(int a,int b) { if(a>b) return b; else return a; } void tarjan(int u) { int i,v; Index++; dfn[u]=Index; low[u]=Index; used[u]=true; instack[u]=true; s.push(u); for(i=0;i<map[u].size();i++) { v=map[u][i]; if(!used[v]) { tarjan(v); low[u]=min(low[u],low[v]); } else if(instack[v]) { low[u]=min(low[u],dfn[v]); } } if(dfn[u]==low[u]) { cnt++; do { v=s.top(); s.pop(); belong[v]=cnt; instack[v]=false; } while(u!=v); } } int max(int a,int b) { if(a>b) return a; else return b; } int main() { int i,a,b,x,y,j; while(scanf("%d%d",&n,&m)!=EOF) { init(); for(i=1;i<=m;i++) { scanf("%d%d",&a,&b); map[a].push_back(b); } for(i=1;i<=n;i++) if(dfn[i]==-1) tarjan(i); for(i=1;i<=n;i++) { for(j=0;j<map[i].size();j++) { if(belong[i]!=belong[map[i][j]]) { out[belong[i]]++; in[belong[map[i][j]]]++; } } } x=0,y=0; for(i=1;i<=cnt;i++) { if(!in[i]) x++; if(!out[i]) y++; } if(cnt==1) printf("0\n"); else printf("%d\n",max(x,y)); } return 0; }