SPFA + A*
#include <cstdio> #include <queue> #include <cstring> #include <algorithm> using namespace std; struct node { int v, dis, f, next; friend bool operator <(node a, node b){ return a.f>b.f; } }; const int INF = 1e9; const int maxn = 1005; const int maxm = 100005; node edge[maxm], edgef[maxm]; int head[maxn], e, headf[maxn], dis[maxn], n, m, s, t, k; void Add(int u, int v, int dis){ edge[e].v = v; edge[e].dis = dis; edge[e].next = head[u]; head[u] = e; edgef[e].v = u; edgef[e].dis = dis; edgef[e].next = headf[v]; headf[v] = e++; } void init(){ int i, u, v, dis; memset(head, -1, sizeof head ); memset(headf, -1, sizeof headf ); e = 0; for(i=1; i<=m; ++i){ scanf("%d%d%d", &u, &v, &dis); Add(u, v, dis); } } int cnt[maxn], vis[maxn]; void SPFA(int s, int t){ int u, v, i, j; queue<int> q; memset(vis, 0, sizeof vis ); memset(cnt, 0, sizeof cnt ); for(i=0; i<=n; ++i) dis[i] = INF; vis[s]=1; dis[s]=0; q.push(s); while(!q.empty()){ u = q.front(); q.pop(); vis[u] = 0; cnt[u]++; if(cnt[u]>=n) return ; for(j=headf[u];~j;j=edgef[j].next) if(dis[v=edgef[j].v]>dis[u]+edgef[j].dis){ dis[v] = dis[u] + edgef[j].dis; if(!vis[v]) vis[v]=1,q.push(v); } } } int A_STAR(int s, int t, int k){ int cnt=0, i; node e, next; priority_queue<node> q; if(s==t) k++; if(dis[s]==INF) return -1; e.v = s; e.dis = 0; e.f = dis[s]; q.push(e); while(!q.empty()){ e = q.top(); q.pop(); if(e.v==t&&++cnt==k) return e.dis; for(i=head[e.v]; ~i; i=edge[i].next){ next.v = edge[i].v; next.dis = e.dis + edge[i].dis; next.f = next.dis + dis[next.v]; q.push(next); } } return -1; } void solve(){ scanf("%d%d%d", &s, &t, &k); SPFA(t, s); printf("%d\n", A_STAR(s, t, k)); } int main(){ while(~scanf("%d%d", &n, &m)){ init(); solve(); } return 0; }
参考链接:
http://www.cnblogs.com/vongang/archive/2012/07/17/2594737.html
http://yzmduncan.iteye.com/blog/1162759
http://ycool.com/post/krb8pah
poj2449 Remmarguts' Date,第K短路
时间: 2024-10-06 09:52:12