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

HDOJ/HDU 3836 Equivalent Sets

2011-07-14 17:40 375 查看
题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=3836

[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
HintCase 2: First prove set 2 is a subset of set 1 and then prove set 3 is a subset of set 1.

[align=left]Source[/align]2011 Multi-University Training Contest 1 - Host by HNU
[align=left]Recommend[/align]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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: