POJ 2449 Remmarguts' Date

Remmarguts’ Date

题意

给定一个n个点,m条边的有向图
求s到t的第k短路

1.从S点出发
2.每次取出估值最小的点,把每条边拓展后放入堆中
3.当取出的点是T时K–
4.注意S==T的情况,K++

A*算法
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
const int M=1005;
typedef pair<int,int>P;
int n,m,S,T,K;
int asdf,head[M],rasdf,rhead[M];
struct edge {
    int to,nxt,cost;
} G[2*M*M],rG[2*M*M];
void add_edge(int a,int b,int c) {
    G[++asdf].to=b;
    G[asdf].nxt=head[a];
    G[asdf].cost=c;
    head[a]=asdf;
}
void radd_edge(int a,int b,int c) {
    rG[++rasdf].to=b;
    rG[rasdf].nxt=rhead[a];
    rG[rasdf].cost=c;
    rhead[a]=rasdf;
}
int dis[M];
void dj(int st){
    priority_queue<P,vector<P>,greater<P> >Q;
    memset(dis,63,sizeof(dis));
    Q.push(P(dis[st]=0,st));
    while(!Q.empty()){
        P p=Q.top();
        Q.pop();
        int x=p.second;
        if(p.first>dis[x])continue;
        for(int i=rhead[x];i;i=rG[i].nxt){
            int y=rG[i].to;
            if(dis[y]>dis[x]+rG[i].cost){
                dis[y]=dis[x]+rG[i].cost;
                Q.push(P(dis[y],y));
            }
        }
    }
} 
priority_queue<P,vector<P>,greater<P> >Q;
int main() {
    int a,b,c;
    scanf("%d %d",&n,&m);
    for(int i=1; i<=m; i++) {
        scanf("%d %d %d",&a,&b,&c);
        add_edge(a,b,c);
        radd_edge(b,a,c);
    }
    scanf("%d %d %d",&S,&T,&K);
    if(S==T)K++;
    dj(T);
    //for(int i=1;i<=n;i++)printf("dis[%d]=%d\n",i,dis[i]);
    Q.push(P(dis[S],S));
    int cnt=0;
    while(!Q.empty()){
        P p=Q.top();
        Q.pop();
        int x=p.second;
        if(x==T){
            cnt++;
            if(cnt==K){
                printf("%d\n",p.first);
                return 0;
            }
        }
        for(int i=head[x];i;i=G[i].nxt){
            int y=G[i].to;
            if(dis[y]>1e9)continue;
            Q.push(P(p.first-dis[x]+G[i].cost+dis[y],y));//dis[y]是估值函数,A*的核心
        }
    }
    printf("-1\n");
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值