http://poj.org/problem?id=3255
第k短路
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<queue>
#include<string.h>
using namespace std;
const int N=5001;
const int M=200005;
const int MAX=0x5fffffff;
int head[N];
struct node
{
int j,k;
int next;
}side[M];
int dist[N];
bool in[N];
struct tt
{
int f,g;
int x;
bool operator <(const tt a) const
{
if(a.f==f)
return a.g<g;
return a.f<f;
}
};
void build(int x,int i)
{
side[i].next=head[x];
head[x]=i;
}
void spfa(int n)
{
queue<int>str;
memset(in,false,sizeof(false));
for(int i=1;i<=n;++i)
dist[i]=MAX;
dist[n]=0;
in[n]=true;
str.push(n);
while(!str.empty())
{
int x=str.front();
str.pop();
in[x]=false;
for(int t=head[x];t!=-1;t=side[t].next)
{
if(dist[side[t].j]>dist[x]+side[t].k)
{
dist[side[t].j]=dist[x]+side[t].k;
if(!in[side[t].j])
{
in[side[t].j]=true;
str.push(side[t].j);
}
}
}
}
}
int Astar(int n)
{
tt k1,k2;
priority_queue< tt >str;
k1.f=dist[1];
k1.g=0;
k1.x=1;
str.push(k1);
int ans=-1;
while(!str.empty())
{
k1=str.top();
str.pop();
int x=k1.x;
if(x==n)
{
if(ans==-1)
{
ans=k1.g;
}else
{//cout<<k1.g<<" "<<ans<<endl;
if(k1.g>ans)
return k1.g;
}
}
for(int t=head[x];t!=-1;t=side[t].next)
{
k2.x=side[t].j;
if(dist[k2.x]==MAX)
continue;
k2.g=k1.g+side[t].k;
k2.f=k2.g+dist[k2.x];
str.push(k2);
}
}
return ans;
}
int main()
{
//freopen("data.txt","r",stdin);
int n,m;
while(scanf("%d %d",&n,&m)!=EOF)
{
memset(head,-1,sizeof(head));
for(int i=0;i<m;++i)
{
int x,y,k;
scanf("%d %d %d",&x,&y,&k);
side[i].j=y;
side[i].k=k;
build(x,i);
side[i+m].j=x;
side[i+m].k=k;
build(y,i+m);
}
spfa(n);
printf("%d\n",Astar(n));
}
return 0;
}
浙公网安备 33010602011771号