博客
关于我
Codeforces1042D——线段树|树状数组|分治+尺取
阅读量:657 次
发布时间:2019-03-15

本文共 1737 字,大约阅读时间需要 5 分钟。

要解决这个问题,我们需要找到满足特定条件的二元组(l, r),其中(l, r)的前缀和满足条件sum[r] - sum[l] < t。考虑到数组规模较大,我们采用树状数组配合前缀和和离散化的方法来优化解决过程。

方法思路

  • 计算前缀和:首先计算数组a的前缀和数组sum。sum数组中的每个元素sum[i]表示从数组a的开头到第i个元素的和。
  • 离散化:由于sum数组的值可能非常大,使用离散化方法将每个sum值映射到一个较小的连续范围内,方便树状数组处理。
  • 树状数组:使用树状数组来动态维护前缀和值,快速查询满足条件的元素个数。对于每个r,计算目标值target = sum[r] - t,查询前缀和数组中sum[0..r-1]中小于target的元素个数,并将结果累加。
  • 更新数据结构:将当前sum[r]插入树状数组,供后续处理。
  • 解决代码

    #pragma GCC optimize("fast-math")
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    #include
    using namespace std; struct FenwickTree { private: vector
    tree; int size; public: FenwickTree(int _size) : tree(size + 1, 0), size(_size) {} void update(int idx, ll delta) { while (idx <= size) { tree[idx] += delta; idx += idx & -idx; } } ll query(int idx) { ll res = 0; while (idx > 0) { res += tree[idx]; idx -= idx & -idx; } return res; } }; void main() { cin >> n >> t; vector
    a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } vector
    sum(n + 1, 0); for (int i = 1; i <= n; ++i) { sum[i] = sum[i-1] + a[i]; } // 离散化sum数组 set
    s; vector
    sorted_vals; for (ll val : sum) { s.insert(val); } sorted_vals.assign(s.begin(), s.end()); map
    rank; for (int i = 0; i < sorted_vals.size(); ++i) { rank[sorted_vals[i]] = i + 1; // 1-based索引 } FenwickTree ft(n + 1); ll ans = 0; for (int r = 1; r <= n; ++r) { ll target = sum[r] - t; ll num = ft.query(rank[sum[r-1]]); ans += num; ft.update(rank[sum[r]], 1); } cout << ans << endl; }

    代码解释

  • 计算前缀和:使用循环计算前缀和数组sum。
  • 离散化:将前缀和数组sum中的值映射到较小的连续整数范围内,方便树状数组处理。
  • 树状数组初始化:创建树状数组对象,维护前缀和值的计数。
  • 遍历每个r:计算目标值target,查询前缀和数组中sum[0..r-1]中小于target的元素个数,并累加到答案中。
  • 更新数据结构:将当前sum[r]插入树状数组,维护动态更新。
  • 这种方法通过树状数组的高效查询和更新操作,将问题的时间复杂度降低到O(n log n),适用于大规模数据处理。

    转载地址:http://xufmz.baihongyu.com/

    你可能感兴趣的文章
    MySQL 大数据量快速插入方法和语句优化
    查看>>
    mysql 如何给SQL添加索引
    查看>>
    mysql 字段区分大小写
    查看>>
    mysql 字段合并问题(group_concat)
    查看>>
    mysql 字段类型类型
    查看>>
    MySQL 字符串截取函数,字段截取,字符串截取
    查看>>
    MySQL 存储引擎
    查看>>
    mysql 存储过程 注入_mysql 视图 事务 存储过程 SQL注入
    查看>>
    MySQL 存储过程参数:in、out、inout
    查看>>
    mysql 存储过程每隔一段时间执行一次
    查看>>
    mysql 存在update不存在insert
    查看>>
    Mysql 学习总结(86)—— Mysql 的 JSON 数据类型正确使用姿势
    查看>>
    Mysql 学习总结(87)—— Mysql 执行计划(Explain)再总结
    查看>>
    Mysql 学习总结(88)—— Mysql 官方为什么不推荐用雪花 id 和 uuid 做 MySQL 主键
    查看>>
    Mysql 学习总结(89)—— Mysql 库表容量统计
    查看>>
    mysql 实现主从复制/主从同步
    查看>>
    mysql 审核_审核MySQL数据库上的登录
    查看>>
    mysql 导入 sql 文件时 ERROR 1046 (3D000) no database selected 错误的解决
    查看>>
    mysql 导入导出大文件
    查看>>
    mysql 将null转代为0
    查看>>