AtCoder Beginner Contest 407 E - Most Valuable Parentheses

AtCoder Beginner Contest 407 E - Most Valuable Parentheses

E - Most Valuable Parentheses

反悔贪心算法

性质:

  • 假设长度为 n n n, n ≡ 0 ( m o d 2 ) n \equiv 0 \pmod{2} n≡0(mod2) 的括号序列是合法的,那么有 n 2 \frac{n}{2} 2n 个左括号
  • 那么长度为 i i i ( i ≤ n i \leq n i≤n) 的括号序列至少有 ⌊ i + 1 2 ⌋ \lfloor \frac{i+1}{2} \rfloor ⌊2i+1⌋ 个左括号
  • 第一个一定是左括号,最后一个一定是右括号

根据性质2进行反悔贪心即可

  • 在前1个数字里面,贪心选择前1大的数
  • 在前3个数字里面,贪心选择前2大的数
  • 在前5个数字里面,贪心选择前3大的数
  • ...
  • 在前 2 × n − 1 2 \times n - 1 2×n−1 个数字里面,贪心选择前 n n n 大的数
cpp 复制代码
#include <bits/stdc++.h>
 #define int long long
#define PII pair<int,int>
#define endl "\n"
#define LL long long
#define fi first
#define se second
#define debug(a) cout<<#a<<"="<<a<<endl;
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define sz(x) (int)x.size()
#define rd(x, y) rand() % (y - x + 1) + x
#define ls u << 1
#define rs u << 1 | 1
using namespace std;
   
const int N = 400010;
int a[N], n, m, k;
 
void solve(){
    cin >> n;
    for(int i = 1; i <= n * 2; i ++ ){
        cin >> a[i];
    }
    priority_queue<int>q;
    int ans = 0;
    for(int i = 1; i <= n; i ++ ){
        if(i == 1) q.push(a[i]);
        else{
            q.push(a[i * 2 - 1]);
            q.push(a[i * 2 - 2]);
        }
        ans += q.top(); q.pop();
    }
    cout << ans << endl;
}
 
signed main(){
    int tt = 1;
    cin >> tt;
    while(tt -- ){
        solve();
    }
    return 0;
}
相关推荐
YuTaoShao2 小时前
【LeetCode 每日一题】3634. 使数组平衡的最少移除数目——(解法一)排序+滑动窗口
算法·leetcode·排序算法
波波0072 小时前
每日一题:.NET 的 GC是如何分代工作的?
算法·.net·gc
风暴之零2 小时前
变点检测算法PELT
算法
深鱼~2 小时前
视觉算法性能翻倍:ops-cv经典算子的昇腾适配指南
算法·cann
李斯啦果2 小时前
【PTA】L1-019 谁先倒
数据结构·算法
梵刹古音2 小时前
【C语言】 指针基础与定义
c语言·开发语言·算法
啊阿狸不会拉杆2 小时前
《机器学习导论》第 5 章-多元方法
人工智能·python·算法·机器学习·numpy·matplotlib·多元方法
R1nG8633 小时前
CANN资源泄漏检测工具源码深度解读 实战设备内存泄漏排查
数据库·算法·cann
_OP_CHEN3 小时前
【算法基础篇】(五十六)容斥原理指南:从集合计数到算法实战,解决组合数学的 “重叠难题”!
算法·蓝桥杯·c/c++·组合数学·容斥原理·算法竞赛·acm/icpc
TracyCoder1233 小时前
LeetCode Hot100(27/100)——94. 二叉树的中序遍历
算法·leetcode