您的位置:首页 > 其它

HDU3836 Tarjan缩点

2013-06-20 13:20 246 查看
/*
      通过强连通分量Tarjan算法后,进行缩点,然后算强连通点的入度跟出度的分量数目即可。
      答案即为入度为0或出度为0的点数目的最大值。  这点可以将缩点后图形堪称有向无环图,仿照树的定义,根为入度为0的点,叶子为出度为0的点。很明显的,要使其成为强连通图,令f为树根数,g为叶子数,则答案为max(f,g),特别的,当缩点只有一个点时,答案为0.
*/

/*
* @author ipqhjjybj
* @date  20130620
*/
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>

#include <iostream>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <utility>

#include <cstring>
#include <vector>
#include <queue>
#include <map>
#include <stack>
#include <string>
#include <memory.h>
using namespace std;

#define inf 0x3f3f3f3f
#define MAXN 30000
#define clr(x,k) memset((x),(k),sizeof(x))
#define cpy(x,k) memcpy((x),(k),sizeof(x))
#define Base 10000

#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
int n,m;
struct node{
int to,next,from;
}Edge[50050];
int head[50050];
int tot;
int low[50050],temp[50050],dfn[50050];
stack<int> st;
int scc_num,lay;
void add(int a,int b){
Edge[tot].to = b;
Edge[tot].from = a;
Edge[tot].next = head[a];
head[a]=tot++;
}
//构图
void init(){
int a,b;
tot = 0;
clr(head,-1);
for(int i = 0;i < m;i++){
scanf("%d %d",&a,&b);
add(a,b);
}
}
//Targan算法实现
int Targan(int k,int lay,int& scc_num){
int j;
temp[k]=1; dfn[k]=low[k]=lay;
st.push(k);
for(int i=head[k];i != -1;i=Edge[i].next){
if(temp[Edge[i].to]==0){
Targan(Edge[i].to,++lay,scc_num);
}
if(temp[Edge[i].to]==1)
low[k] = min(low[k],low[Edge[i].to]);
}
if(dfn[k]==low[k]){
++scc_num;
do{
j = st.top();
low[j]=scc_num;
temp[j]=2;
st.pop();
}while(j!=k);
}
return 0;
}
int in[MAXN],out[MAXN];
//缩点
void degreeSet(){
clr(in,0),clr(out,0);
for(int i = 0;i < tot;i++){
if(low[Edge[i].to]!=low[Edge[i].from]){
//缩点操作
out[low[Edge[i].to]]++;
in[low[Edge[i].from]]++;
}
}
}
int main(){
while(scanf("%d %d",&n,&m)!=EOF){
init();
clr(low,0);
clr(temp,0);
scc_num=0,lay=1;
st.empty();
for(int i = 1;i<=n;i++){
if(temp[i]==0)
Targan(i,lay,scc_num);
}

degreeSet();
int inNum,outNum;
inNum = outNum=0;
for(int i=1;i <= scc_num;i++){
if(!in[i])
inNum++;
if(!out[i])
outNum++;
}
if(scc_num==1){
printf("0\n");
}else printf("%d\n",max(inNum,outNum));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ACM HDU 图论 Tanjan