【图论】【A*搜索】[POJ2449]Remmarguts' Date
题目
本题实质是求第k短的路径;
SPFA+A*
进行启发式搜索直至访问终点k次,
估值函数:当前已经走的距离+当前点到终点的最短路
注意:当s==t时,要特判
#include<cstdio>
#include<queue>
#include<cstring>
#include<cstdlib>
using namespace std;
#define MAXN 1000
#define MAXM 100000
queue<int>q;
struct node2{
int pos,d,f;
bool operator < (const node2 &x) const{
return f>x.f;
}
};
priority_queue<node2>pq;
int n,m,dist[MAXN+10],s,t,k;
bool vis[MAXN+10];
struct node{
int u,v,wt;
node *next;
}edge[MAXM*2+10],*adj[MAXN+10],*adj2[MAXN+10],*ecnt=&edge[0];
void Read(int &x){
char c;
while((c=getchar())&&c!=EOF)
if(c>='0'&&c<='9'){
x=c-'0';
while((c=getchar())&&c>='0'&&c<='9')
x=x*10+c-'0';
ungetc(c,stdin);
return;
}
}
void addedge(int u,int v,int wt){
node *p=++ecnt;
p->v=v;
p->wt=wt;
p->next=adj[u];
adj[u]=p;
}
void addedge2(int u,int v,int wt){
node *p=++ecnt;
p->v=v;
p->wt=wt;
p->next=adj2[u];
adj2[u]=p;
}
void read(){
Read(n),Read(m);
int i,u,v,wt;
for(i=1;i<=m;i++){
Read(u),Read(v),Read(wt);
addedge(u,v,wt);
addedge2(v,u,wt);
}
Read(s),Read(t),Read(k);
if(s==t)
k++;
}
void spfa(int s){
q.push(s);
dist[s]=0;
vis[s]=1;
int u,v,wt;
while(!q.empty()){
u=q.front();
q.pop();
vis[u]=0;
for(node *p=adj2[u];p;p=p->next){
v=p->v,wt=p->wt;
if(dist[v]>dist[u]+wt){
dist[v]=dist[u]+wt;
if(!vis[v]){
q.push(v);
vis[v]=1;
}
}
}
}
}
void Astar(){
node2 u,v;
int cnt=0;
u.pos=s,u.d=0,u.f=dist[s];
pq.push(u);
while(!pq.empty()){
u=pq.top();
if(u.pos==t)
cnt++;
if(cnt==k){
printf("%d",u.d);
exit(0);
}
pq.pop();
for(node *p=adj[u.pos];p;p=p->next){
v.pos=p->v;
v.d=p->wt+u.d;
v.f=v.d+dist[p->v];
pq.push(v);
}
}
}
int main()
{
memset(dist,0x7f,sizeof dist);
read();
spfa(t);
Astar();
printf("-1");
}