洛谷P8794题解

本题主要用到了二分与Floyd,由于n的范围较小,因此使用Floyd不会超时。

本题的核心代码如下

for (int i = 1; i <= n; i++)//Floyd
		dis[i][i] = 0;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++)
			dis[i][j] = max(a[i][j] - c[i] - c[j], b[i][j]);
	for (int k = 1; k <= n; k++)
		for (int i = 1; i <= n; i++)
			for (int j = 1; j <= n; j++)
				dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j]);

之后由于Q过大,我们可以用到二分,代码如下

while (l <= r)//二分
	{
		mid = (l + r) / 2;
		if (check(mid)==1) ans = min(ans, mid), r = mid - 1;
		else l = mid + 1;
	}

之后本题就比较简单了,下面附上代码

#include <iostream>
using namespace std;
int n;
long long ans=1e10, dis[105][105], c[105], a[105][105], b[105][105], q;//数据开大一点,防止超范围
int check(int x)
{
	long long p = 0, m = x - n * (x / n);
	for (int i = 1; i <= n; i++)
	{
		c[i] = x / n;
		if (i <= m)
			c[i]++;
	}
	for (int i = 1; i <= n; i++)//Floyd
		dis[i][i] = 0;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++)
			dis[i][j] = max(a[i][j] - c[i] - c[j], b[i][j]);
	for (int k = 1; k <= n; k++)
		for (int i = 1; i <= n; i++)
			for (int j = 1; j <= n; j++)
				dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j]);
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++)
		{
			p += dis[i][j];
			if (p > q)//防止数据爆掉
			{
				return 0;
			}
		}
	if (p <= q) return 1;
	else return 0;
}
int main()
{
	cin >> n >> q;
	for (int i = 1; i <= n; i++)//存图
	{
		for (int j = 1; j <= n; j++)
			cin >> a[i][j];
	}
	for (int i = 1; i <= n; i++)
	{
		for (int j = 1; j <= n; j++)
			cin >> b[i][j];
	}
	long long l = 0, r = 1e9, mid;
	while (l <= r)//二分
	{
		mid = (l + r) / 2;
		if (check(mid)==1) ans = min(ans, mid), r = mid - 1;
		else l = mid + 1;
	}
	if (ans == 1e10) cout << -1;
	else cout << ans;;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值