CUIT ACM Personal Training 11.27(FM)J - Building Permutation

J - Building Permutation

Time Limit:2000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u

Description

Permutation p is an ordered set of integers p1,  p2,  ...,  pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,  p2,  ...,  pn.

You have a sequence of integers a1, a2, ..., an. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.

Input

The first line contains integer n (1 ≤ n ≤ 3·105) — the size of the sought permutation. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).

Output

Print a single number — the minimum number of moves.

Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64dspecifier.

Sample Input

Input
2
3 0
Output
2
Input
3
-1 -1 2
Output
6

Hint

In the first sample you should decrease the first number by one and then increase the second number by one. The resulting permutation is (2, 1).

In the second sample you need 6 moves to build permutation (1, 3, 2).



題解:這個題也是簡單的貪心,給你一串數字,讓你每次加一或者減一,使得他們可以形成一個以1爲公差的等差數列。樣例是很有誤導性的,主要原因是他並沒有排好順序。其實這個問題只要進行排序之後,依次變化成座標就可以了。爲什麼這就是最優解呢?首先我們給出3 4 5,要使得他們變成1 2 3,那麼對應變換,也就是5->3,4->2,3->1,可以達到步數最短,這個我們可以通過數學推導來證明,比如有有k>p>q,使得他們變成m,m+1,m+2,那麼如果按照剛纔的對應,我們變化的總次數是|k-m-2|+|p-m-1|+|q-m|。如果不按照那個順序來,我們變化的次數可能就會變成|k-m|+|p-m-1|+|q-m-2|之類的,如果q>=m+2時,結果確實與剛纔的對應變化次數相同。q<m+2時,前一次的結果是k+p+q-3m-3,後一次的結果是k+p-q+1-m,用後面的減前面的就會發現結果是2m+4-2q,因爲q<m+2,所以最後結果是大於0的。所以同理去推導,當按照遞增的順序變成1,2,3的序列步數最少。


AC代碼如下:

#include<bits/stdc++.h>
using namespace std;

long long sum = 0, a[300005];
int n,i,t;

int main()
{
    scanf("%d",&n);
    for(i=0;i<n;i++)
        scanf("%lld",&a[i]);
    sort(a,a+n);
    for(i=1;i<=n;i++)
        sum += abs(a[i-1] - i);
    printf("%lld\n",sum);
    return 0;
}


發佈了36 篇原創文章 · 獲贊 14 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章