poj2449---BFS+Astar

寻找第k短路。看到这道题时,很快就想到了思路,但就是实现不了。看了discuss,可以先用dijkstra求出最短路作为估价函数,在astar来实现求出第k短路,而astar最惯常做法是用优先队列保存节点。

用TPoint来保存astar里的节点,其中to是指向的位置,dis代表当前节点中已经过的距离,all是到目标的总距离。

#include<queue>
#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define maxn 1005
#define inf 1<<30
int sum1[maxn],sum2[maxn];
int dis[maxn],cnt[maxn];
bool vis[maxn];
int tot1,tot2,n,m,t;
int st,en,kth;
struct TNode
{
	int to,next,cost;
	bool operator<(const TNode &temp) const
	{
		return cost>temp.cost;
	}
};
struct TPoint
{
	int to,dis,all;
	bool operator<(const TPoint &temp) const
	{
		return all>temp.all;
	}
};
vector<TNode>ans1,ans2;
priority_queue<TNode>qu;
priority_queue<TPoint>ans;
void addedge(int u,int v,int w,bool flag)
{
	TNode tmp;
	tmp.to=u,tmp.cost=w;
	if(flag)
	{
		tmp.next=sum1[v],sum1[v]=tot1++;
		ans1.push_back(tmp);
	}
	else
	{
		tmp.next=sum2[v],sum2[v]=tot2++;
		ans2.push_back(tmp);
	}
}
void dijkstra()
{
	int k;
	fill(dis,dis+n+1,inf);
	memset(vis,0,sizeof(vis));
	while(!qu.empty()) qu.pop();
	TNode tmp1,tmp2;
	tmp1.to=en,tmp1.cost=0;
	qu.push(tmp1);
	dis[en]=0;
	while(!qu.empty())
	{
		tmp1=qu.top(),qu.pop();
		if(vis[tmp1.to]) continue;
		vis[tmp1.to]=1;
		for(k=sum1[tmp1.to];k!=-1;k=ans1[k].next)
		{
		    if(dis[ans1[k].to]>dis[tmp1.to]+ans1[k].cost)
		    {
		        dis[ans1[k].to]=dis[tmp1.to]+ans1[k].cost;
		        tmp2.to=ans1[k].to;
		        tmp2.cost=dis[tmp2.to];
		        qu.push(tmp2);
		    }
		}
	}
}
int astar()
{
    int i,j,k;
    TPoint tmp1,tmp2;
    while(!ans.empty()) ans.pop();
    memset(cnt,0,sizeof(cnt));
    tmp1.to=st,tmp1.dis=0,tmp1.all=dis[st];
    if(tmp1.all==inf) return -1;
    ans.push(tmp1);
    while(!ans.empty())
    {
        tmp1=ans.top(),ans.pop();
        cnt[tmp1.to]++;
        if(cnt[en]==kth) return tmp1.all;
        if(cnt[tmp1.to]>kth) continue;
        for(k=sum2[tmp1.to];k!=-1;k=ans2[k].next)
        {
            tmp2.to=ans2[k].to;
            tmp2.dis=tmp1.dis+ans2[k].cost;
            tmp2.all=tmp2.dis+dis[tmp2.to];
            ans.push(tmp2);
        }
    }
    return -1;
}
int main()
{
	int i,u,v,w;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		tot1=tot2=0;
		memset(sum1,-1,sizeof(sum1));
		memset(sum2,-1,sizeof(sum2));
		ans1.clear();
		ans2.clear();
		for(i=0;i<m;i++)
		{
			scanf("%d%d%d",&u,&v,&w);
			addedge(u,v,w,1);
			addedge(v,u,w,0);
		}
		scanf("%d%d%d",&st,&en,&kth);
		dijkstra();
		if(st==en) kth++;
		printf("%d\n",astar());
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值