题目链接
初始化p=1,r=l,求出[l,r+p]这一段区间的“校验值”,若“校验值”≤t,则r+=p,p*=2,否则p/=2,直到p等于零
每次排序时只对新增序列排序,然后合并新旧两段。
代码调试很久不过,去参考了大佬博客,讲解很详细
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
#define _rep(i,a,b) for(int i=(a);i<=(b);i++)
const int N=5e5+10;
int T;
int n,m;
ll t;
ll s[N];
ll a[N],b[N];//忘了ab也要long long
inline bool calc(int l,int mid,int r)
{
int len=r-l+1,p=l;
ll sum=0;
_rep(i,mid,r)a[i]=s[i];
sort(a+mid,a+r+1);
if(l==mid)_rep(i,l,r)b[i]=a[i];
else
{
int i=l,j=mid;
while(i<mid&&j<=r)
if(a[i]<=a[j])b[p++]=a[i++];
else b[p++]=a[j++];
while(i<mid)b[p++]=a[i++];
while(j<=r)b[p++]=a[j++];
}
_rep(i,l,min(l+len/2-1,l+m-1))
sum+=(b[i]-b[r-i+l])*(b[i]-b[r-i+l]);
if(sum<=t)
{
_rep(i,l,r)a[i]=b[i];
return true;
}
return false;
}
int main()
{
//freopen("in.txt","r",stdin);
scanf("%d",&T);
while(T--)
{
int l,r,p,ans=0;l=r=p=1;
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
scanf("%d%d%lld",&n,&m,&t);
_rep(i,1,n)scanf("%lld",&s[i]);
a[1]=s[1];
while(r<n)
{
if(!p)
{
ans++;
p=1;
l=++r;
a[l]=s[l];
continue;
}
else
{
if(r+p<=n&&calc(l,r+1,r+p))
{
r+=p;p*=2;
if(r==n)break;
}
else p/=2;
}
}
if(r==n)ans++;
printf("%d\n",ans);
}
return 0;
}