Codeforces 819 B. Mister B and PR Shifts - 模拟
2017-06-28 16:21
267 查看
题意:
有一个无序排列,有操作使得∑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。
代码:
有一个无序排列,有操作使得∑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 , a , 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; }
相关文章推荐
- 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 Round #421 (Div. 1):B. Mister B and PR Shifts 思维,乱搞
- [CF819B]Mister B and PR Shifts
- Codeforces Round #421 (Div. 2) D. Mister B and PR Shifts
- Codeforces 819 D. Mister B and Astronomers 数论
- Codeforces Round #421 (Div. 1):B. Mister B and PR Shifts(瞎搞)
- Codeforces Round #421 Mister B and PR Shifts(暴力瞎搞)
- Codeforces 819 E. Mister B and Flight to the Moon
- Codeforces Round #421 (Div. 1) B. Mister B and PR Shifts(技巧)
- codeforces 251 div2 C. Devu and Partitioning of the Array 模拟
- 【CodeForces】66B - Petya and Countryside(递增子串变形题,模拟)
- Codeforces--658A--Bear and Reverse Radewoosh(模拟)
- Codeforces--658C--Bear and Forgotten Tree 3(模拟&&技巧)(好题)
- codeforces 425B Sereja and Table(状态压缩,也可以数组模拟)
- Codeforces 518C Anya and Smartphone【思维+模拟】
- Codeforces Good Bye 2017: F. New Year and Rainbow Roads(模拟)
- CodeForces 360A - Levko and Array Recovery (模拟)
- CodeForces 811B——Vladik and Complicated Book ——思维,模拟