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

本文介绍了一种算法,用于解决在一个由多个村庄和不同类型的路径组成的网络中找到最大的绝对连通区域的问题。该算法使用Tarjan算法求解强连通分量,并通过输出结构体排序来确定最大连通区域及其包含的村庄。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

在幻想乡,上白泽慧音是以知识渊博闻名的老师。春雪异变导致人间之里的很多道路都被大雪堵塞,使有的学生不能顺利地到达慧音所在的村庄。因此慧音决定换一个能够聚集最多人数的村庄作为新的教学地点。人间之里由 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 50010
using 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() {;}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值