P4568 [JLOI2011] 飞行路线

原题链接

题解

分层图最短路模板题

code

 

#include<bits/stdc++.h>
using namespace std;
struct Node{
    int way,key,value;
    bool operator >(const Node &a)const{
        return value>a.value;
    }
};
const int N=1e4+5;
const int M=1e5+5;
const int MAX=5e8;
int head[N],Next[M],to[M],w[M],vis[N][12],dis[N][12];
int n,m,k,cnt=1,s,t;
void initial(){
    for (int i=0;i<n;i++){
        for (int j=0;j<=k;j++){
            dis[i][j]=MAX;
            vis[i][j]=0;
        }
    }
}
void build(int a,int b,int c){
    Next[cnt]=head[a];
    to[cnt]=b;
    w[cnt]=c;
    head[a]=cnt++;
}
int main(){
    cin>>n>>m>>k;
    cin>>s>>t;
    initial();
    for (int i=1;i<=m;i++) {
        int a,b,c;
        cin>>a>>b>>c;
        build(a,b,c);
        build(b,a,c);
    }
    priority_queue<Node,vector<Node>,greater<Node> > que;
    Node x;
    x.way=s;x.value=0;x.key=0;
    dis[s][0]=0;
    que.push(x);
    while (!que.empty()){
        x=que.top();que.pop();
        if (vis[x.way][x.key]) continue;
        vis[x.way][x.key]=1;
        if (x.way==t) {
            cout<<x.value<<endl;
            break;
        }
        for (int i=head[x.way];i>0;i=Next[i]){
            if (x.key<k){
                if (!vis[to[i]][x.key+1] && x.value<dis[to[i]][x.key+1]){
                    dis[to[i]][x.key+1]=x.value;
                    Node y;
                    y.way=to[i];y.value=x.value;y.key=x.key+1;
                    que.push(y);
                }
            }
            if (!vis[to[i]][x.key] && x.value+w[i]<dis[to[i]][x.key]){
                dis[to[i]][x.key]=x.value+w[i];
                Node y;
                y.way=to[i];y.value=x.value+w[i];y.key=x.key;
                que.push(y);
            }
        }
    }
    return 0;
}

 

posted @ 2024-03-30 00:01  黑屿白  阅读(26)  评论(0)    收藏  举报