Telephone Lines(最短路 + 二分)

Telephone Lines

这道题还可以用分层图的方法来做,但是蒟蒻还没有学。

下面采用的是二分答案的方法。由题知,路径中的 k 条电缆免费,那么我们希望所有电缆中第 1 ~ k 长的电缆免费,而只需支付第 k + 1 长的电缆费用,因此我们只需找到这条电缆的长度 ans,采用二分的方法,这里的 Mr 取值为 1e6 + 1。下面说一下 l, r 的取值:

l = 0 :由题意知,ans 是有可能取到 0 的。

r = 1e6 + 1 : 如果只取 r = 1e6 时,如果 ans 等于 1e6 或者 1 号点到 n 号点根本不连通,最终二分结束的时候都有 r == 1e6,无法区分这两种情况。但是取 r = 1e6 + 1 时,如果 1 号点到 n 号点不连通的时候,二分结束后 r == 1e6 + 1,就可以将两种情况分开了

int l = 0, r = Mr, mid;
while(l < r)
{
	mid = (l + r) / 2;
	if(check(mid)) r = mid;
	else l = mid + 1;
}

if(r == Mr) puts("-1");

else printf("%d\n", r);

我们在计算最短路的时候,将长度大于 ans 的路权记为 1,否则为 0,最后得到的 dist[n] 就是得到免费机会的路径条数

完整代码如下:(优先队列实现)(对于路权只为 0 或 1 的情况,也可以用双端队列实现)

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
#define N 1010
#define M 20010
#define Mr 1000001
using namespace std;

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


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

bool check(int bound) // 传入可能的答案(边界bound)
{
	memset(st, 0, sizeof st); // 因为要多次调用check函数,所以要初始化😭
	memset(dist, 0x3f, sizeof dist);
	dist[1] = 0;

	priority_queue<PII, vector<PII>, greater<PII> > heap;
	heap.push({0, 1});

	while(heap.size())
	{
		PII t = heap.top();
		heap.pop();

		int id = t.second, dis = t.first;

		if(st[id]) continue;

		st[id] = true;

		for (int i = h[id]; i; i = ne[i])
		{
			int j = e[i];
			int v = w[i] > bound; // 将长度大于bound的边权记为1,否则为0
			int tmp = dist[id] + v;
			if(dist[j] > tmp)
			{
				dist[j] = tmp;
				heap.push({tmp, j});
			}
		}
	}

	return dist[n] <= k;

}

int main()
{
	cin >> n >> m >> k;

	for (int i = 0; i < m; i ++)
	{
		int a, b, c;
		scanf("%d%d%d", &a, &b, &c);
		add(a, b, c), add(b, a, c);
	}

	int l = 0, r = Mr, mid;
	while(l < r)
	{
		mid = (l + r) / 2;
		if(check(mid)) r = mid;
		else l = mid + 1;
	}

	if(r == Mr) puts("-1");

	else printf("%d\n", r);


    return 0;
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Victayria

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

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

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

打赏作者

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

抵扣说明:

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

余额充值