Some time ago Mister B detected a strange signal from the space, which he started to study.
After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation which has the minimum possible deviation.
Let's define the deviation of a permutation p as .
Find a cyclic shift of permutation p with minimum possible deviation. If there are multiple solutions, print any of them.
Let's denote id k (0 ≤ k < n) of a cyclic shift of permutation p as the number of right shifts needed to reach this shift, for example:
- k = 0: shift p1, p2, ... pn,
- k = 1: shift pn, p1, ... pn - 1,
- ...,
- k = n - 1: shift p2, p3, ... pn, p1.
First line contains single integer n (2 ≤ n ≤ 106) — the length of the permutation.
The second line contains n space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the elements of the permutation. It is guaranteed that all elements are distinct.
Print two integers: the minimum deviation of cyclic shifts of permutation p and the id of such shift. If there are multiple solutions, print any of them.
3 1 2 3
0 0
3 2 3 1
0 1
3 3 2 1
2 1
In the first sample test the given permutation p is the identity permutation, that's why its deviation equals to 0, the shift id equals to 0 as well.
In the second sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 2, 3) equals to 0, the deviation of the 2-nd cyclic shift (3, 1, 2) equals to 4, the optimal is the 1-st cyclic shift.
In the third sample test the deviation of p equals to 4, the deviation of the 1-st cyclic shift (1, 3, 2) equals to 2, the deviation of the 2-nd cyclic shift (2, 1, 3) also equals to 2, so the optimal are both 1-st and 2-nd cyclic shifts.
题解:
暴力O(n^2)很容易想到 那么能不能优化呢?
考虑每次右移 答案是可以从上一次移动的答案算出来
若p[i]>i那么答案会-1 反之则会+1
那么我们只需要知道每步p[i]>i的个数
我们可以用O(1)的时间求出这一位上放着的p[i]要走几步才会与下标的大小关系改变
然后对它做一个前缀和 就可以求出每步p[i]>i的个数 答案就是上一个答案-这个个数+(n-这个个数)(一个是正的 绝对值要减少 而一个是负的 绝对值增加)
代码:
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn=1000000+10;
int p[maxn];
int A[maxn];
int B[maxn];
int dis[maxn];
int ans[maxn];
inline int abs(int x){
return x<0?-x:x;
}
int main(){
freopen("MrBB1.in","r",stdin);
freopen("MrBB1.out","w",stdout);
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&p[i]);
if(p[i]==1)
continue;
if(i<p[i]){
A[p[i]-i]++;
dis[0]++;
}
else
A[p[i]+n-i]++;
B[n-i+1]++;
}
int cnt=0;
long long ans=0;
long long maxx=0x7fffffff,u=0;
for(int i=1;i<=n;i++){
if(p[i]>i)
cnt++;
ans+=abs(p[i]-i);
}
maxx=ans;
for(int i=1;i<n;i++){
dis[i]=dis[i-1]+B[i]-A[i];
ans+=n-dis[i-1];
ans-=dis[i-1];
ans--;
ans+=p[n-i+1]-1;
ans-=n-p[n-i+1];
if(ans<maxx){
maxx=ans;
u=i;
}
}
cout<<maxx<<' '<<u<<endl;
return 0;
}