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

题目

二分

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;
}
相关推荐
kukubuzai2 分钟前
双指针系列二--末尾篇(3道题)
c++·算法·leetcode
杜 硕16 分钟前
单链表经典算法题
数据结构·算法
小O的算法实验室1 小时前
IEEE TCYB,着色旅行商问题:模型、求解与应用
算法
h_a_o777oah1 小时前
【图论】网络流:Dinic 算法模板实现原理及解题技巧
c++·算法·图论·acm·网络流·最小割·dinic算法
我不会起名字3221 小时前
一天一道力扣Hot100(37):深度优先算法--括号生成
java·数据结构·c++·后端·python·算法·go
foolishlee1 小时前
SCRAM-SHA-256
数据库·算法·postgresql
Rabitebla2 小时前
【Linux 系统编程】权限(一):身份、提权,和那 9 个权限位
linux·数据结构·c++·算法
-dzk-2 小时前
【回溯】LC 22.括号生成
算法·回溯
杜 硕3 小时前
顺序表算法
数据结构·算法
AgentMaster4 小时前
智能客服多渠道接入,5 款产品的全渠道整合能力对比与实战
大数据·人工智能·算法