dijkstra 算法40分求助!回复必关!
查看原帖
dijkstra 算法40分求助!回复必关!
482998
jeffstart楼主2023/1/28 15:01
#include <bits/stdc++.h>
using namespace std;

struct edge {
    int to, cost;
    edge(int _to, int _cost) { to = _to, cost = _cost; }
};

const int N = 110;
int resident[N];
vector<edge> G[N];
typedef pair<int, int> P;
int d[N];

void dijkstra(int s) {
    memset(d, 0x3f, sizeof(d));
    d[s] = 0;
    priority_queue<P, vector<P>, greater<P>> que;
    que.push({0, s});
    while (!que.empty()) {
        P p = que.top();
        que.pop();
        int v = p.second;
        if (d[v] < p.first) {
            continue;
        }
        for (auto e : G[v]) {
            if (d[e.to] > d[v] + e.cost) {
                d[e.to] = d[v] + e.cost;
                que.push({d[e.to], e.to});
            }
        }
    }
}

int main() {
    ios::sync_with_stdio(false), cin.tie(0);
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> resident[i];
        int u, v;
        cin >> u >> v;
        G[i].push_back(edge(u, 1));
        G[u].push_back(edge(i, 1));
        G[i].push_back(edge(v, 1));
        G[v].push_back(edge(i, 1));
    }
    int ans = INT_MAX;
    for (int i = 1; i <= n; i++) {
        dijkstra(i);
        int res = 0;
        for (int j = 1; j <= n; j++) {
            res += d[j] * resident[j];
        }
        ans = min(ans, res);
    }
    cout << ans << "\n";
    return 0;
}
2023/1/28 15:01
加载中...