第K短路

来源:互联网 发布:ctp高频交易系统源码 编辑:程序博客网 时间:2024/06/03 13:58
#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;}/*671 2 1 102 3 2 103 4 3 101 5 10 45 3 10 65 6 5 166 4 5 4*/

0 0
原创粉丝点击