1 条题解

  • 0
    @ 2026-11-2 14:09:00

    贸易(Trade) 题解

    思路分析

    按题目要求使用对应数据结构与算法模拟/递推求解,注意数据范围边界与时间复杂度。

    参考代码

    #include <iostream>
    #include <vector>
    #include <queue>
    #include <tuple>
    using namespace std;
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n, m, k;
        if (!(cin >> n >> m >> k)) return 0;
        vector<vector<pair<int, long long>>> adj(n + 1);
        for (int i = 0; i < m; ++i) {
            int u, v;
            long long w;
            cin >> u >> v >> w;
            adj[u].push_back({v, w});
            adj[v].push_back({u, w});
        }
        const long long INF = (1LL << 58);
        vector<vector<long long>> dist(n + 1, vector<long long>(4, INF));
        using State = tuple<long long, int, int>;
        priority_queue<State, vector<State>, greater<State>> pq;
        dist[1][0] = 0;
        pq.push({0, 1, 0});
        while (!pq.empty()) {
            auto [d, u, s] = pq.top();
            pq.pop();
            if (d != dist[u][s]) continue;
            for (auto& edge : adj[u]) {
                int v = edge.first;
                long long w = edge.second;
                if (d + w < dist[v][s]) {
                    dist[v][s] = d + w;
                    pq.push({dist[v][s], v, s});
                }
                if (!(s & 1) && d < dist[v][s | 1]) {
                    dist[v][s | 1] = d;
                    pq.push({dist[v][s | 1], v, s | 1});
                }
                if (!(s & 2) && d + 2 * w < dist[v][s | 2]) {
                    dist[v][s | 2] = d + 2 * w;
                    pq.push({dist[v][s | 2], v, s | 2});
                }
                if (s == 0 && d + w < dist[v][3]) {
                    dist[v][3] = d + w;
                    pq.push({dist[v][3], v, 3});
                }
            }
        }
        for (int i = 0; i < k; ++i) {
            int t;
            cin >> t;
            cout << (t == 1 ? 0 : dist[t][3]) << "\n";
        }
        return 0;
    }
    
    • 1

    信息

    ID
    8788
    时间
    2000ms
    内存
    256MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者