結果

問題 No.2914 正閉路検出
ユーザー momoyuu
提出日時 2024-10-06 17:39:01
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 93 ms / 2,000 ms
コード長 2,323 bytes
コンパイル時間 1,326 ms
コンパイル使用メモリ 107,728 KB
実行使用メモリ 37,544 KB
最終ジャッジ日時 2024-10-06 17:39:11
合計ジャッジ時間 9,540 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 55
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;
using ll = long long;

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);

    int n,m;
    cin>>n>>m;
    vector<vector<pair<ll,ll>>> g(n);
    vector<ll> u(m),v(m),w(m);
    for(int i = 0;i<m;i++){
        cin>>u[i]>>v[i]>>w[i];
        u[i]--;v[i]--;
        g[u[i]].push_back(make_pair(v[i],i));
        g[v[i]].push_back(make_pair(u[i],i));
    }

    vector<int> que;
    vector<int> used(m,0);
    vector<int> vis(n,0);
    vector<ll> p(n,0);

    vector<ll> ans;
    int st;
    bool fn = false;

    auto dfs = [&](auto dfs,int ni,ll now) -> void {
        vis[ni]++;
        p[ni] = now;
        for(auto itr:g[ni]){
            int id = itr.second;
            if(used[id]) continue;
            int to = itr.first;
            if(vis[to]==0){
                ll nxt = now;
                if(u[id]==ni) nxt += w[id];
                else nxt -= w[id];
                used[id] = 1;
                que.push_back(id);
                dfs(dfs,to,nxt);
                if(fn) return;
                que.pop_back();
            }else{
                ll nxt = now;
                if(u[id]==ni) nxt += w[id];
                else nxt -= w[id];
                if(p[to]==nxt) continue;
                int pp = ni;
                while(pp!=to){
                    int nj = que.back();
                    que.pop_back();
                    ans.push_back(nj);
                    if(pp==u[nj]) pp = v[nj];
                    else pp = u[nj];
                }
                ans.push_back(id);
                st = ni;
                fn = true;
                return;
            }
        }
    };
    for(int i = 0;i<n;i++){
        if(vis[i]) continue;
        dfs(dfs,i,0);
        if(fn) break;
    }

    if(ans.empty()){
        cout<<-1<<endl;
        return 0;
    }
    cout<<ans.size()<<endl;
    cout<<st+1<<endl;
    ll now = 0;
    for(int i = 0;i<ans.size();i++){
        if(st==u[ans[i]]){
            now += w[ans[i]];
            st = v[ans[i]];
        }else{
            now -= w[ans[i]];
            st = u[ans[i]];
        }
    }
    if(now<0) reverse(ans.begin(),ans.end());
    for(int i = 0;i<ans.size();i++){
        if(i) cout<<" ";
        cout<<ans[i]+1;
    }
    cout<<endl;

}   


0