codeforces 285C Building Permutation (简单贪心)

Building Permutation
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Input

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).

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%I64d specifier.

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

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值