CSES – Cycle Finding

最短路、回溯

#include<bits/stdc++.h>
#define int long long
#define pii pair<int,int>
#define f first
#define s second
#define fastio ios_base::sync_with_stdio(0);cin.tie(0)
using namespace std;
//declare
const int maxn = 2505;
int n,m,dis[maxn],p[maxn],bad_node;
vector<int> G[maxn], v;
vector<array<int,3>> edges;
bool vis[maxn];
//
void bellman_ford(){
    for(int i=0;i<n-1;i++){
        for(auto [from,to,weight] : edges){
            if(dis[to] > dis[from] + weight){
                p[to] = from;
                dis[to] = min(dis[to], dis[from] + weight);
            }
        }
    }
}
signed main(){
    fastio;
    cin>>n>>m;
    for(int i=0;i<m;i++){
        int a,b,c; cin>>a>>b>>c;
        edges.push_back({a,b,c});
        G[a].push_back(b);
    }
    for(int i=1;i<=n;i++) dis[i] = 1e18;
    dis[1] = 0;
    bellman_ford();
    bool flag = 0;
    for(auto [from,to,weight] : edges){
        if(dis[to] > dis[from] + weight){
            flag = 1;
            p[to] = from;
            bad_node = to;
        }
    }
    if(!flag) return cout<<"NO\n", 0;
    cout<<"YES\n";
    for(int i=0;i<n;i++) bad_node = p[bad_node];
    cout<<bad_node<<" ";
    vector<int> ans;
    int now = bad_node;
    while(1){
        if(vis[now]) break;
        vis[now] = 1;
        ans.push_back(now);
        now = p[now];
    }
    reverse(ans.begin(),ans.end());
    for(int i:ans) cout<<i<<" ";
    cout<<"\n";
    return 0;
}

相關文章

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *