第K短路

#include<cstdio>
#include<queue>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 1005;          //图中点的个数
const int INF  = 10000007;      //无限大的边权
struct Edge{;
    int to,dist,speed;
    Edge(int to,int dist,int speed):to(to),dist(dist),speed(speed){};
};
struct State{
    int pos,speed;
    int f,g;
    State(int pos,int g,int ,int speed):
        pos(pos),g(g),f(f),speed(speed){};
    bool operator < (const State &temp)const{
        if(f != temp.f)
            return f > temp.f;
        return g > temp.g;
    }
};
void AddEdge(vector<Edge>&vec,int v,int d,int sp){
    vec.push_back(Edge(v,d,sp));
}

vector<Edge>G1[maxn];
vector<Edge>G2[maxn];
int dist[maxn],n,m;
bool SPFA(int s){               //利用SPFA算法求解每个点到终点的距离
    bool cnt[maxn],inq[maxn];
    memset(cnt,false,sizeof(cnt));
    memset(inq,false,sizeof(cnt));
    for(int i = 1; i <= n; i++) dist[i] = INF;
    queue<int>q;
    dist[s] = 0;
    inq[s] = true;
    q.push(s);
    while(!q.empty()){
        int now = q.front(); q.pop();
        inq[now] = false;
        for(int i = 0; i < G2[now].size(); i++){
            int to = G2[now][i].to,d = G2[now][i].dist;
            if(dist[to] > dist[now] + d){
                dist[to] = dist[now] + d;
                if(!inq[now]){
                    q.push(to);
                    inq[to] = true;
                    if(++cnt[to] > n)
                        return false;
                }
            }
        }
    }
    return true;
}
int  A_Star(int s,int t,int sp){
    priority_queue<State>q;
    State temp(0,0,0,0);
    if(dist[s] == INF) return -1;
    q.push(State(s,0,dist[s],0));
    while(!q.empty()){
        State now = q.top(); q.pop();
        int pos = now.pos;
        if(now.pos == t){                   //到达了终点,并且满足约束条件
            if(now.speed  <= sp)
                return now.f;
        }
        for(int i = 0; i < G1[pos].size(); i++){
            int tpos = G1[pos][i].to,d = G1[pos][i].dist,sp = G1[pos][i].speed;
            temp.pos = tpos;
            temp.g   = now.g + d;
            temp.f   = temp.g + dist[temp.pos];
            temp.speed = now.speed + G1[pos][i].speed;
            q.push(temp);
        }
    }
    return -1;
}
int main(){
    scanf("%d%d",&n,&m);
    for(int i = 0; i < m; i++){
        int u,v,d,speed;
        scanf("%d%d%d%d",&u,&v,&d,&speed);      //加入一条边的长度、通过时间
        AddEdge(G1[u],v,d,speed);
        AddEdge(G2[v],u,d,speed);
    }
    int s,t,k;
    scanf("%d%d%d",&s,&t,&k);
    SPFA(t);
    printf("%d\n",A_Star(s,t,k));
    return 0;
}
/*
6
7
1 2 1 10
2 3 2 10
3 4 3 10
1 5 10 4
5 3 10 6
5 6 5 16
6 4 5 4

*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值