結果

問題 No.2712 Play more!
ユーザー rurun
提出日時 2024-03-31 15:14:13
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
WA  
実行時間 -
コード長 2,077 bytes
コンパイル時間 820 ms
コンパイル使用メモリ 76,840 KB
最終ジャッジ日時 2025-02-20 17:45:02
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 31 WA * 2
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
using namespace std;
using lint = long long;

// 無限大を表す値
const long long INF = 1LL << 60; // 十分大きな値を用いる (ここでは 2^60)

// 辺を表す型,ここでは重みを表す型を long long 型とする
struct Edge {
    int to; // 隣接頂点番号
    long long w; // 重み
    Edge(int to, long long w) : to(to), w(w) {}
};

// 重み付きグラフを表す型
using Graph = vector<vector<Edge>>;

// 緩和を実施する関数
template<class T> bool chmin(T& a, T b) {
    if (a > b) {
        a = b;
        return true;
    }
    else return false;
}

int main() {
    // 頂点数,辺数,始点
    int n, m, s=0;
    cin >> n >> m;
    vector<lint> A(n);
    for (int i = 0; i < n; i++) cin >> A[i];

    // グラフ
    Graph G(n);
    for (int i = 0; i < m; ++i) {
        int a, b, w;
        cin >> a >> b >> w;
        a--, b--;
        G[a].push_back(Edge(b, -(A[a]-w)));
    }

    // ベルマン・フォード法
    bool exist_negative_cycle = false; // 負閉路をもつかどうか
    vector<long long> dist(n, INF);
    dist[s] = 0;
    for (int iter = 0; iter < n; ++iter) {
        bool update = false; // 更新が発生したかどうかを表すフラグ
        for (int v = 0; v < n; ++v) {
            // dist[v] = INF のときは頂点 v からの緩和を行わない
            if (dist[v] == INF) continue;

            for (auto e : G[v]) {
                // 緩和処理を行い,更新されたら update を true にする
                if (chmin(dist[e.to], dist[v] + e.w)) {
                    update = true;
                }
            }
        }

        // 更新が行われなかったら,すでに最短路が求められている
        if (!update) break;

        // N 回目の反復で更新が行われたならば,負閉路をもつ
        if (iter == n - 1 && update) exist_negative_cycle = true;
    }

    // 結果出力
    if (exist_negative_cycle) cout << "inf" << endl;
    else cout << -dist[n-1]+A[n-1] << endl;
}
0