A* 40分求调
查看原帖
A* 40分求调
1285691
yinbe2楼主2024/10/11 19:42
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
using namespace std;
int n,m,k,d[1005],cnt=1,id=1,in_cnt[1005];
bool vis[1005];
struct road
{
	int v,w;
};
vector<road>r[1005];
vector<road>r_fan[1005];
struct node
{
	int x,dist;
	const bool operator>(const node &o)const
	{
		return dist>o.dist;
	}
};
priority_queue<node,vector<node>,greater<node>>pq;
struct node2
{
	int x,dist;
	const bool operator>(const node2 &o)const
	{
		return dist+d[x]>o.dist+d[o.x];
	}
};
priority_queue<node2,vector<node2>,greater<node2>>pq2;
int main()
{
//	freopen("test.in","r",stdin);
//	freopen("test.out","w",stdout); 
	memset(d,0x3f,sizeof(d));
	scanf("%d%d%d",&n,&m,&k);
	for(int i=1;i<=m;i++)
	{
		int x,y,z;
		scanf("%d%d%d",&x,&y,&z);
		r_fan[y].push_back({x,z});
		r[x].push_back({y,z});
	}
	pq.push({1,0});
	d[1]=0;
	while(!pq.empty()&&cnt<=n)
	{
		node a=pq.top();
		pq.pop();
		if(vis[a.x])
		{
			continue;
		}
		vis[a.x]=true;
		for(road ro:r_fan[a.x])
		{
			if(d[ro.v]>d[a.x]+ro.w)
			{
				d[ro.v]=d[a.x]+ro.w;
				pq.push({ro.v,d[ro.v]});
			}
		}
		cnt++;
	}
	pq2.push({n,0});
	while(!pq2.empty())
	{
		node2 a=pq2.top();
		pq2.pop();
		if(a.x==1&&id<=k)
		{
			printf("%d\n",a.dist);
			id++;
			if(id>k)
			{
				return 0;
			}
		}
		for(road ro:r[a.x])
		{
			if(in_cnt[ro.v]<k)
			{
				in_cnt[ro.v]++;
				pq2.push({ro.v,a.dist+ro.w});
			}
		}
	}
	if(id<=k)
	{
		for(int i=id;i<=k;i++)
		{
			printf("-1\n");
		}
	}
	return 0;
}
2024/10/11 19:42
加载中...