結果

問題 No.30 たこやき工場
ユーザー H3PO4
提出日時 2023-02-21 17:06:49
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 21 ms / 5,000 ms
コード長 1,578 bytes
コンパイル時間 1,155 ms
コンパイル使用メモリ 90,276 KB
最終ジャッジ日時 2025-02-10 19:45:02
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 17
権限があれば一括ダウンロードができます

ソースコード

diff #

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

std::vector<int> topological_sort(int N,
                                  std::vector<std::pair<int, int>> edges) {
    std::vector<int> ins(N);
    std::vector<std::vector<int>> outs(N);
    for (const auto &[v1, v2]: edges) {
        ins.at(v2)++;
        outs.at(v1).push_back(v2);
    }

    std::queue<int> q;
    for (int v2 = 0; v2 < N; v2++) {
        if (ins.at(v2) == 0) { q.push(v2); }
    }
    std::vector<int> res;
    while (!q.empty()) {
        const auto v1 = q.front();
        q.pop();
        res.push_back(v1);
        for (const auto &v2: outs.at(v1)) {
            ins.at(v2)--;
            if (ins.at(v2) == 0) {
                q.push(v2);
            }
        }
    }
    return res;
}

int main() {
    int N, M;
    std::cin >> N;
    std::cin >> M;
    std::vector<std::pair<int, int>> edges;
    std::vector<std::vector<std::pair<int, int>>> materials(N);
    for (int i = 0; i < M; i++) {
        int P, Q, R;
        std::cin >> P >> Q >> R;
        P--;
        R--;
        edges.emplace_back(P, R);
        materials.at(R).emplace_back(P, Q);
    }
    auto tps = topological_sort(N, edges);
    std::reverse(tps.begin(), tps.end());
    std::vector<int> ans(N, 0);
    ans.at(N - 1) = 1;
    for (const auto &x: tps) {
        for (const auto &[p, q]: materials.at(x)) {
            ans.at(p) += q * ans.at(x);
        }
        if (!materials.at(x).empty()) { ans.at(x) = 0; }
    }
    for (int i = 0; i < N - 1; i++) { std::cout << ans.at(i) << std::endl; }
}
0