AcWing 134 贪心

题意

传送门 AcWing 134 双端队列

题解

队列拼接后得到非降序列,考虑将数组按照值域排序,求在索引值上满足单谷性质的连续不重叠的序列的最小值。单谷性质是为了保证新加入双端队列的数字只能从两头插入,即其索引值大于队内中间元素的索引值。

采取贪心策略,从左向右扫描数组,尽可能的拓展满足单谷性质的段的长度。若存在值域相等的元素,保证其相邻的条件下,可以交换其位置,使段尽可能的拓展;可以观察到使值域相等的元素按照索引值有序后,升序拼接或降序拼接,不会使答案更差。

#include <bits/stdc++.h>
using namespace std;
const int maxn = 200005;
struct node
{
    int x, id;
} A[maxn];
int N;

bool cmp1(const node &a, const node &b) { return a.x < b.x; }

bool cmp2(const node &a, const node &b) { return a.id < b.id; }

int main()
{
    scanf("%d", &N);
    for (int i = 0; i < N; ++i)
    {
        scanf("%d", &A[i].x);
        A[i].id = i;
    }
    sort(A, A + N, cmp1);
    int s = -1, pre = 0, res = 0;
    for (int i = 0; i < N;)
    {
        int l = i, r = i + 1, x = A[i].x;
        while (r < N && A[r].x == x)
            ++r;
        sort(A + l, A + r, cmp2);
        int mn = A[l].id, mx = A[r - 1].id;
        if (s == -1)
            s = 0, pre = mn, ++res;
        else if (s == 0)
        {
            if (mx > pre)
                s = 1, pre = mx;
            else
                pre = mn;
        }
        else
        {
            if (mn < pre)
                ++res, s = 0, pre = mn;
            else
                pre = mx;
        }
        i = r;
    }
    printf("%d\n", res);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值