其他分享
首页 > 其他分享> > D1. Equalizing by Division (easy version)

D1. Equalizing by Division (easy version)

作者:互联网

The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any ai and divide it by 2 rounding down (in other words, in one move you can set ai:=⌊ai2⌋).
You can perform such an operation any (possibly, zero) number of times with any ai.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don’t forget that it is possible to have ai=0 after some operations, thus the answer always exists.

Input
The first line of the input contains two integers n and k (1≤k≤n≤50) — the number of elements in the array and the number of equal numbers required.
The second line of the input contains n integers a1,a2,…,an (1≤ai≤2⋅105), where ai is the i-th element of a.

Output
Print one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.

Examples
inputCopy
5 3
1 2 2 4 5
outputCopy
1
inputCopy
5 3
1 2 3 4 5
outputCopy
2
inputCopy
5 3
1 2 3 3 3
outputCopy
0

题意:要使得数组中元素出现k个相等的,可做操作,每个元素都可/2,直到出现k个相等的。
解法:把每个数都/2,分解出来,然后暴力遍历每一遍。

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int a[N];
int main()
{
  int n,k;
  scanf("%d %d",&n,&k);
  for(int i=0;i<n;i++) cin>>a[i];
  vector<int> v;
  for(int i=0;i<n;i++)
  {
    int x=a[i];
    while(x>0)
    {
      v.push_back(x);
      x/=2;
    }
  }
  int ans=1e9+10;
  for(auto res:v)
  {
    vector<int> cnt;
    for(int i=0;i<n;i++)
    {
      int x=a[i];
      int cur=0;
      while(x>res)
      {
        x/=2;
        cur++;
      }
      if(x==res) cnt.push_back(cur);
    }
    if(cnt.size()<k) continue;
    sort(cnt.begin(),cnt.end());
    ans=min(ans,accumulate(cnt.begin(),cnt.begin()+k,0));
  }
  printf("%d\n",ans);
}

标签:operations,Division,Equalizing,int,number,ai,version,array,outputCopy
来源: https://blog.csdn.net/qq_43690454/article/details/100173379