Descriptionios
Inputapi
Outputapp
Sample Inputdom
2 2 1 2 5 2 1 4 1 2 2
Sample Outputide
14
連接:http://poj.org/problem?id=2449
題目大意:N個站,S是大廳號,T是王子所在地。求S->T的第K短路,若是不存在第K短路,輸出-1...
解題思路:K短路模板
代碼以下:
#include <stdio.h> #include <string.h> #include <queue> #include <iostream> #include <algorithm> using namespace std; #define N 1005 #define INF 999999999 int vis[N], dis[N], times[N], s, t, k; struct Forward { int forv, forw; }; struct Edge { int v, w; friend bool operator < (Edge x, Edge y) { return x.w > y.w; } }; struct Astar { int asv, asw; friend bool operator < (Astar x, Astar y) { return x.asw+dis[x.asv] > y.asw+dis[y.asv]; } }; vector<Forward>vFor[N]; vector<Forward>vRes[N]; void dijkstra() { int i; memset(vis, 0, sizeof(vis)); for(i=1; i<=1000; i++) dis[i]=INF; dis[t]=0; priority_queue<Edge>Q; Edge edge1, edge2; edge1.v=t; edge1.w=0; Q.push(edge1); while(!Q.empty()) { edge1=Q.top(); Q.pop(); int v=edge1.v, w=edge1.w; vis[v]=1; for(i=0; i<vRes[v].size(); i++) { int vv=vRes[v][i].forv, ww=vRes[v][i].forw; if(!vis[vv]&&dis[vv]>dis[v]+ww) { dis[vv]=dis[v]+ww; edge2.v=vv; edge2.w=dis[vv]; Q.push(edge2); } } } } int astar() { memset(times, 0, sizeof(times)); Astar ss, tt; if(dis[s]==INF) return -1; priority_queue<Astar>Q; ss.asv=s; ss.asw=0; Q.push(ss); while(!Q.empty()) { ss=Q.top(); Q.pop(); int v=ss.asv; int w=ss.asw; times[v]++; if(v==t&×[t]==k) return w; if(times[v]>k) continue; for(int i=0; i<vFor[v].size(); i++) { int forv=vFor[v][i].forv, forw=vFor[v][i].forw+w; tt.asv=forv, tt.asw=forw; Q.push(tt); } } return -1; } int main() { int i, j, a, b, c, m, n; while(scanf("%d%d", &n, &m)!=EOF) { for(i=0; i<=1000; i++) { vFor[i].clear(); vRes[i].clear(); } for(i=0; i<m; i++) { scanf("%d%d%d", &a, &b, &c); Forward f; f.forv=b, f.forw=c; vFor[a].push_back(f); f.forv=a; vRes[b].push_back(f); } scanf("%d%d%d", &s, &t, &k); dijkstra(); if(s==t) k++; printf("%d\n", astar()); } return 0; }