| Time Limit: 4000MS | Memory Limit: 65536K | |
| Total Submissions: 21084 | Accepted: 5740 |
Description
Input
Output
Sample Input
2 2 1 2 5 2 1 4 1 2 2
Sample Output
14
Source
#include<stdio.h>
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
#define inf 99999999
#define N 1100
typedef struct nnn
{
int F,G,s;
friend bool operator<(nnn a,nnn b)
{
return a.F>b.F;
}
}PATH;
typedef struct nn
{
int v,w;
}node;
vector<node>map[N],tmap[N];
int H[N];
void findH(int s)
{
queue<int>q;
int inq[N]={0};
q.push(s); inq[s]=1; H[s]=0;
while(!q.empty())
{
s=q.front(); q.pop(); inq[s]=0;
int m=tmap[s].size();
for(int i=0;i<m;i++)
{
int j=tmap[s][i].v;
if(H[j]>tmap[s][i].w+H[s])
{
H[j]=tmap[s][i].w+H[s];
if(!inq[j])
inq[j]=1,q.push(j);
}
}
}
}
int Astar(int st,int end,int K)
{
priority_queue<PATH>q;
PATH p,tp;
int k[N]={0};
findH(end);
if(H[st]==inf)return -1;
p.s=st; p.G=0; p.F=H[st];
q.push(p);
while(!q.empty())
{
p=q.top(); q.pop();
k[p.s]++;
if(k[p.s]>K)continue;//每个点最多走K次,超过K条路不必走
if(p.s==end&&k[end]==K) return p.F;
int m=map[p.s].size();
for(int i=0;i<m;i++)
{
int j=map[p.s][i].v;
if(H[j]!=inf)//表明当前点不能通向终点,就不用加入队列
{
tp.G=p.G+map[p.s][i].w;
tp.F=H[j]+tp.G;
tp.s=j;
q.push(tp);
}
}
}
return -1;
}
int main()
{
int n,m,S,T,K,a,b,t;
node p;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
map[i].clear(); tmap[i].clear(); H[i]=inf;
}
while(m--)
{
scanf("%d%d%d",&a,&b,&t);
p.v=b; p.w=t; map[a].push_back(p);
p.v=a; tmap[b].push_back(p);//反建一个地图求H
}
scanf("%d%d%d",&S,&T,&K);
if(S==T)K++;
printf("%d\n",Astar(S,T,K));
}
POJ2449Remmarguts' Date(A*算法求第K小路),布布扣,bubuko.com
POJ2449Remmarguts' Date(A*算法求第K小路)
原文地址:http://blog.csdn.net/u010372095/article/details/38638323