您的位置:首页 > 产品设计 > UI/UE

HDU 3836 Equivalent Sets(强连通缩点)

2015-10-09 18:32 387 查看

Equivalent Sets

[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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.

[align=left]Output[/align]
For each case, output a single integer: the minimum steps needed.

[align=left]Sample Input[/align]

4 0

3 2

1 2
1 3

[align=left]Sample Output[/align]

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.

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
#include<vector>
using namespace std;

const int maxn=20005;
vector<int>G[maxn];
stack<int>s;
int in[maxn],out[maxn],dfn[maxn],lowlink[maxn],sccno[maxn];
int scc_cnt,dfs_clock;
int m,n;

void init()
{
for(int i=1;i<=n;i++)G[i].clear();
memset(in,0,sizeof(in));
memset(out,0,sizeof(out));
memset(dfn,0,sizeof(dfn));
memset(lowlink,0,sizeof(lowlink));
memset(sccno,0,sizeof(sccno));
scc_cnt=dfs_clock=0;
}

void tarjan(int u)
{
lowlink[u]=dfn[u]=++dfs_clock;
s.push(u);
for(int i=0;i<G[u].size();i++)
{
int v=G[u][i];
if(!dfn[v])
{
tarjan(v);
lowlink[u]=min(lowlink[u],lowlink[v]);
}
else if(!sccno[v])
lowlink[u]=min(lowlink[u],dfn[v]);
}
if(lowlink[u]==dfn[u])
{
scc_cnt++;
while(1)
{
int x=s.top();
s.pop();
sccno[x]=scc_cnt;
if(x==u)break;
}
}
}

int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
init();
for(int i=0;i<m;i++)
{
int u,v;
scanf("%d%d",&u,&v);
G[u].push_back(v);
}
for(int i=1;i<=n;i++)
if(!dfn[i])
tarjan(i);
for(int i=1;i<=n;i++)
for(int j=0;j<G[i].size();j++)
if(sccno[G[i][j]]!=sccno[i])
{
in[sccno[G[i][j]]]++;
out[sccno[i]]++;
}
int cnt1=0,cnt2=0;
for(int i=1;i<=scc_cnt;i++)
{
if(!in[i])
cnt1++;
if(!out[i])
cnt2++;
}
if(scc_cnt==1)
puts("0");
else
printf("%d\n",max(cnt1,cnt2));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: