Equivalent SetsTime Limit: 12000/4000 MS (Java/Others) Memory Limit: 104857/104857 K (Java/Others)Total Submission(s): 3619 Accepted Submission(s): 1262
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
Sample Output
Source
|
题意:计算需要加多少边才能构成一个强连通图注意给的图本身就是一个强连通图的情况
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<vector>
#include<stack>
#define inf 0x3f3f3f3f
using namespace std;
const int maxn=100010;
int dfs_clock,scc_cnt;
int head[maxn];
int sccno[maxn];
int low[maxn],dfn[maxn];
bool instack[maxn];
int in[maxn],out[maxn];
stack<int>S;
vector<int>scc[maxn];
vector<int>G[maxn];
struct Node{
int from,to,next;
}A[maxn];
int MAX(int a,int b){
return a>b?a:b;
}
int MIN(int a,int b){
return a<b?a:b;
}
void init(){
dfs_clock=scc_cnt=0;
memset(head,-1,sizeof(head));
memset(sccno,0,sizeof(sccno));
memset(instack,false,sizeof(instack));
memset(in,0,sizeof(in));
memset(out,0,sizeof(out));
memset(low,0,sizeof(low));
memset(dfn,0,sizeof(dfn));
}
void tarjan(int u,int pre){
int v;
dfn[u]=low[u]=++dfs_clock;
S.push(u);instack[u]=true;
for(int k=head[u];k!=-1;k=A[k].next){
v=A[k].to;
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();
G[scc_cnt].clear();
while(1){
v=S.top();S.pop();
instack[v]=false;
scc[scc_cnt].push_back(v);
sccno[v]=scc_cnt;
if(u==v)break;
}
}
}
void suodian(int m){
for(int i=0;i<m;++i){
int u=sccno[A[i].from];
int v=sccno[A[i].to];
if(u!=v){
G[u].push_back(v);
in[v]++;out[u]++;
}
}
}
int main()
{
int i,j,k,n,m;
while(scanf("%d%d",&n,&m)!=EOF){
init();
for(i=0;i<m;++i){
scanf("%d%d",&A[i].from,&A[i].to);
A[i].next=head[A[i].from];
head[A[i].from]=i;
}
for(i=1;i<=n;++i){
if(!dfn[i]){
tarjan(i,-1);
}
}
if(scc_cnt==1){
printf("%d\n",0);
continue;
}
suodian(m);
int ans1=0,ans2=0;
for(i=1;i<=scc_cnt;++i){
if(in[i]==0)ans1++;
if(out[i]==0)ans2++;
}
printf("%d\n",MAX(ans1,ans2));
}
return 0;
}