第K最短路程序

第K最短路程序

# include <stdio.h>
# include <string.h>
# include <stdlib.h>
struct edge{
int v1,v2,v;
}e[2000];
struct kk{
int v,len;
}Q[500000];
int top[200];
int heap[200][20];
int F[200];
int cmp(const void *a,const void *b)
{
edge a1=*(edge *)a;
edge b1=*(edge *)b;
return a1.v1-b1.v1;
}
void Insert(int num,int x)
{
int p=top[num]++;
while(p&&heap[num][(p-1)/2]<x){
  heap[num][p]=heap[num][(p-1)/2];
  p=(p-1)/2;
}
heap[num][p]=x;        
}
int pop(int num)
{
int ans=heap[num][0];
int t=heap[num][--top[num]];
int p=0;
int s=2*p+1;
while(s<top[num]){
  if(s+1<top[num]&&heap[num][s+1]>heap[num][s]) s++;
  if(heap[num][s]<=t) break;
  heap[num][p]=heap[num][s];
  p=s;
  s=2*p+1;
}
heap[num][p]=t;
return ans;
}
int main()
{
int n,m;
int i,s,t,k;
while(scanf("%d%d",&n,&m)!=EOF){
  if(n==0&&m==0) break;
  scanf("%d%d%d",&s,&t,&k);
  s--;t--;
  for(i=0;i<m;i++) {
   scanf("%d%d%d",&e[i].v1,&e[i].v2,&e[i].v);
   e[i].v1--;e[i].v2--;
  }
  qsort((void *)e,m,sizeof(e[0]),cmp);
  memset(F,-1,sizeof(F));
  F[e[0].v1]=0;
  for(i=1;i<m;i++) if(e[i].v1!=e[i-1].v1) F[e[i].v1]=i;
  memset(top,0,sizeof(top));
  Q[0].v=s;
  Q[0].len=0;
  int qt=0;
  int qh=1;
  kk x,tmp;
  for(;qt<qh;qt++){
   x = Q[qt];
   for(i=F[x.v];i!=-1&&i<m&&e[i].v1==x.v;i++) {
    tmp.v = e[i].v2;
    tmp.len=x.len+e[i].v;
    if(top[tmp.v]<k) {
     Insert(tmp.v,tmp.len);
     Q[qh++]=tmp;
    }
    else if(tmp.len<heap[tmp.v][0]) {
     pop(tmp.v);
     Insert(tmp.v,tmp.len);
     Q[qh++]=tmp;
    }
   }
  }
  if(top[t]<k) printf("-1/n");
  else printf("%d/n",heap[t][0]);        
}
return 0;
}

猜你喜欢

转载自blog.csdn.net/wflishh/article/details/2293106