codeforces #629 F - Make k Equal

codeforces #629 F - Make k Equal

  • 题意:给n个数,你只能执行2个操作:选择一个最大值-1,选择一个最小值+1。问通过最少多少次操作,才能让数组有大于等于k个相同的数。

  • 题解:

    • 先设最后k个值为x。 这道题最关键的是发现x只能是数组中出现的数,这样o(n)扫描这个数组,计算每次让a[i]作为x时的最值即可。

    • 这个最值计算如下:

      \[(1)\ \ \ \ i*a[i] - \sum_{j=1}^{i}a[j] - (i - k) \ \ \ \ \ \ \ \ i>k \]

      \[(2) \ \ \ \ \ \sum_{j=i}^{n}a[j]-(n-i+1)*a[i]-(n-i+1-k) \ \ \ \ \ i+k \le n + 1 \]

      \[(3) \ \ \ \ \ i*a[i] - \sum_{j=1}^{i}a[j] + \sum_{j=i}^{n}a[j]-(n-i+1)*a[i] - (n - k) \]

    • 所以只要维护前缀和即可。

  • 代码:

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<cmath>
    #include<map>
    #include<queue>
    #include<vector>
    using namespace std;
    typedef long long ll;
    const int N = 2e5 + 105;
    const int mod = 1e9 + 7;
    const double Pi = 3.1415926;
    const ll INF = 1e16;
    
    int n, m, t, k, first_mid;
    ll res;
    ll a[N], sum[N], num[N];
    map<ll, ll>mp;
    int flag = 0;
    
    int main()
    {
    	int cnt = 0;
    	scanf("%d%d",&n,&k);
    	for(int i = 1; i <= n; ++ i) scanf("%lld",&a[i]);
    	sort(a + 1, a + n + 1);
    	for(int i = 1; i <= n; ++ i){
    		sum[i] = sum[i - 1] + a[i];
    		if(!mp[a[i]]) mp[a[i]] = ++ cnt;
    		num[mp[a[i]]] ++;
    		if(num[mp[a[i]]] >= k) flag = 1;
    	}
    	if(flag){
    		printf("0\n");
    		return 0;
    	}
    	
    	res = INF;
    	for(int i = 1; i <= n; ++ i){
    		ll A = i * a[i] - sum[i], B = sum[n] - sum[i - 1] - (n - i + 1) * a[i];
    		if(i >= k) res = min(res, A - (i - k));
    		if(i + k <= n + 1) res = min(res, B - (n - i + 1 - k));
    		res = min(res, A + B - (n - k));
    	}
    	printf("%lld\n",res);
    	return 0;
    }
    
    

猜你喜欢

转载自www.cnblogs.com/A-sc/p/12732801.html