题目链接:http://poj.org/problem?id=2449
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<queue> using namespace std; const int maxn = 1005; const int maxe = 100050; const int INF = 0x3f3f3f3f; struct Edge{ int v,w; int next; Edge(int v=0,int w=0,int next=0): v(v), w(w), next(next){} }; struct Heap{ int u,f,g; Heap(int u=0,int f=0,int g=0): u(u), f(f), g(g){} bool operator < (const Heap& rhs) const{ return f > rhs.f; } }; int dist[maxn]; struct Dijkstra{ Edge edges[maxe]; int head[maxn],cnt; bool vis[maxn]; void init(){ memset(head,-1,sizeof(head)); cnt = 0; } void addedge(int u,int v,int w){ edges[cnt] = Edge(v,w,head[u]); head[u] = cnt++; } void solve(int s){ memset(vis,0,sizeof(vis)); memset(dist,0x3f,sizeof(dist)); priority_queue<Heap> Q; Q.push(Heap(s,0,0)); dist[s] = 0; while(!Q.empty()){ Heap temp = Q.top(); Q.pop(); int u = temp.u; int d = temp.f; if(vis[u]) continue; vis[u] = true; for(int i=head[u];i!=-1;i=edges[i].next){ Edge& e = edges[i]; if(dist[e.v] > d + e.w){ dist[e.v] = d + e.w; Q.push(Heap(e.v,dist[e.v],0)); } } } } }solver1; struct A_Star{ Edge edges[maxe]; int head[maxn],cnt; int num[maxn]; void init(){ memset(head,-1,sizeof(head)); cnt = 0; } void addedge(int u,int v,int w){ edges[cnt] = Edge(v,w,head[u]); head[u] = cnt++; } int solve(int s,int t,int k){ memset(num,0,sizeof(num)); priority_queue<Heap> Q; if(dist[s] >= INF) return -1; Q.push(Heap(s,dist[s],0)); while(!Q.empty()){ Heap temp = Q.top(); Q.pop(); int u = temp.u; num[u]++; if(num[t] == k){ return temp.f; } if(num[u] > k){ continue; } for(int i=head[u];i!=-1;i=edges[i].next){ Edge& e = edges[i]; int g = temp.g + e.w; int f = g + dist[e.v]; Q.push(Heap(e.v,f,g)); } } return -1; } }solver2; int main() { //freopen("E:\acm\input.txt","r",stdin); int N,M; cin>>N>>M; solver1.init(); solver2.init(); for(int i=1;i<=M;i++){ int u,v,w; scanf("%d %d %d",&u,&v,&w); solver1.addedge(v,u,w); solver2.addedge(u,v,w); } int s,t,k; scanf("%d %d %d",&s,&t,&k); solver1.solve(t); if(s == t) k++; int ans = solver2.solve(s,t,k); printf("%d ",ans); }