[蓝桥杯]真题讲解:班级活动(贪心)

[蓝桥杯]真题讲解:班级活动(贪心)

一、视频讲解

[蓝桥杯]真题讲解:班级活动(贪心)

二、正解代码

在这里插入图片描述

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);
        }
    }
}

  • 10
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值