P3534 [POI2012] STU-Well

Description

https://www.luogu.com.cn/problem/P3534

Solution

考虑二分答案 $k$。然后先把 $a_i>a_{i-1}+k$ 和 $a_i>a_{i+1}+k$ 的给调整完,再枚举最后要变成 $0$ 的点。

对答案产生另外的影响的,就是从这个点 $i$ 划出两条斜率为 $k,-k$ 的直线的上面的点。

注意到枚举的点往右移动,产生影响的区间是不往左的。双指针指一下即可。复杂度 $O(n\log w)$。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include<bits/stdc++.h>
#define int long long
#define ull unsigned long long
#define maxn 1000005
#define put() putchar('\n')
#define Tp template<typename T>
#define Ts template<typename T,typename... Ar>
using namespace std;
Tp void read(T &x){
int f=1;x=0;char c=getchar();
while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();}
while (c>='0'&&c<='9') {x=x*10+c-'0';c=getchar();}
x*=f;
}
namespace Debug{
Tp void _debug(char* f,T t){cerr<<f<<'='<<t<<endl;}
Ts void _debug(char* f,T x,Ar... y){while(*f!=',') cerr<<*f++;cerr<<'='<<x<<",";_debug(f+1,y...);}
#define gdb(...) _debug((char*)#__VA_ARGS__,__VA_ARGS__)
}using namespace Debug;
#define fi first
#define se second
#define mk make_pair
const int mod=1e9+7;
int power(int x,int y=mod-2) {
int sum=1;
while (y) {
if (y&1) sum=sum*x%mod;
x=x*x%mod;y>>=1;
}
return sum;
}
int n,m,a[maxn],b[maxn],ANS,s[maxn];
int F(int x) {return x*(x+1)/2;}
bool check(int val) {
int i,l,r,sum=0,ans=1e18;
for (i=1;i<=n;i++) a[i]=b[i];
for (i=2;i<=n;i++) if (a[i]>a[i-1]+val) sum+=a[i]-(a[i-1]+val),a[i]=a[i-1]+val;
for (i=n-1;i>=1;i--) if (a[i]>a[i+1]+val) sum+=a[i]-(a[i+1]+val),a[i]=a[i+1]+val;
for (i=1;i<=n;i++) s[i]=s[i-1]+a[i];
l=1;r=1;int id=0;
while (r<n&&a[r+1]>(r)*val) r++;
ans=min(ans,s[r]-F(r-1)*val);
if (ans+sum<=m) id=1;

for (i=2;i<=n;i++) {
while (r<n&&a[r+1]>(r-i+1)*val) r++;
while (l<=n&&a[l]<(i-l)*val) l++;
int tmp=s[r]-s[l-1]-(F(r-i)+F(i-l))*val;
ans=min(ans,tmp);
if (tmp+sum<=m&&!id) id=i;
}
if (ans+sum<=m) ANS=id;
return ans+sum<=m;
}
signed main(void){
int i;
read(n);read(m);
for (i=1;i<=n;i++) read(a[i]),b[i]=a[i];
int l=-1,r=1e9,mid;
while (l+1<r) {
mid=l+r>>1;
if (check(mid)) r=mid;
else l=mid;
}
printf("%lld %lld\n",ANS,r);
return 0;
}
//i=begin && g++ $i.cpp -o $i -std=c++14 && ./$i