[蓝桥杯]真题讲解:班级活动(贪心)
- 一、视频讲解
- 二、正解代码
- 1、C++
- 2、python3
- 3、Java
一、视频讲解
[蓝桥杯]真题讲解:班级活动(贪心)
二、正解代码
1、C++
#include<bits/stdc++.h>
using namespace std;
int main(){
int n; cin >> n;
vector<int>a(n);
map<int,int>st;
for(int i = 0; i < n; i ++) {
cin >> a[i];
st[a[i]] ++;
}
int ans = 0;
int c1 = 0, c2 = 0;
for(auto x: st) {
if(x.second > 2){
c2 += (x.second - 2);
}else if(x.second == 1) {
c1 += 1;
}
}
if(c1 < c2){
cout << c2 << endl;
}else {
cout << c2 + (c1 - c2) / 2 << endl;
}
}
2、python3
n = int(input())
a = list(map(int, input().split()))
st = {}
for x in a:
if x not in st:
st[x] = 1
else:
st[x] += 1
ans, c1, c2 = 0, 0, 0
for x, y in st.items():
if y > 2:
c2 += (y - 2)
elif y == 1:
c1 += 1
if c1 < c2:
print(c2)
else:
print(c2 + (c1 - c2) // 2)
3、Java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<Integer> a = new ArrayList<>();
Map<Integer, Integer> st = new HashMap<>();
for(int i = 0; i < n; i ++) {
int x = sc.nextInt();
a.add(x);
if(st.get(x) != null)
st.put(x, st.get(x) + 1);
else
st.put(x, 1);
}
int ans = 0, c1 = 0, c2 = 0;
for(Map.Entry<Integer, Integer> x: st.entrySet()){
if(x.getValue() > 2) {
c2 += x.getValue() - 2;
}else if(x.getValue() == 1) {
c1 += 1;
}
}
if(c1 < c2) {
System.out.println(c2);
}else{
System.out.println(c2 + (c1 - c2) / 2);
}
}
}