跳到正文

题解

题解 CF2207C Where's My Water?

JuRuoOIer约 5 分钟
原文

这是 2026年3月13日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2026年3月13日
更新
2026年7月12日
篇幅
约 5 分钟
获赞
1
题目
CF2207C

版本

  1. v2当前
  2. v1

题解 CF2207C Where’s My Water?

其他题(几天后完工)

自评:橙~黄(本题)不会评,应该是紫(Bonus)。

单调栈都不会写了还有救吗。

题意

给定一个 nn 列 hh 行的网格,第 ii 列底部是高 aia_i 的泥土,其余部分是水。你需要选择不超过 22 个位置安装抽水机,水会往低处流,求最多抽到多少水。

数据范围:多测,t≤103,h≤109,∑n≤2000t\le 10^3,h\le 10^9,\sum n\le 2000。

Bonus(By 我自己):∑n≤5×105\sum n\le 5\times 10^5。

做法

首先大胆猜想一定会选到最大的,这个可以证明,大体思路是考虑选了两个不是最大的 x,yx,y 然后拿最大的换,这玩意证了一节课我是不是没救了。实现直接单调栈,当然 nn 就两千暴力也行。

然后发现最大的可能有多个,这时选第一个或者最后一个一定是不劣的,证明随便讨论一下,或者直接感性理解就是隔的越远公共部分肯定越小。

然后再在剩下的里面找最大的,此时需要考虑每个位置被抽走的部分,而如果上单调栈那这部分并不能平凡维护,所以只好暴力,于是单组总复杂度 O(n2)O(n^2)。

当然如果不怕麻烦上数据结构就好说了,线段树维护一下各个位置被抽走的部分,然后整个过程就是区间 chkmin 区间求和,也是正着一遍反着一遍就行,吉司机线段树板子题,总复杂度降到 O(nlog⁡n)O(n\log n),也就是我说的 Bonus。

注意用单调栈的话别把当前位置的贡献算两次了。

代码的话由于一开始想错了以为找第二个点也能线性(如果您真的会请务必教教我),所以找第一个点写的单调栈,找第二个点写的暴力,凑合看看吧。

C++
//Please ignore those headfiles.I write them just because
//DEV-C++ won't support completion if i use <bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<cmath>
#include<cctype>
#include<string>
#include<algorithm>
#include<vector>
#include<map>
#include<unordered_map>
#include<set>
#include<stack>
#include<queue>
#define ll long long
#define ull unsigned long long
#define lf double
#define ld long double
#define LL __int128
#define ui unsigned int
using namespace std;
ll T,n,h,a[2010],s[2010],ans[2010],del[2010],top;
int main(){
	ios::sync_with_stdio(0);
	cin>>T;
	while(T--){
		cin>>n>>h;
		for(int i=0;i<n;i++){
			cin>>a[i];
			a[i]=h-a[i];
		}
		ll cnt=0,mxp=n-1;
		s[0]=-1;top=1;
		for(int i=0;i<n;i++){
			while(top>1&&a[i]<=a[s[top-1]]){
				cnt-=(s[top-1]-s[top-2])*a[s[top-1]];
				top--;
			}
			cnt+=(i-s[top-1])*a[i];
			s[top++]=i;
			ans[i]=cnt;
		}
		cnt=0;
		s[0]=n;top=1;
		for(int i=n-1;~i;i--){
			while(top>1&&a[i]<=a[s[top-1]]){
				cnt-=(s[top-2]-s[top-1])*a[s[top-1]];
				top--;
			}
			cnt+=(s[top-1]-i)*a[i];
			s[top++]=i;
			ans[i]+=cnt-a[i];
			if(ans[i]>=ans[mxp]){
				mxp=i;
			}
		}
		cnt=a[mxp];
		for(int i=mxp;~i;i--){
			cnt=min(cnt,a[i]);
			del[i]=cnt;
		}
		cnt=a[mxp];
		for(int i=mxp;i<n;i++){
			cnt=min(cnt,a[i]);
			del[i]=cnt;
		}
		ll mx=0;
		for(int i=0;i<n;i++){
			ll tot=0;
			cnt=a[i];
			for(int j=i;~j;j--){
				cnt=min(cnt,a[j]);
				tot+=cnt-min(cnt,del[j]);
			}
			cnt=a[i];
			for(int j=i+1;j<n;j++){
				cnt=min(cnt,a[j]);
				tot+=cnt-min(cnt,del[j]);
			}
			if(tot>mx){
				mx=tot;
			}
		}
		cout<<ans[mxp]+mx<<endl;
	}
	return 0;
}