1490F - Equalize the Array - CodeForces Solution


binary search data structures greedy math sortings *1500

Please click on ads to support us..

Python Code:

import collections

t = int(input())
for _ in range(t):
    n = int(input())
    arr = list(map(int, input().split()))
    total = n
    min_removals = total
    previous = 0
    c = collections.Counter(collections.Counter(arr).values())
    current_count = sum(c.values())
    for k in sorted(c.keys()):
        current_cost = total - (current_count * k)
        min_removals = min(min_removals, current_cost)
        current_count -= c[k]
        previous += (c[k] * k)
    print(min_removals)

C++ Code:

#include<bits/stdc++.h>
using namespace std;
int main()
{
	int tc;
	cin>>tc;
	while(tc--)
	{
		int n,x;
		cin>>n;
		
		vector<int>v;
		map<int,int>freq,umap;
		
		for(int i=0;i<n;i++)
		{
			cin>>x;
			freq[x]++;
		}
		
		for(auto it:freq)
		{
		    int y=it.second;
			umap[y]++; 
			
			if(umap[y]==1)
			v.push_back(y);
		}
		
		sort(v.rbegin(),v.rend());

		vector<int>suffix(v.size());
		suffix[v.size()-1]=0;
		
		for(int i=v.size()-2;i>=0;i--)

		suffix[i]=suffix[i+1]+(v[i+1]*umap[v[i+1]]);

		int mini=suffix[0],carry=umap[v[0]],add=0;
		
		for(int i=1;i<v.size();i++)
		{
			add+=((v[i-1]-v[i])*carry);
			mini=min(mini,add+suffix[i]);
			carry+=umap[v[i]];
		}
		
		cout<<mini<<endl;
	}
}


Comments

Submit
0 Comments
More Questions

1475A - Odd Divisor
1454B - Unique Bid Auction
978C - Letters
501B - Misha and Changing Handles
1496A - Split it
1666L - Labyrinth
1294B - Collecting Packages
1642B - Power Walking
1424M - Ancient Language
600C - Make Palindrome
1669D - Colorful Stamp
1669B - Triple
1669A - Division
1669H - Maximal AND
1669E - 2-Letter Strings
483A - Counterexample
3C - Tic-tac-toe
1669F - Eating Candies
1323B - Count Subrectangles
991C - Candies
1463A - Dungeon
1671D - Insert a Progression
1671A - String Building
1671B - Consecutive Points Segment
1671C - Dolce Vita
1669G - Fall Down
4D - Mysterious Present
1316B - String Modification
1204A - BowWow and the Timetable
508B - Anton and currency you all know