P9587 题解(2023 激励计划评分 10)
RainRecall · · 题解
P9587 题解
怎么感觉我跟正解做的不是很一样。
前置知识
- 数学
题目解法
首先发现一件事,
然后根据这个,我们分情况来讨论。
假设我们每次遍历到一个值
-
如果
f(i)\le k \le g(i) ,说明已经满足条件,输出0 。 -
如果
g(i)\le k ,说明当前的a_i 太大了,但是此时把a_i 往上调是没用的,这样只会使g(i) 越来越小。所以设q=k-g(i) ,应该找到序列中比a_i 小的数中,前q 大的,把它们全都变成a_i 。若序列中比a_i 小的数中,前q 大的数的和为x ,则答案为qa_i-x 。 -
如果
f(i)\ge k ,说明当前的a_i 太小了,但此时改其它的数只会使f(i) 更大,所以只能改a_i 本身。容易发现把a_i 改到序列中第k 大值就可以满足条件。设第k 大值为p ,答案即为p-a_i 。
然后发现这个操作是
AC 代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#define int long long
using namespace std;
int c,n,k,a[5000005],b[5000005],ff[5000005];
int read(){
int f=1,x=0;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 f*x;
}
signed main(){
cin>>c>>n>>k;
for(int i=1;i<=n;++i)a[i]=read(),b[i]=a[i];
sort(b+1,b+n+1);
int qwq=b[n-k+1];//第 k 大值
for(int i=1;i<=n;++i)ff[i]=ff[i-1]+b[i];
for(int i=1;i<=n;++i){
int f=n-(upper_bound(b+1,b+n+1,a[i])-b)+2,g=n-(lower_bound(b+1,b+n+1,a[i])-b)+1;//f(i) 和 g(i)
if(f<=k&&k<=g)puts("0");
else if(g<k){
int ovo=lower_bound(b+1,b+n+1,a[i])-b;//a_i 在序列中的位置
printf("%lld\n",(k-g)*a[i]-(ff[ovo-1]-ff[ovo-1-(k-g)]));
}
else{
printf("%lld\n",qwq-a[i]);
}
}
return 0;
}