Codeforces 819 B. Mister B and PR Shifts

来源:互联网 发布:什么软件可以做代理 编辑:程序博客网 时间:2024/05/22 07:53
题意:

有一个无序排列,有操作使得ni=1|pii|最小。
构造规则:初始时有一个排列编号为0,每次操作将排列循环右移,排列的编号+1。

数据范围:

2n106

算法:

考虑维护一个桶记录pi在它目标位置的左边时的距离,并且记录偏左(包括在目标位置上的点)、偏右的点的个数。
利用这个桶就可以在线性时间内计算每次右移的答案。
Ansi=Ansi1leftist+rightistabs(pn(n+1))+pn1
在每次更新完答案后要把最后一个放到第一个位置上所以leftist+1,rightist1

代码:
#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;}