Equalize the Array(前缀和)
题目描述:
Polycarp was gifted an array aa of length nn . Polycarp considers an array beautiful if there exists a number CC , such that each number in the array occurs either zero or CC times. Polycarp wants to remove some elements from the array aa to make it beautiful.
For example, if n=6n=6 and a = [1, 3, 2, 1, 4, 2]a=[1,3,2,1,4,2] , then the following options are possible to make the array aa array beautiful:
- Polycarp removes elements at positions 22 and 55 , array aa becomes equal to [1, 2, 1, 2][1,2,1,2] ;
- Polycarp removes elements at positions 11 and 66 , array aa becomes equal to [3, 2, 1, 4][3,2,1,4] ;
- Polycarp removes elements at positions 1, 21,2 and 66 , array aa becomes equal to [2, 1, 4][2,1,4] ;
Help Polycarp determine the minimum number of elements to remove from the array aa to make it beautiful.
Input:
follow.
The first line of each test case consists of one integer nn ( 1 \le n \le 2 \cdot 10^51≤n≤2⋅105 ) — the length of the array aa .
The second line of each test case contains nn integers a_1, a_2, \ldots, a_na1,a2,…,an ( 1 \le a_i \le 10^91≤ai≤109 ) — array aa .
It is guaranteed that the sum of nn over all test cases does not exceed 2 \cdot 10^52⋅105 .
Output:
For each test case, output one integer — the minimum number of elements that Polycarp has to remove from the array aa to make it beautiful.
Example:
input:
3
6
1 3 2 1 4 2
4
100 100 4 100
8
1 2 3 3 3 2 6 6
output:
2
1
2
题意:有 t 组数据。每组数据给出一个长度为 n 的序列 a_1,a_2,...,a_n,问最少需要删除多少个元素,才可以使得剩余的序列中,所有不同数字出现的次数均相等。
思路:每个数都出现刚好要么 0 次要么 c次。考虑枚举这个 c。首先处理出每个数的出现次数然后把这些出现次数从小到大排序。假定我们在考虑第 i个出现次数 b_i,如果所有的数的出现次数都要变为 b_i,
说明多了的次数要减掉,比 b_i 少的出现次数要全部删掉。sum_i−1 为比 b_i 出现少的,要全部删掉,s_n - s_i 表示所有大于 b_i 的 b_k之和,减掉不需要删除的 (cnt-i)*b_i 即可。
#include<bits/stdc++.h> #include<iostream> #include<cctype> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<queue> #include<stack> using namespace std; typedef unsigned long long ull; typedef long long ll; typedef pair<ll,ll> pi; #define IOS std::ios::sync_with_stdio(false) #define ls p<<1 #define rs p<<1|1 #define mod 1000000000 + 7 #define PI acos(-1.0) #define INF 1e18 #define N 200000 + 5 /*********************Code*********************/ int t,n,a[N],ans,cnt,sum[N],b[N]; map<int,int>mp; int main(void){ IOS; cin>>t; while(t--){ cin>>n; mp.clear(); ans = 1e9,cnt = 0; for(int i = 0;i < n;i++){ cin>>a[i]; mp[a[i]]++; } for(auto i: mp){ b[++cnt] = i.second; } sort(b,b+cnt+1); for(int i =1;i <=cnt;i++ ) sum[i] =sum[i-1]+b[i]; for(int i = 1;i <=cnt;i++){ ans = min(ans,sum[i-1]+sum[cnt]-sum[i]-(cnt-i)*b[i]); } cout<<ans<<endl; } return 0; }