蓝桥杯刷题第二十六天

第一题:玩具

题目描述

有 n 个玩具,第 i 个玩具的价格是 ai​ 元,超市里搞促销活动,购买 2 个玩具即可免单其中价格较低的一个,价格相等也免单其中一个。牛牛想买下所有玩具,至少需要花多少元?

输入描述:

第一行一个正整数 n(1≤n≤106)。

第二行 n 个正整数,第 i 个表示 ai​(1≤ai​≤109)。

输出描述:

输出一个数表示答案

输入

3 1 2 3

输出

4

说明

第二个和第三个一起买,花 3 元,再花 1 元买下第一个,合计 4 元。

每次选取最大两个数即可,price加上最大的那个价格即可

#include<iostream>
#include<algorithm>
using namespace std;

const int N = 1000010;
typedef long long LL;
int a[N];
int n;

int main(){
    cin>>n;
    
    for(int i = 1; i <= n; i++) cin>>a[i];
    
    sort(a + 1, a + 1 + n);
    int l = n - 1, r = n;
    LL price = 0;
    while(l >= 1 || r >= 1){
        if(l < 1){
            price += a[r];
            break;
        } 
        int x = a[l], y = a[r];
        if(x == y){
            price += x;
            l-= 2, r -= 2;
            continue;
        }
        else{
            price += max(x, y);
            l -= 2, r -= 2;
            continue;
        }
    }
    
    cout<<price<<endl;
    return 0;
}

 这样写更简单

#include<iostream>
#include<algorithm>
using namespace std;

const int N = 1000010;
typedef long long LL;
int a[N];
int n;

int main(){
    cin>>n;
    
    for(int i = 1; i <= n; i++) cin>>a[i];
    
    sort(a + 1, a + 1 + n);
    int l = n - 1, r = n;
    LL price = 0;
    for(int i = n; i >= 1; i -= 2){
        price += a[i];
    }
    
    cout<<price<<endl;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Libert_AC

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值