跳到正文

题解

P9457 魔法少女扶苏(Hard Version)题解

Shiozeu约 4 分钟
原文
文章信息与版本

文章信息

发布
2023年7月14日
收录
2026年10月1日
更新
2026年11月3日
篇幅
约 4 分钟

版本

  1. v1当前

原本只写了 div.4 的弱化版本,发现 Hard 版本只是改了数据范围。随便改改就过去了(逃)

我们假设一共释放 ansans 次魔法,不难发现只要 ansans 越大,符合条件的点就越多,于是这个问题具有单调性。题中要求的是最小的 ansans,于是考虑使用二分答案。最开始 ll 和 rr 的范围应该是 11 到最大的 ai,ja_{i,j},由于 0≤ai.j≤10110 \leq a_{i.j} \leq 10^{11},时间并不大。

接下来考虑怎么写 check 函数。

我们设第 ii 行上所有的点的和为 cntxicntx_i,第 jj 列上所有点的和为 cntyjcnty_j,不难得出 ai,ja_{i,j} 想要做出贡献,需要满足的条件为:

ai,j−ans≥cntxi+cntyj−(n+m)×ansa_{i,j} - ans \geq cntx_i + cnty_j - (n+m) \times ans

但我们需要统计出至少有 kk 个点满足条件,如果只是这样去一个一个 check 的话,时间依旧是 O(nm)\mathcal{O}(nm) 的,无法接受。

考虑把它们全部移到左边去,得:

ai,j−cntxi−cntyj+(n+m−1)×ans≥0a_{i,j} - cntx_i - cnty_j + (n+m-1) \times ans \geq 0

其中 ai,j−cntxi−cntyja_{i,j} - cntx_i - cnty_j 可以预处理出来。

因此我们不妨将所有的 ai,j−si,ja_{i,j}-s_{i,j} 从大到小排序,这样只要排序后的第 kk 个点满足条件,那么前面的 k−1k-1 个就一定满足条件(因为前面 k−1k-1 个点的权值大于或等于第 kk 个),这样每次 check 就是 O(1)\mathcal{O}(1) 的了。

  • 考虑预处理的复杂度。我们要计算出 cntxicntx_i,cntyjcnty_j,并给每个 ai,j−cntxi−cntyja_{i,j} - cntx_i - cnty_j 排序,这样的复杂度就是 O(nm+log⁡n+log⁡m)\mathcal{O}(nm + \log n + \log m) 的。

  • 考虑二分的复杂度。每次 check 是 O(1)\mathcal{O}(1) 的。设 aia_i 的最大值为 PP,则二分的复杂度为 O(log⁡P)\mathcal{O}(\log P)。

总时间复杂度 O(nm+log⁡n+log⁡m+log⁡P)\mathcal{O}(nm + \log n + \log m + \log P)。

温馨提示:记得开 long long。

C++
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 3e3 + 5;
const ll P = 1e11 + 5;

int n, m, k, tot;
ll cntx[maxn], cnty[maxn];

//快读 
ll read() {
	ll res = 0, flag = 1; char c = getchar();
	while(c < '0' || c > '9') { if(c == '-') flag = -1; c = getchar(); }
	while(c >= '0' && c <= '9') { res = res*10 + c - '0'; c = getchar(); }
	return res * flag; 
}

struct node {
	ll val; int x, y;
	bool operator < (const node& d) const {
		//从大到小排序 
		return val > d.val;
	}
} p[maxn*maxn];

bool check(ll mid) {
	if(p[k].val + 1ll* (n+m-1) * mid >= 0) return true;
	else return false;
}

int main() {
	scanf("%d %d %d", &n, &m, &k);
	for(int i = 1; i <= n; i++)
	for(int j = 1; j <= m; j++) {
		scanf("%lld", &p[++tot].val);
		//存到一个数组里,方便排序 
		p[tot].x = i, p[tot].y = j;
		cntx[i] += p[tot].val;
		cnty[j] += p[tot].val;
	}
	
	//求出a[i][j] - cntx[i] - cnty[j],并从大到小排序 
	for(int i = 1; i <= tot; i++)
		p[i].val -= cntx[p[i].x] + cnty[p[i].y];
	sort(p+1, p+1+tot);
	
	//二分 
	ll l = 0, r = P, ans = 0;
	while(l <= r) {
		ll mid = (l+r) >> 1;
		if(check(mid)) ans = mid, r = mid - 1;
		else l = mid + 1;
	}
	
	printf("%lld\n", ans);
	return 0;
}
原文
存档评论2 条抓取于