题目链接
题目大意
给定一个整数 M,对于任意一个整数集合 S,定义“校验值”如下:
从集合 S 中取出 M 对数(即 2×M 个数,不能重复使用集合中的数,如果 S 中的整数不够 M 对,则取到不能取为止),使得“每对数的差的平方”之和最大,这个最大值就称为集合 S 的“校验值”。
现在给定一个长度为 N 的数列 A 以及一个整数 T。
我们要把 A 分成若干段,使得每一段的“校验值”都不超过 T。
求最少需要分成几段。
考察
倍增算法
倍增算法基础
思路
类似与倍增查找数
- 从当前区间开始扩展终点位置ed(区间右端点的下一个),当 e d + l e n < = n ed+len <= n ed+len<=n且 校验值 s < = T s<=T s<=T时就让 e d + = l e n ed+=len ed+=len且 l e n len len倍增( l e n ∗ 2 len*2 len∗2)否则就缩短 l e n len len。直到 [ s t , e d ) [st,ed) [st,ed)最大范围覆盖。
- 使 s t = e d st = ed st=ed切换到下一个区间。
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 500010;
typedef long long ll;
ll a[N],n,m,t,ans;
ll tr[N];
ll sq(ll x){
return x*x;
}
ll get(int l, int r){//获得校验值
int k = 0;
for(int i = l; i < r; i++)
tr[k++] = a[i];
sort(tr,tr+k);
ll sum = 0;
for(int i = 0; i < m && i < k; i++, k--)
sum += sq(tr[k-1]-tr[i]);
return sum;
}
int main(){
cin.tie(0)->sync_with_stdio(false);
cout.tie(0);
int T; cin>>T;
while(T--){
ans = 0;
cin>>n>>m>>t;
for(int i = 0; i < n; i++) cin>>a[i];
int st = 0, ed = 0;//ed表示最后一个的下一个位置
while(ed < n){
int len = 1;//扩展的长度
while(len){//当len == 0说明区间[st,ed)已经最大范围
if(ed+len <= n && get(st,ed+len) <= t){
ed += len;
len <<= 1;//倍增
} else {
len >>= 1; //缩短
}
}
st = ed;//切换下一个区间
ans++;
}
cout<<ans<<'\n';
}
return 0;
}