二分+模拟,CF1461D - Divide and Summarize

一、题目

1、题目描述

2、输入输出

2.1输入
2.2输出

3、原题链接

Problem - 1461D - Codeforces


二、解题报告

1、思路分析

我们发现每次分裂操作结果都是固定的

我们从初始序列分裂出两个确定的子序列,两个确定的子序列又分裂出4个确定的子序列

那么也就是说我们最终能够分裂出的子序列的数目是O(n)的

我们预处理出所有的子序列就预处理出了所有可以得到的和(当然这个和要在分裂的过程中维护)

而分裂要求我们得到小于等于mid的部分和大于的部分

所以我们需要对原序列进行排序,模拟的过程通过二分来找到分裂的位置

同时预处理前缀和以便每次分裂前都记录一下当前得到的值

值得注意的是numsl = numsr的时候说明当前子序列是相同的,我们无法继续向下分裂

2、复杂度

时间复杂度: O(NlogN)空间复杂度:O(N)

3、代码详解

复制代码
​
cpp 复制代码
#include <bits/stdc++.h>
using PII = std::pair<int, int>;
using i64 = long long;
std::mt19937 rnd(std::chrono::steady_clock::now().time_since_epoch().count());

const int P = [](int x) {
    auto isprime = [](int x) {
        if (x <= 1) return false;
        for (int i = 2; i <= x / i; i ++ )
            if (x % i == 0) return false;
        return true;
    };
    while (!isprime(x)) x ++;
    return x;
}(rnd() % 900000000 + 100000000);

void solve() {
    /*  直接模拟    */
    int N, Q, s;
    std::cin >> N >> Q;
    std::vector<int> nums(N);
    std::vector<i64> pre(N + 1);
    for (int i = 0; i < N; i ++ ) 
        std::cin >> nums[i];
    std::sort(nums.begin(), nums.end());

    for (int i = 0; i < N; i ++ ) 
        pre[i + 1] += nums[i] + pre[i];
    
    std::vector<std::array<int, 2>> segs { { 0, N - 1 } };  segs.reserve(N);
    std::unordered_set<i64> st;

    while (segs.size()) {
        std::vector<std::array<int, 2>> nxt;
        for (auto& [l, r] : segs) {
            st.insert(pre[r + 1] - pre[l] + P);

            if (nums[l] != nums[r]) {
                int mid = std::upper_bound(nums.begin(), nums.end(), (nums[l] + nums[r]) >> 1) - nums.begin();
                nxt.insert(nxt.end(), { { l, mid - 1 }, { mid, r } });
            }
        }
        segs = std::move(nxt);
    }

    for (int i = 0, s; i < Q; i ++) {
        std::cin >> s;
        if (st.count(1LL * s + P))
            std::cout << "YES\n";
        else
            std::cout << "NO\n";
    }
}


int main () {
    std::ios::sync_with_stdio(false);   std::cin.tie(0);  std::cout.tie(0);
    int _ = 1;
    std::cin >> _;
    while (_ --)
        solve();
    return 0;
}
相关推荐
多弗朗皮卡丘18 分钟前
C++STL之空间配置器
开发语言·c++·内存池·空间配置器
牵猫散步的鱼儿22 分钟前
Demosaic 和 Remosaic
c++
荆棘鸟智能26 分钟前
河道采砂船识别与轨迹追踪怎么做?检测、跟踪与电子围栏实战思路
人工智能·算法·目标检测
CodeYp201930 分钟前
第19讲:封装红黑树实现 mymap 和 myset
开发语言·c++·红黑树
DFT计算杂谈1 小时前
GSAS-II X 射线衍射(XRD)数据转换为对分布函数(PDF,Pair Distribution Function)
算法·机器学习·pdf
孙鹏宇.1 小时前
C++类型转换
c++
绕灵儿1 小时前
火灾检测-应用场景-YOLO训练记录
人工智能·算法
超级架构师1 小时前
让 COBOL 长出 AI 大脑:原生 Agent 核心框架 praxo-core 深度剖析
c语言·开发语言·c++·人工智能·python·架构·ai编程
·present·1 小时前
CSAPP(lecture 10)
c语言·c++
YLCHUP1 小时前
【模拟&STL】题解:AT_abc203_e [ABC203E] White Pawn_基础算法_数据结构_STL模板库_AtcoderABC_C++算法竞赛
数据结构·c++·算法·leetcode·动态规划·哈希算法·近邻算法