Permutationp is an ordered set of integers p1, p2, ..., pn, consisting ofn distinct positive integers, each of them doesn't exceedn. We'll denote the i-th element of permutation p aspi. We'll call numbern 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.
The first line contains integer n (1 ≤ n ≤ 3·105) — the size of the sought permutation. The second line containsn integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).
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%I64d specifier.
2 3 0
2
3 -1 -1 2
6
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).
问题:就是给你一组数...然后让它变为自然数数列(不用管顺序)所需要的最小改变...
分析:问题其实就是找每个数和自然数列差的绝对值的和最小...而自然数列是递增数列...所以把题目里给的数列排成递增的,然后算下差的绝对值的和就行...
注意:有个坑是用来记改变的sum值用int的话会越界...所以还是得用long long...其他的都用int就行...注意题目中给的范围...
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int n,a[300005];
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
sort(a,a+n);
int t=1;
long long sum=0;
for(int j=0;j<n;j++){
sum+=abs(j+1-a[j]);
}
cout<<sum<<endl;
return 0;
}