题解:P14915 「QFOI R3」算法竞赛
数的顺序不影响结果,我们先把数组排序。
对于样例 1,我们依次往队伍中加入
对于样例 2,我们依次往队伍中加入
我们发现,我们想要加入
至于为什么每次都要
记录当前队伍的人数
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int n,k,d,a[N],tot,ans;
int main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin>>n>>k>>d;
for(int i=1;i<=n;i++)cin>>a[i];
sort(a+1,a+n+1);
for(int i=1;i<=n;i++){
if(tot==0)tot++;
else if(a[i]-a[i-1]<=d){
tot++;
if(tot==k)tot=0;
}
else{
int pre=a[i-1];
while(1){
pre+=d;
tot++;
ans++;
if(tot==k){
tot=0;
break;
}
if(a[i]-pre<=d)break;
}
if(tot){
tot++;
if(tot==k)tot=0;
}
else tot++;
}
}
if(tot!=k&&tot)ans+=k-tot;
cout<<ans;
return 0;
}
考虑优化:我们其实要找到一个最小的
代码如下,可供参考:
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e5+10;
int n,k,d,a[N],tot,ans;
signed main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin>>n>>k>>d;
for(int i=1;i<=n;i++)cin>>a[i];
sort(a+1,a+n+1);
for(int i=1;i<=n;i++){
if(tot==0)tot++;
else if(a[i]-a[i-1]<=d){
tot++;
if(tot==k)tot=0;
}
else{
if(d==0)ans+=k-tot,tot=0;
else{
int x=(a[i]-a[i-1]+d-1)/d;
x--;
if(tot+x>=k)ans+=k-tot,tot=0;
else{
tot+=x;
ans+=x;
}
}
tot++;
if(tot==k)tot=0;
}
}
if(tot!=k&&tot)ans+=k-tot;
cout<<ans;
return 0;
}