Loading

洛谷-P1726 上白泽慧音

上白泽慧音

找一个点数量最大,且字典序最小的强连通块

\(tarjan\)

\(tarjan\) 在跑的时候顺便维护一个连通块的数量

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;
const int maxn = 5e3 + 10;
vector<int>gra[maxn];
stack<int>st;
int scc[maxn], cnt_scc = 0;
int dfn[maxn], low[maxn], tp = 0;
int vis[maxn], cnt[maxn];

void tarjan(int now)
{
    dfn[now] = low[now] = ++tp;
    st.push(now);
    vis[now] = 1;
    for(int nex : gra[now])
    {
        if(dfn[nex] == 0)
        {
            tarjan(nex);
            low[now] = min(low[now], low[nex]);
        }
        else if(vis[nex])
            low[now] = min(low[now], low[nex]);
    }
    if(low[now] == dfn[now])
    {
        cnt_scc++;
        while(st.top() != now)
        {
            int x = st.top();
            vis[x] = 0;
            scc[x] = cnt_scc;
            cnt[cnt_scc]++;
            st.pop();
        }
        scc[now] = cnt_scc;
        st.pop();
        vis[now] = 0;
        cnt[cnt_scc]++;
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n, m;
    cin >> n >> m;
    for(int i=0; i<m; i++)
    {
        int a, b, t;
        cin >> a >> b >> t;
        gra[a].push_back(b);
        if(t == 2)
            gra[b].push_back(a);
    }
    for(int i=1; i<=n; i++)
        if(dfn[i] == 0) tarjan(i);
    int way = 0, num = -1;
    for(int i=1; i<=n; i++)
    {
        if(num < cnt[scc[i]])
        {
            num = cnt[scc[i]];
            way = scc[i];
        }
    }
    cout << num << endl;
    int cur = 0;
    for(int i=1; i<=n; i++)
    {
        if(scc[i] == way)
        {
            if(cur++) cout << " ";
            cout << i;
        }
    }
    cout << endl;
    return 0;
}
posted @ 2022-08-12 14:14  dgsvygd  阅读(38)  评论(0编辑  收藏  举报