HDU 6181:Two Paths(A* + SPFA)

题目链接

题意

给出n个点m条边的无向图,求次短路。

思路

POJ 2449 类似,只不过大小要开成long long。

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 100011;
const int INF = 0x3f;
struct Edge {
    int v, nxt; LL w;
} edge[N*2];
struct Node {
    int u; LL g, h;
    friend bool operator < (const Node &a, const Node &b) {
        return a.g + a.h > b.h + b.g;
    }
};
int n, m, vis[N], head[N], tot;
LL h[N];

void Add(int u, int v, LL w) {
    edge[tot] = (Edge) { v, head[u], w }; head[u] = tot++;
    edge[tot] = (Edge) { u, head[v], w }; head[v] = tot++;
}

void Spfa(int s, int t) {
    memset(h, INF, sizeof(h));
    memset(vis, 0, sizeof(vis));
    queue<int> que; que.push(t);
    vis[t] = 1; h[t] = 0;
    while(!que.empty()) {
        int u = que.front(); que.pop();
        vis[u] = 0;
        for(int i = head[u]; ~i; i = edge[i].nxt) {
            int v = edge[i].v, w = edge[i].w;
            if(h[v] > h[u] + w) {
                h[v] = h[u] + w;
                if(!vis[v]) vis[v] = 1, que.push(v);
            }
        }
    }
}

LL Astar(int s, int t, int k) {
    Node now = (Node) { s, 0LL, h[s] };
    priority_queue<Node> que; que.push(now);
    int cnt = 0;
    while(!que.empty()) {
        now = que.top(); que.pop();
        int u = now.u; LL gg = now.g, hh = now.h;
//        printf("%d : %d - %d
", u, gg, hh);
        if(u == t) cnt++;
        if(cnt == k) return gg + hh;
        for(int i = head[u]; ~i; i = edge[i].nxt) {
            int v = edge[i].v; LL w = edge[i].w;
            now = (Node) { v, gg + w, h[v] };
            que.push(now);
        }
    }
    return 0;
}

int main() {
    int t; scanf("%d", &t);
    while(t--) {
        scanf("%d%d", &n, &m);
        memset(head, -1, sizeof(head)); tot = 0;
        for(int i = 1; i <= m; i++) {
            int u, v; LL w;
            scanf("%d%d%lld", &u, &v, &w);
            Add(u, v, w);
        }
        Spfa(1, n);
        printf("%lld
", Astar(1, n, 2));
    }
    return 0;
}

原文地址:https://www.cnblogs.com/fightfordream/p/7578485.html