本题主要用到了二分与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;
}