【买二赠一——二分、贪心(有误)】

题目

二分

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 5e5 + 10;
bool vis[N];
int a[N];
int two, pos = 1, n;
ll sum;
int main()
{
    cin >> n;
    for (int i = 1; i <= n; i++)
        cin >> a[i];

    sort(a + 1, a + n + 1, greater<int>());
    while (pos <= n)
    {
        if (vis[pos] == 1)
        {
            pos++;
            continue;
        }

        vis[pos] = 1;
        two++;
        sum += a[pos];

        if (two >= 2)
        {
            int l = pos + 1;
            int r = n;
            while (l < r)
            {
                int mid = l + r >> 1;
                if (a[mid] <= a[pos] / 2)
                    r = mid;
                else
                    l = mid + 1;
            }

            if (a[l] <= a[pos] / 2)
            {
                while (vis[l])
                    l++;
                vis[l] = 1;
            }

            two = 0;
        }

        pos++;
    }

    cout << sum;
}

妙用STL

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
vector<int> v;
long long sum;
int main()
{
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        int x;
        cin >> x;
        v.push_back(x);
    }

    sort(v.begin(), v.end());
    while (v.size())
    {
        auto it = prev(v.end());
        int v1 = *it;
        sum += v1;
        if (it == v.begin())
            break;
        int v2 = *prev(it);
        sum += v2;
        v.erase(prev(v.end()));
        v.erase(prev(v.end()));
        auto lower = upper_bound(v.begin(), v.end(), v2 / 2);
        if (lower == v.begin())
            continue;
        v.erase(prev(lower));
    }

    cout << sum;
}
相关推荐
月光船幽幽5 分钟前
呼吸孔设计重塑系统稳定性
python·科技·算法
旖旎夜光20 分钟前
LeetCode 991: 坏了的计算器(贪心算法) —— 题解
数据结构·c++·算法·leetcode·贪心算法
旖旎夜光39 分钟前
LeetCode 553:最优除法(贪心算法) —— 题解
数据结构·c++·算法·leetcode·贪心算法
雾喔1 小时前
算法练习7
java·数据结构·算法
可编程芯片开发2 小时前
基于模糊PID控制的六步逆变器供电无刷直流电机调速simulink仿真
算法
imperialeast2 小时前
WinAXP音乐播放器8月4日更新
windows·算法·ui
ZhouDevin2 小时前
算法论文/模型微调1——CNN架构做lora微调训练
人工智能·深度学习·算法·架构·cnn
小月土星3 小时前
LeetCode 21. 合并两个有序链表 超详细题解(虚拟头结点 + 逐行代码拆解)
算法
oier_Asad.Chen3 小时前
【OI学习笔记】Floyed-Warshall算法解决传递闭包问题
c++·笔记·学习·算法·图论·最短路·传递闭包
国科安芯3 小时前
卫星星务计算机数据管理中SEU容错机制的技术实现研究——以AS32S601存储器ECC架构为例
网络·单片机·算法·fpga开发·架构·云计算·risc-v