K短路:dijkstra+A*(rec).
k短路问题模板.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
const int maxn=100010;
int n,m,l;
int dis[maxn];
bool vis[maxn];
int head1[maxn];
int cnt[maxn];
int head2[maxn];
struct edge{
int to;
int next;
int val;
}s1[maxn*2],s2[maxn*2];
struct node{
int f;
int g;
int from;
bool operator < (node a)const
{
if(a.f==f)
return g>a.g;
return f>a.f;
}
};
void add(int x,int y,int k)
{
l++;
s1[l].to=y;
s1[l].next=head1[x];
s1[l].val=k;
head1[x]=l;
s2[l].to=x;
s2[l].next=head2[y];
s2[l].val=k;
head2[y]=l;
}
void spfa(int k)
{
int i,j;
for(i=1;i<=n;i++)
dis[i]=maxn;
dis[k]=0;
queue<int>q;
q.push(k);
vis[k]=1;
while(!q.empty())
{
int x=q.front();
q.pop();
vis[x]=0;
for(i=head2[x];i!=-1;i=s2[i].next)
{
int y=s2[i].to;
if(dis[y]>dis[x]+s2[i].val)
{
dis[y]=dis[x]+s2[i].val;
if(!vis[y])
{
q.push(y);
vis[y]=1;
}
}
}
}
}
int make(int x,int y,int k)
{
if(x==y)
k++;
if(dis[x]==maxn)
return -1;
priority_queue<node>q;
int sum=0;
node p1,p2;
p1.from=x;
p1.g=0;
p1.f=p1.g+dis[p1.from];
q.push(p1);
while(!q.empty())
{
p1=q.top();
q.pop();
if(p1.from==y)
sum++;
if(sum==k)
return p1.g;
for(int i=head1[p1.from];i!=-1;i=s1[i].next)
{
p2.from=s1[i].to;
p2.g=p1.g+s1[i].val;
p2.f=p2.g+dis[p2.from];
q.push(p2);
}
}
return -1;
}
int main(void)
{
int i,j,k;
int x,y,z;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i=1;i<=n;i++)
{
dis[i]=maxn;
}
l=0;
memset(head1,-1,sizeof(head1));
memset(head2,-1,sizeof(head2));
for(i=1;i<=m;i++)
{
scanf("%d%d%d",&x,&y,&k);
add(x,y,k);
}
scanf("%d%d%d",&x,&y,&k);
spfa(y);
z=make(x,y,k);
printf("%d\n",z);
}
return 0;
}