AT5256 [ABC142F] Pure(有向图求最小环)

传送门

思路:

枚举每个点作为原点,求最小环长度。
关于求最小环,将spfa算法改为:将与原点所连的所有点放入队列。
输出方案的话,维护前驱数组记录是如何转移的。
推荐一篇很好的博客

代码:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include<map>
#include<set>
#include<vector>
#include<queue>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>PLL;
typedef pair<int, int>PII;
typedef pair<double, double>PDD;
#define I_int ll
inline ll read()
{
    ll x = 0, f = 1;
    char ch = getchar();
    while(ch < '0' || ch > '9')
    {
        if(ch == '-')f = -1;
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9')
    {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}
#define read read()
#define closeSync ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define multiCase int T;cin>>T;for(int t=1;t<=T;t++)
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define repp(i,a,b) for(int i=(a);i<(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define perr(i,a,b) for(int i=(a);i>(b);i--)
ll ksm(ll a, ll b, ll p)
{
    ll res = 1;
    while(b)
    {
        if(b & 1)res = res * a % p;
        a = a * a % p;
        b >>= 1;
    }
    return res;
}
const int inf = 0x3f3f3f3f;
#define PI acos(-1)
const int maxn=1100;

vector<int>g[maxn];
int n,m,mp[maxn][maxn],dis[maxn],pre[maxn],res[maxn],st[maxn];

int spfa(int s){
    memset(st,0,sizeof st);
    queue<int>q;
    memset(dis,0x3f,sizeof dis);
    for(int i=0;i<g[s].size();i++){
        int j=g[s][i];
        pre[j]=s;
        st[j]=1;
        dis[j]=1;
        q.push(j);
    }
    while(!q.empty()){
        int t=q.front();q.pop();
        st[t]=0;
        for(int i=0;i<g[t].size();i++){
            int j=g[t][i];
            if(dis[j]>dis[t]+1){
                dis[j]=dis[t]+1;
                pre[j]=t;
                if(!st[j]){
                    st[j]=1;
                    q.push(j);
                }
            }
        }
    }
    return dis[s];
}

int main()
{
    n=read,m=read;
    rep(i,1,m){
        int u=read,v=read;
        g[u].push_back(v);
        mp[u][v]=1;
    }
    int minn=inf,s=-1;
    for(int i=1;i<=n;i++){
        int tmp=spfa(i);
        if(tmp<minn){
            minn=tmp;
            s=i;
            for(int j=1;j<=n;j++) res[j]=pre[j];
        }
    }
    if(minn==inf){
        puts("-1");
    }
    else{
        printf("%d
",minn);
        vector<int>path;
        int now=s;
        while(res[now]!=s){
            path.push_back(now);
            now=res[now];
        }
        path.push_back(now);
        reverse(path.begin(),path.end());
        for(int i=0;i<path.size();i++)
            cout<<path[i]<<endl;
    }
    return 0;
}

/*

**/





原文地址:https://www.cnblogs.com/OvOq/p/14839012.html