【LuoguP2939】 [USACO09FEB]Revamping Trails G

code

#include <algorithm>
#include <cstring>
#include <cctype>
#include <queue>
#include <cstdio>

using namespace std;
using P = pair<int, int>;
inline int read(){
    
    
    int x = 0; char ch = getchar();
    while (!isdigit(ch)){
    
    ch = getchar();}
    while (isdigit(ch)){
    
    
        x = (x << 1) + (x << 3) + (ch ^ 48);
        ch = getchar();
    }return x;
}

const int N = 3e5 + 10;
const int M = 5e6 + 10;
int n, m, k, tot;
int head[N], dis[N], vis[N];
struct edge{
    
    
    int to, nxt, w;
}e[M];

inline void add(int u, int v, int w){
    
    
    e[++tot] = {
    
    v, head[u], w};
    head[u] = tot;
}

void dij(int start){
    
    
    memset(dis, 0x3f, sizeof dis);
    priority_queue<P, vector<P>, greater<P> > que;
    dis[start] = 0;
    que.push(make_pair(0, start));
    while (!que.empty()){
    
    
        int u = que.top().second;
        que.pop();
        if (vis[u]) continue;
        vis[u] = 1;
        for (int i = head[u]; ~i; i = e[i].nxt) {
    
    
            int v = e[i].to, w  = e[i].w;
            if (dis[v] > dis[u] + w){
    
    
                dis[v] = dis[u] + w;
                que.push(make_pair(dis[v], v));
            }
        }
    }
}

int main(){
    
    
    memset(head, -1, sizeof head);
    n = read(), m = read(), k = read();
    for (int i = 0, u, v, val; i < m; ++i) {
    
    
        u = read(), v = read(), val = read();
        add(u, v, val), add(v, u, val);
        for (int j = 1; j <= k; ++j) {
    
    
            add(u + n*(j - 1), v + n*j, 0);
            add(v + n*(j - 1), u + n*j, 0);
            add(u + n*j, v + n*j, val);
            add(v +n*j, u + n*j, val);
        }
    }
    for (int i = 1; i <= k; ++i) {
    
    
        add(n + (i - 1)*n, n + i*n, 0);
    }
    dij(1);
    printf("%d\n", dis[n*k + n]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_50070650/article/details/112842471