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

HDU 3836 Equivalent Sets

2014-08-25 20:14 204 查看

Equivalent Sets

Time Limit: 4000ms
Memory Limit: 104857KB
This problem will be judged on HDU. Original ID: 3836
64-bit integer IO format: %I64d Java class name: Main

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.

[b]Input[/b]

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.

[b]Output[/b]

For each case, output a single integer: the minimum steps needed.

[b]Sample Input[/b]

4 0
3 2
1 2
1 3

[b]Sample Output[/b]

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.

[b]Source[/b]

2011 Multi-University Training Contest 1 - Host by HNU

解题:本意就是最少添加多少条边,使得全图强连通。tarjan求极大强连通子图后缩点。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <climits>
#include <vector>
#include <queue>
#include <cstdlib>
#include <string>
#include <set>
#include <stack>
#define LL long long
#define pii pair<int,int>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 20100;
int dfn[maxn],low[maxn],belong[maxn];
bool instack[maxn];
vector<int>g[maxn];
stack<int>stk;
int n,m,cnt,scc,in[maxn],out[maxn];
void tarjan(int u){
dfn[u] = low[u] = ++cnt;
stk.push(u);
instack[u] = true;
for(int i = 0; i < g[u].size(); i++){
if(!dfn[g[u][i]]){
tarjan(g[u][i]);
low[u] = min(low[u],low[g[u][i]]);
}else if(instack[g[u][i]]) low[u] = min(low[u],dfn[g[u][i]]);
}
if(dfn[u] == low[u]){
scc++;
int v;
do{
v = stk.top();
instack[v] = false;
belong[v] = scc;
stk.pop();
}while(v != u);
}
}
int main() {
int i,j,u,v,a,b;
while(~scanf("%d %d",&n,&m)){
for(i = 0; i <= n; i++){
dfn[i] = low[i] = belong[i] = 0;
instack[i] = false;
g[i].clear();
in[i] = out[i] = 0;
}
cnt = scc = 0;
while(!stk.empty()) stk.pop();
for(i = 1; i <= m; i++){
scanf("%d %d",&u,&v);
g[u].push_back(v);
}
for(i = 1; i <= n; i++)
if(!dfn[i]) tarjan(i);
for(i = 1; i <= n; i++){
for(j = 0; j < g[i].size(); j++){
if(belong[i] != belong[g[i][j]]){
in[belong[g[i][j]]]++;
out[belong[i]]++;
}
}
}
for(a = b = 0,i = 1; i <= scc; i++){
if(!in[i]) a++;
if(!out[i]) b++;
}
printf("%d\n",scc == 1?0:max(a,b));
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: