using
System;
using
System.Collections.Generic;
class
GFG {
static
int
Compare(KeyValuePair<
int
,
int
> a,
KeyValuePair<
int
,
int
> b)
{
return
a.Key.CompareTo(b.Key);
}
static
int
minOperationToEmpty(
int
[] A,
int
N)
{
int
j, i, OpCnt = 0;
Dictionary<
int
,
int
> freq
=
new
Dictionary<
int
,
int
>();
var
arrPos =
new
List<KeyValuePair<
int
,
int
> >();
var
optimalPairs
=
new
List<KeyValuePair<
int
,
int
> >();
for
(i = 0; i < N; i++) {
if
(freq.ContainsKey(A[i])) {
var
val = freq[A[i]];
freq.Remove(A[i]);
freq.Add(A[i], val + 1);
}
else
freq.Add(A[i], 1);
}
foreach
(
var
e
in
freq) arrPos.Add(
new
KeyValuePair<
int
,
int
>(e.Value, e.Key));
arrPos.Sort(Compare);
for
(i = arrPos.Count - 1; i >= 1; i--) {
j = i - 1;
while
(arrPos[i].Key != 0 && j >= 0) {
int
temp = Math.Min(arrPos[i].Key,
arrPos[j].Key);
int
loop = temp;
while
(loop-- != 0)
optimalPairs.Add(
new
KeyValuePair<
int
,
int
>(
arrPos[i].Value,
arrPos[j].Value));
OpCnt += temp;
var
p =
new
KeyValuePair<
int
,
int
>(
arrPos[i].Key - temp, arrPos[i].Value);
arrPos[i] = p;
p =
new
KeyValuePair<
int
,
int
>(
arrPos[j].Key - temp, arrPos[j].Value);
arrPos[j] = p;
j--;
}
}
for
(i = 0; i < arrPos.Count; i++) {
if
(arrPos[i].Key != 0) {
OpCnt += arrPos[i].Key;
break
;
}
}
for
(j = 0;
j < optimalPairs.Count && i < arrPos.Count
&& arrPos[i].Key >= 2;
j++) {
if
(optimalPairs[j].Key != arrPos[i].Value
&& optimalPairs[j].Value
!= arrPos[i].Value) {
OpCnt--;
Console.WriteLine(i);
var
p =
new
KeyValuePair<
int
,
int
>(
arrPos[i].Key - 2, arrPos[i].Value);
arrPos[i] = p;
}
}
return
OpCnt;
}
static
void
Main()
{
int
[] A = { 1, 2, 3, 4, 5, 6, 7, 8 };
int
N = A.Length;
Console.Write(minOperationToEmpty(A, N));
}
}