第十四届蓝桥杯国赛 C++ B 组 C 题——班级活动(AC)-3. AC_Code

时间:2024-01-26 18:08:43
  • C++
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;

int n;
int main()
{
    cin >> n;
    map<int, int> cnt;
    for (int i = 0; i < n; ++i)
    {
        int x;
        cin >> x;
        cnt[x]++;
    }
    int a = 0, b = 0;
    for (auto [x, y] : cnt)
    {
        if (y == 1)
        {
            a++;
        }
        else if (y > 2)
        {
            b += y - 2;
        }
    }
    if (b >= a)
    {
        cout << b << '\n';
    }
    else
    {
        cout << (a - b) / 2 + b << '\n';
    }
    return 0;
}

  • Java
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        Map<Integer, Integer> cnt = new HashMap<>();
        for (int i = 0; i < n; ++i) {
            int x = sc.nextInt();
            cnt.put(x, cnt.getOrDefault(x, 0) + 1);
        }
        int a = 0, b = 0;
        for (Map.Entry<Integer, Integer> entry : cnt.entrySet()) {
            int y = entry.getValue();
            if (y == 1) {
                a++;
            } else if (y > 2) {
                b += y - 2;
            }
        }
        if (b >= a) {
            System.out.println(b);
        } else {
            System.out.println((a - b) / 2 + b);
        }
    }
}
  • Python
n = int(input())
line = list(map(int, input().split()))
cnt = {}
for i in range(n):
    x = line[i]
    if x in cnt:
        cnt[x] += 1
    else:
        cnt[x] = 1
a = 0
b = 0
for y in cnt.values():
    if y == 1:
        a += 1
    elif y > 2:
        b += y - 2
if b >= a:
    print(b)
else:
    print((a - b) // 2 + b)