二分+模拟,CF1461D - Divide and Summarize

一、题目

1、题目描述

2、输入输出

2.1输入
2.2输出

3、原题链接

Problem - 1461D - Codeforces


二、解题报告

1、思路分析

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

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

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

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

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

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

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

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

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;
}
相关推荐
海梨花5 分钟前
【力扣Hot100】刷题日记
算法·leetcode·1024程序员节
m0_7482402526 分钟前
基于Reactor模式的高性能C++仿Muduo库:Server服务器模块实现
服务器·c++·php
hope_wisdom28 分钟前
C/C++数据结构之用链表实现栈
c语言·数据结构·c++·链表·
DuHz33 分钟前
使用稀疏采样方法减轻汽车雷达干扰——论文阅读
论文阅读·算法·汽车·信息与通信·信号处理
王老师青少年编程38 分钟前
AtCoder真题及详细题解 ABC427C: Bipartize
c++·题解·1024程序员节·atcoder·csp·abc·信奥赛
ceclar12340 分钟前
C++容器forward_list
开发语言·c++·list
ceclar12344 分钟前
C++容器list
java·c++·list
大肘子咒你1 小时前
数字狂潮来袭
数据结构·c++·1024程序员节
hansang_IR1 小时前
【算法速成课 3】康托展开(Cantor Expansion)/ 题解 P3014 [USACO11FEB] Cow Line S
c++·算法·状态压缩·康托展开·排列映射
m0_748233641 小时前
【类与对象(中)】C++类默认成员函数全解析
开发语言·c++·算法