CF1197D Yet Another Subarray Problem(思维+前缀和)

思路:

先考虑暴力的做法,(O(n^2))枚举所有的区间,计算后取最大值。
考虑怎么优化一下,可以发现,如果当前的左端点为(l),那么将(a_l,a_{l+m},a_{l+2m})的值全部减去(k),那么当求和时选到这些数的时候(frac{r-l+1}{m})就会加一,也就满足了所求式子的后半段。由于(m)很小,我们可以直接枚举(0<=x<=m),每次都用(x)作为区间的分割点。维护一个前缀(sum)和跟前缀和的后缀最大值(las),对于枚举到的每一个左端点(i),(las[i]-sum[i-1])就是答案。

代码:

// Problem: CF1197D Yet Another Subarray Problem
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/CF1197D
// Memory Limit: 250 MB
// Time Limit: 2000 ms
// Author:Cutele
// 
// Powered by CP Editor (https://cpeditor.org)

#pragma GCC optimize(2)
#pragma GCC optimize(3,"Ofast","inline")
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>PLL;
typedef pair<int, int>PII;
typedef pair<double, double>PDD;
#define I_int ll
inline ll read(){ll x = 0, f = 1;char ch = getchar();while(ch < '0' || ch > '9'){if(ch == '-')f = -1;ch = getchar();}while(ch >= '0' && ch <= '9'){x = x * 10 + ch - '0';ch = getchar();}return x * f;}

inline void write(ll x){if (x < 0) x = ~x + 1, putchar('-');if (x > 9) write(x / 10);putchar(x % 10 + '0');}

#define read read()
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define repp(i,a,b) for(int i=(a);i<(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define perr(i,a,b) for(int i=(a);i>(b);i--)

ll ksm(ll a, ll b,ll mod){ll res = 1;while(b){if(b&1)res=res*a%mod;a=a*a%mod;b>>=1;}return res;}

const int maxn=3e5+7;

ll n,m,k,a[maxn],sum[maxn],las[maxn];

ll dfs(int x){
	rep(i,1,n){
		sum[i]=sum[i-1]+a[i];
		if(i % m == x) sum[i]-=k;
	}
	per(i,n,1) las[i]=max(las[i+1],sum[i]);
	ll ans=0;
	for(int i=x;i<=n;i+=m){
		if(!i) continue;
		ans=max(ans,las[i]-sum[i-1]);
	}
	return ans; 
}

int main(){
	
	n=read,m=read,k=read;
	rep(i,1,n) a[i]=read;
	las[n+1]=-1e18;
	ll ans=0;
	repp(i,0,m) ans=max(ans,dfs(i)); 
	write(ans);
	
	
	
	
	return 0;
}
原文地址:https://www.cnblogs.com/OvOq/p/15112750.html