Codeforces 819 B. Mister B and PR Shifts
来源:互联网 发布:什么软件可以做代理 编辑:程序博客网 时间:2024/05/22 07:53
题意:
有一个无序排列,有操作使得
∑ni=1|pi−i| 最小。
构造规则:初始时有一个排列编号为0,每次操作将排列循环右移,排列的编号+1。
数据范围:
2 ≤ n ≤ 106
算法:
考虑维护一个桶记录
pi 在它目标位置的左边时的距离,并且记录偏左(包括在目标位置上的点)、偏右的点的个数。
利用这个桶就可以在线性时间内计算每次右移的答案。
Ansi=Ansi−1−leftist+rightist−abs(pn−(n+1))+pn−1
在每次更新完答案后要把最后一个放到第一个位置上所以leftist+1,rightist−1 。
代码:
#include <cstdio>#include <algorithm>using namespace std;int rd() { int x = 0; char c = getchar(); while (c > '9' || c < '0') c = getchar(); while (c >= '0' && c <= '9') x = x * 10 + c - 48, c = getchar(); return x; }const int N = 2e6 + 10;int p[N], a[N], id, pl, pr, n;long long ans, sum;int main() { n = rd(); for (int i = 1; i <= n; i ++) p[i] = rd(); for (int i = 1; i <= n; i ++) { sum += abs(p[i] - i); if (p[i] >= i) a[p[i] - i] ++, pl ++; else pr ++; } ans = sum; for (int i = 1; i < n; i ++) { pl -= a[i - 1], pr += a[i - 1]; sum = sum - pl + pr - abs(p[n - i + 1] - (n + 1)) + p[n - i + 1] - 1; pl ++, pr --; a[p[n - i + 1] + i - 1] ++; if (ans > sum) ans = sum, id = i; } printf("%lld %d\n", ans, id); return 0;}
阅读全文
1 0
- Codeforces 819 B. Mister B and PR Shifts
- Codeforces 819B. Mister B and PR Shifts
- CodeForces-820D Mister B and PR Shifts
- Codeforces Round #421 (Div. 1):B. Mister B and PR Shifts(瞎搞)
- Codeforces Round #421 (Div. 1):B. Mister B and PR Shifts 思维,乱搞
- Codeforces Round #421 Mister B and PR Shifts(暴力瞎搞)
- Codeforces Round 421 Div.2 D. Mister B and PR Shifts 思维 乱搞
- Codeforces Round #421 (Div. 2) D. Mister B and PR Shifts
- Codeforces Round #421 (Div. 2) D. Mister B and PR Shifts
- CodeForces 820D Mister B and PR Shifts(思维题)
- codeforces819B Mister B and PR Shifts -- 线段树
- #421 Div.2 D. Mister B and PR Shifts
- CF 820D Mister B and PR Shifts 差分(区间+k*(x-L)+b)
- codeforces819bMister B and PR Shifts
- Codeforces 819 A. Mister B and Boring Game
- Codeforces 819 E. Mister B and Flight to the Moon
- Codeforces 819 D. Mister B and Astronomers 数论
- Codeforces 820B Mister B and Angle in Polygon
- OpenCV自学笔记14:Harris角点检测实例
- Clustered Features——聚合要素
- viewpager详细使用说明
- Haproxy的详解
- 学习SVM(三)理解SVM中的对偶问题
- Codeforces 819 B. Mister B and PR Shifts
- Java多态性理解
- PHP中文乱码解决方案
- python merge、concat合并数据集
- 项目学习笔记
- java api
- Shell命令之Android及iOS常用操作命令
- Oracle12C 数据库安装示范教程
- 聚类总结