POJ 2449 Remmarguts' Date 第k短路

POJ 2449 Remmarguts' Date 第k短路

题意:有n个点,m条边,m行是a到b的权值为c,最后一行是问s到e的第k短路是多少,没有则输出-1

第k短路的模板,代码是从https://www.cnblogs.com/shuaihui520/p/9623597.html这个大佬这里copy的,思路是从书上看到的。(算法竞赛进阶指南124页)

#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
const int INF  = 0x3f3f3f3f;
const int maxn = 1024;
const int maxm = 100008;
struct EDGE{ int v, nxt, w; };
struct NODE{
    int pos, Cost, F;
    bool operator < (const NODE & rhs) const {
        if(this->F == rhs.F) return this->Cost > rhs.Cost;
        return this->F > rhs.F;
    };
};

EDGE Edge[maxm];
EDGE REdge[maxm];
int Head[maxn], RHead[maxn];
int cnt, Rcnt;
int N;
void init()
{
    memset(Head, -1, sizeof(Head));
    memset(RHead, -1, sizeof(RHead));
    cnt = Rcnt = 0;
}

void AddEdge(int from, int to, int weight)
{
    Edge[cnt].w = weight;
    Edge[cnt].v = to;
    Edge[cnt].nxt = Head[from];
    Head[from] = cnt++;
}

void AddREdge(int from, int to, int weight)
{
    REdge[Rcnt].w = weight;
    REdge[Rcnt].v = to;
    REdge[Rcnt].nxt = RHead[from];
    RHead[from] = Rcnt++;
}

int vis[maxn];
int H[maxn];
void SPFA(int st)
{
    queue<int> que;
    memset(H, INF, sizeof(H));
    memset(vis, 0, sizeof(vis));
    H[st] = 0;
    que.push(st);
    while(!que.empty()){
        int cur = que.front(); que.pop();
        vis[cur] = 0;
        for(int i=RHead[cur]; i!=-1; i=REdge[i].nxt) {
            int v = REdge[i].v;
            if(H[v] > H[cur] + REdge[i].w) {
                H[v] = H[cur] + REdge[i].w;
                if(!vis[v]) {
                    vis[v] = 1;
                    que.push(v);
                }
            }
        }
    }
}

int A_Star(int s, int t, int k)
{
    if(s == t) k++;
    if(H[s]==INF) return -1;
    priority_queue<NODE> que;
    NODE cur, into;
    cur.pos = s;
    cur.Cost = 0;
    cur.F = H[s];
    que.push(cur);
    int CNT = 0;
    while(!que.empty()){
        cur = que.top();
        que.pop();
        if(cur.pos == t) CNT++;
        if(CNT == k) return cur.Cost;
        for(int i=Head[cur.pos]; i!=-1; i=Edge[i].nxt){
            into.Cost = cur.Cost+Edge[i].w;
            into.F = cur.Cost+Edge[i].w+H[Edge[i].v];
            into.pos = Edge[i].v;
            que.push(into);
        }
    }return -1;
}


int main(void)
{
    int M, K, S, des;
    while(~scanf("%d %d", &N, &M)){
        init();
        int from, to, weight;
        while(M--){
            scanf("%d %d %d",&from, &to, &weight);
             AddEdge(from, to, weight);
            AddREdge(to, from, weight);
        }
        scanf("%d %d %d", &S, &des, &K);
        SPFA(des);
        printf("%d
", A_Star(S,des,K));
    }
    return 0;
}

原文地址:https://www.cnblogs.com/fanshhh/p/11878595.html