Acwing_340通信线路【最短路+二分】

题目链接:Acwing_340通信线路

思路分析:

  • 题意是叫我们可以把k个边权值变为0,之后选取一条路径,该路径的总权值和是该路径上的最大权值,求最短路径,这题先要处理一下把那些边变为0,最后再求最短路即可
  • 做法:我们二分一个X,X为满足从1点到N点至少有一条路径上权值大于X的边小于等于K,这样如果我们求这个X的最小值,就是答案了,那么对于每一次X都要求一次最短路,我们把大于X的权值的边权值置为1,小于等于的置为0,然后求一边最短路,即可求出最少要经过几条大于X的路径,判断是否小于等于k即可
  • 对于边权只有0/1的最短路问题,我们用双端队列bfs即可,道理和dijkstra一样,bfs过程中把是权值0的插入队头,1的插入队尾,这样就保证每一次取到的都是没有被选的边中的最小值,和dijkstra一样,所以该方法正确。

AC代码:

#include <cstring>
#include <iostream>
#include <algorithm>
#include <deque>

using namespace std;

const int N = 1010, M = 20010;

int n, m, k;
int h[N], e[M], w[M], ne[M], idx;
int dist[N];
deque<int> q;
bool st[N];

void add(int a, int b, int c)
{
	e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}

bool check(int bound)
{
	memset(dist, 0x3f, sizeof dist);
	memset(st, 0, sizeof st);

	q.push_back(1);
	dist[1] = 0;

	while (q.size())
	{
		int t = q.front();
		q.pop_front();

		if (st[t]) continue;
		st[t] = true;

		for (int i = h[t]; ~i; i = ne[i])
		{
			int j = e[i], x = w[i] > bound;
			if (dist[j] > dist[t] + x)
			{
				dist[j] = dist[t] + x;
				if (!x) q.push_front(j);
				else q.push_back(j);
			}
		}
	}

	return dist[n] <= k;

}

int main()
{
	cin >> n >> m >> k;
	memset(h, -1, sizeof h);
	while (m--)
	{
		int a, b, c;
		cin >> a >> b >> c;
		add(a, b, c), add(b, a, c);
	}

	int l = 0, r = 1e6 + 1;
	while (l < r)
	{
		int mid = l + r >> 1;
		if (check(mid)) r = mid;
		else l = mid + 1;
	}

	if (r == 1e6 + 1) cout << -1 << endl;
	else cout << r << endl;

	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值