UOJ #92 有向图的强连通分量

【题目描述】:

有向图强连通分量:在有向图G中,如果两个顶点vi,vj间(vi>vj)有一条从vi到vj的有向路径,同时还有一条从vj到vi的有向路径,则称两个顶点强连通(strongly connected)。如果有向图G的每两个顶点都强连通,称G是一个强连通图。有向图的极大强连通子图,称为强连通分量(strongly connected components)。

现在给出一个有向图。结点个数N(<=1000)(编号1~N),边数M(<=5000)。请你按照从小到大的顺序输出最大的强连通分量结点编号。
【输入描述】:

第一行N和M 以下M行,每行两个空格隔开的整数表示一条有向边;
【输出描述】:

输出一行,最大的强连通分量的结点(由小到大输出)
【样例输入】:

10 20
2 2
5 3
8 5
3 4
8 7
10 10
10 6
7 7
2 8
3 2
8 1
3 8
1 7
8 10
7 5
6 4
9 2
8 6
7 5
1 8

【样例输出】:

1 2 3 5 7 8

【时间限制、数据范围及描述】:

时间:1s 空间:256M

N<=1000, M<=5000

本题直接跑一边tarjan,用桶记录下每个强连通分量中的节点个数,输出其中最大的强联通分量即可。

Code:
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<ctime>
using namespace std;
const int N=50005;
int n,m,head[N],dfs[N],stack[N],low[N],cnt,t,top,ans[N],len,num[N],maxn;
bool vis[N];
struct node{
    int u,v,next;
}edge[N];
void push(int u,int v){
    ++cnt;
    edge[cnt].u=u;
    edge[cnt].v=v;
    edge[cnt].next=head[u];
    head[u]=cnt;
}
void tarjan(int u){
    dfs[u]=low[u]=++t;
    stack[++top]=u;
    vis[stack[top]]=1;
    for(int i=head[u];i!=-1;i=edge[i].next){
        if(!dfs[edge[i].v]){
            tarjan(edge[i].v);
        }
        if(vis[edge[i].v]){
            low[u]=min(low[u],low[edge[i].v]);
        }
    }
    if(low[u]==dfs[u]){
        for(++len;stack[top+1]!=u;){
			ans[stack[top]]=len;
            vis[stack[top--]]=0;
        }
    }
}
int main(){
    int u,v;
    scanf("%d%d",&n,&m);
    memset(head,-1,sizeof(head));
    for(int i=1;i<=m;i++){
        scanf("%d%d",&u,&v);
        push(u,v);
    }
    for(int i=1;i<=n;i++){
        if(!dfs[i]){
            tarjan(i);
        }
    }
	for(int i=1;i<=n;i++){
		num[ans[i]]++;
		maxn=max(maxn,num[ans[i]]);
	}
	for(int i=1;i<=n;i++){
		if(num[ans[i]]==maxn){
			printf("%d ",i);
		}
	}
    return 0;
}
posted @ 2019-07-16 15:59  prestige  阅读(158)  评论(0编辑  收藏  举报