第k短路(A*算法)

AcWing 178. 第K短路

在这里插入图片描述

Code

int n, m, S, T, k;
vector<int> a[1003][1003], b[1003][1003];
int vis[1003], f[1004];

//估价函数f[x]:从T到x的最短路径的长度
void dfs()
{
	priority_queue<pii, vector<pii>, greater<pii> > q;
	mt(f, 0x3f); mt(vis, 0);
	f[T] = 0;
	q.push({ 0, T });

	while (sz(q))
	{
		int x = q.top().sd; q.pop();
		if (vis[x]) continue;
		vis[x] = 1;

		for (int y = 1; y <= n; y++)
			for (auto w : b[x][y])
				if (f[y] > f[x] + w)
					f[y] = f[x] + w,
					q.push({ f[y], y });
	}
}

#define piii pair<int, pair<int, int> >
int d[1003];
int A()
{
	priority_queue<piii, vector<piii>, greater<piii> > q;
	mt(vis, 0);
	q.push({ f[S], {0 , S} });

	while (sz(q))
	{
		int ans = q.top().sd.ft;//备份d[x]
		int x = q.top().sd.sd; 
		q.pop();
		if (vis[x] > k) continue;
		vis[x]++;

		if (vis[T] == k) { return ans; }//终点

		for (int y = 1; y <= n; y++)
			if (vis[y] < k)
				for (auto w : a[x][y])
					//此处 d[y] = d[x] + w, 是错误的。因为 可以从 x --> x, 
					//所以 d[x]会改变,需要用最初的d[x],也即ans
					d[y] = ans + w,
					q.push({ ans + f[y] + w, { ans + w, y} });
	}
	return -1;
}

int main()
{
	IOS;
	cin >> n >> m;
	for (int i = 1; i <= m; i++)
	{
		int x, y, z; cin >> x >> y >> z;
		a[x][y].push_back(z);//两点有多条边连接
		b[y][x].push_back(z);//也可以用链式向前星
	}
	cin >> S >> T >> k;

	if (!m)
	{
		cout << -1 << endl;
		return 0;
	}

	dfs();
	//每条最短路至少包含一条边,所以d[S --> S] = 0不算入最短路
	if (S == T) k++;
	cout << A() << endl;


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

to cling

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值