#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
*/
第K短路
最新推荐文章于 2022-04-07 23:07:35 发布