上白泽慧音(tarjan求强连通分量)

来源:互联网 发布:acrobat for mac 破解 编辑:程序博客网 时间:2024/05/27 20:48

题目描述

在幻想乡,上白泽慧音是以知识渊博闻名的老师。春雪异变导致人间之里的很多道路都被大雪堵塞,使有的学生不能顺利地到达慧音所在的村庄。因此慧音决定换一个能够聚集最多人数的村庄作为新的教学地点。人间之里由 N 个村庄(编号为 1..N)和 M 条道路组成,道路分为两种一种为单向通行的,一种为双向通行的,分别用 1 和 2 来标记。如果存在由村庄 A 到达村庄 B 的通路,那么我们认为可以从村庄 A 到达村庄 B,记为(A,B)。当(A,B)和(B,A)同时满足时,我们认为 A,B 是绝对连通的,记为

输入格式

第 1 行:两个正整数 N,M
第 2..M+1 行:每行三个正整数 a,b,t, t = 1 表示存在从村庄 a 到 b 的单向道路,t = 2 表示村庄a,b 之间存在双向通行的道路。保证每条道路只出现一次。

输出格式

第 1 行: 1 个整数,表示最大的绝对连通区域包含的村庄个数。
第 2 行:若干个整数,依次输出最大的绝对连通区域所包含的村庄编号。

输入样例

5 5
1 2 1
1 3 2
2 4 2
5 1 2
3 5 1

输出样例

3
1 3 5

数据范围

对于 60%的数据:N <= 200 且 M <= 10,000
对于 100%的数据:N <= 5,000 且 M <= 50,000


tarjan求强连通分量,很裸的,输出结构体排序处理,就可以A掉了

代码

#include<cstdio>#include<stack>#include<cstring>#include<algorithm>#define MAXN 50010using namespace std;int n,m;int dfn[MAXN],low[MAXN],cnt;bool vis[MAXN];int head[MAXN],tot;struct node {    int tal;    short s[5000];};node e[5000];struct nod {    int to;    int next;};nod  ed[MAXN*2];stack<int> s;inline void read(int&x) {    x=0;char c=getchar();    while(c>'9'||c<'0') c=getchar();    while(c>='0'&&c<='9') x=10*x+c-48,c=getchar();}inline void add(int x,int y) {    ed[++tot].to=y;    ed[tot].next=head[x];    head[x]=tot;}inline bool cmp(const node&a,const node&b) {    if(a.tal==b.tal)      for(int i=1;i<=a.tal;i++)        return a.s[i]<b.s[i];    return a.tal>b.tal;}inline void tarjan(int u) {    dfn[u]=low[u]=++tot;    vis[u]=true;    s.push(u);    for(int i=head[u];i;i=ed[i].next) {        int v=ed[i].to;        if(!dfn[v]) {            tarjan(v);            low[u]=min(low[u],low[v]);        }        else if(vis[v]) low[u]=min(low[u],dfn[v]);    }     if(dfn[u]==low[u]) {        ++cnt;        int t,sum=0;        do {            t=s.top();            s.pop();            vis[t]=false;            e[cnt].s[++sum]=t;        }while(u!=t);        e[cnt].tal=sum;        sort(e[cnt].s+1,e[cnt].s+sum+1);    }}int hh() {    freopen("classroom.in","r",stdin);    freopen("classroom.out","w",stdout);    read(n);read(m);    int x,y,z;    for(int i=1;i<=m;i++) {        read(x);read(y);read(z);        if(z==1) add(x,y);        else add(x,y),add(y,x);    }    tot=0;    for(int i=1;i<=n;i++) {        if(!dfn[i])          tarjan(i);    }    sort(e+1,e+1+cnt,cmp);    printf("%d\n",e[1].tal);    for(int i=1;i<=e[1].tal;i++)      printf("%d ",e[1].s[i]);    printf("\n");    return 0;}int hhh=hh();int main() {;}
0 0