dijsktra18分求调(感觉和100的dij一样啊))
查看原帖
dijsktra18分求调(感觉和100的dij一样啊))
1127749
Longerdoc楼主2024/8/8 00:01
#include<iostream>
#include<queue>
#include<algorithm>
#include<vector>
#include<cstring>
using namespace std;
const int N = 4e6 + 10;
typedef long long ll;
typedef pair<int, int> ppi;
 int h[N], e[N], w[N], ne[N], d[N], idx;
int n, m, k;
int s, t;
bool st[N];
void add(int a, int b, int c) {
    e[idx] = b; ne[idx] = h[a]; w[idx] = c;
    h[a] = idx++;
}
ll dijsktra(int s, int t) {
    memset(d, 0x3f, sizeof(d));
    d[s] = 0;
    priority_queue<ppi, vector<ppi>, greater<ppi> > heap;
    heap.push({ 0,s });
    while (!heap.empty()) {
        auto t = heap.top();
        heap.pop();
        int ver = t.first;
        int u = t.second;
        if (st[u]) continue; //此时u点的最短路已经确定
        st[u] = true;
        for (int i = h[u]; i != -1; i = ne[i]) {
            int j = e[i];
            if (d[j] > ver + w[i]) {
                d[j] = w[i] + ver;//d[j]此时第一次更新就是最终的最短路了
                heap.push({ d[j],j });
            }
        }
    }

    return d[t + k * n];
}
int main() {
    cin >> n >> m >> k;
    cin >> s >> t;
    memset(h, -1, sizeof(h));
    for (int i = 0; i < m; i++) {
        int x, y, c;
        cin >> x >> y >> c;
        add(x, y, c); add(x, y, c);
        for (int j = 1; j <= k; j++) {
            add(x + (j - 1) * n, y + j * n, 0);
            add(y + (j - 1) * n, x + j * n, 0);
            add(x + j * n, y + j * n, c);
            add(y + j * n, x + j * n, c);
        }
    }

    cout << dijsktra(s, t);
}

2024/8/8 00:01
加载中...