当前位置: 首页 > news >正文

Codeforces Round 1054 (Div. 3) - D、E

目录
  • D. A and B
  • E. Hidden Knowledge of the Ancients

Codeforces Round 1054 (Div. 3)

D. A and B

参考了 Tutorial

题意很简单,(总结后)就是将所有的字符 a 或者所有的字符 b 汇集到一起。那么对于每种字符分别考虑位置聚到一起的代价,选择小的就是答案。

Let the target be to make all occurrences of one letter contiguous. Do it for both letters and take the minimum.
Fix a letter \(c\in{a,b}\) and let its positions be \(p_0<p_1<\dots<p_{m-1}\). If we place these \(m\) copies into a consecutive block starting at some index \(L\), the number of adjacent swaps needed is $ \sum_{i=0}^{m-1} \bigl|, p_i - (L+i) ,\bigr| ;=; \sum_{i=0}^{m-1} \bigl|, (p_i - i) - L ,\bigr|$
Set \(b_i=p_i-i\). The function \(\sum_i |b_i-L|\) is minimized when \(L\) is a median of \({b_i}\). Hence the optimal cost to cluster all \(c\)'s is
$ \operatorname{cost}(c) = \sum_{i=0}^{m-1} \bigl|, b_i - \operatorname{med}(b) ,\bigr|, \quad \text{where } b_i = p_i - i.$
The answer is \(\min(\operatorname{cost}(a),\operatorname{cost}(b))\).
This counts the minimal number of adjacent swaps because each swap reduces the sum of pairwise inversions between the two types by exactly \(1\), and aligning to a consecutive block achieves the minimum. The algorithm computes positions, builds \(b_i\), takes the median, and sums absolute deviations — all in linear time after positions are known.
The time complexity is \(O(n)\).

在代码实现中,最终计算的是 val += abs(v[pos] - v[i]) - abs(pos - i);。这样的写法和题解的描述是等价的!
中位数的选取即为 k = m / 2 位置上的数 p[k] - k
题解公式为 \(cost(a) = \sum_{i = 0}^{m - 1} |b_i - b_k| = \sum_{i = 0}^{m - 1} |(p_i - i) - (p_k - k)|\)
代码对应的公式为 \(val = \sum_{i = 0}^{m - 1} (|p_i - p_k| - |i - k|)\)
对于本题,这两个式子是对应成立的

代码:Qiansui_code

E. Hidden Knowledge of the Ancients

参考链接

  • 双指针做法:https://zhuanlan.zhihu.com/p/1954707609866208306
  • 容斥做法:https://www.cnblogs.com/cjiaw/articles/19148932
http://www.hskmm.com/?act=detail&tid=39755

相关文章:

  • AI元人文:客观清醒 - 传统模型转型的残酷博弈
  • ​​ORourke 算法​​ 多边形的最小面积外接矩形 - MKT
  • 102302106-陈昭颖-第一次作业
  • P1877 [HAOI2012] 音量调节
  • 数论导论
  • P14321 「ALFR Round 11」D Adjacent Lifting, Fewest Rounds 题解
  • 国庆集训day1~2笔记-动态规划
  • P1679 神奇的四次方数
  • Minio外网访问内网上传的预签名url的方法以及报错原因
  • vscode解决中文乱码
  • 【ESP32 在线语音】星火大模型
  • RT-Thread 之互斥量使用
  • 20232419 2025-2026-1 《网络与系统攻防技术》实验三实验报告
  • 语义文本理解 BERT - MKT
  • Rig 项目深度分析报告
  • FM-Fusion 利用rgbd相机 ram-GroundingDINO-sam 重建语义地图 - MKT
  • AI元人文构想系列:从战略能力到价值对话的文明之路
  • 事件日志查看Windows安装软件情况
  • RT-Thread之创建线程
  • cias_voice_plyer_handle.c 解析
  • 【CI130x 离在线】FreeRTOS的流缓冲(StreamBuffer)
  • 数据采集与融合技术作业1
  • RT-Thread Nano源码浅析
  • 关于SQLite - 世界上装机量最多的数据库
  • 《从 “被动听” 到 “主动学”:课堂听讲助力大学生思维成长》
  • 用AI批量生成产品视频!Python+Google Veo 3.1 API让电商转化率飙升
  • 模拟IIC与硬件IIIC哪个更常用?
  • 每日反思(2025_10_26)
  • 251019 NOIP 模拟赛 T2 | dp 及其优化、调整法最优解性质、数形结合
  • 小作业 14(2018 北京高考文科)