跳到正文

个人记录

2026/4/26 ans

Leo3721约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年6月7日
更新
2026年6月21日
篇幅
约 3 分钟
获赞
1

版本

  1. v2当前
  2. v1
C++
#include <bits/stdc++.h>
using namespace std;
struct node{
    int u,e,s,dis;
    bool operator<(const node& r) const {
        return dis>r.dis;
    }
};
int main() {
    ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    int n,m,k;
    cin>>n>>m>>k;
    n--;
    vector<vector<vector<vector<pair<int,int>>>>>g(n+1,vector<vector<vector<pair<int,int>>>>(k,vector<vector<pair<int,int>>>(k)));
    for(int i=0;i<m;i++){
        int u,v,w;
        cin>>u>>v>>w;
        u--;v--;
        for(int e=0;e<k;e++){
            for(int s=0;s<k;s++){
                int ne=(e+1)%k;
                int ns=(s+w)%k;
                g[u][e][s].push_back({v*k*k+ne*k+ns,w});
                g[v][e][s].push_back({u*k*k+ne*k+ns,w});
            }
        }
    }
    int ts=(n+1)*k*k;
    vector<int>dis(ts,0x3f3f3f3f);
    vector<bool>vis(ts,0);
    priority_queue<node>heap;
    int st=0;
    dis[st]=0;
    heap.push({0,0,0,0});
    while(!heap.empty()){
        node qw=heap.top();heap.pop();
        int u=qw.u,e=qw.e,s=qw.s,d=qw.dis;
        int sa=u*k*k+e*k+s;
        if(vis[sa])continue;
        vis[sa]=1;
        for(auto&ed:g[u][e][s]){
            int ns=ed.first,wi=ed.second;
            if(dis[ns]>d+wi){
                dis[ns]=d+wi;
                heap.push({ns/(k*k),(ns/k)%k,ns%k,dis[ns]});
            }
        }
    }
    int ans=dis[n*k*k];
    cout<<(ans==0x3f3f3f3f?-1:ans);
    return 0;
}

T770635

原文