CodeForces 285C

本文介绍了一个经典的编程问题——如何通过增减操作将给定整数序列转换为排列,并提供了一种有效的解决方案。该方案首先对输入序列进行排序,然后计算序列元素与理想位置之间的绝对差值之和作为最小操作次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C. Building Permutation
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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 C++. It is preferred to use the cin, cout streams or the %I64d specifier.

Examples
Input
Copy
2
3 0
Output
Copy
2
Input
Copy
3
-1 -1 2
Output
Copy
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).



这道题只需要将输入的数组排序一下,并与原数组的差相加起来便是答案


#include<bits/stdc++.h>
using namespace std;
long long a[300005];
int main(){
	int n;
	while(~scanf("%d",&n)){
		
		for(int i=1;i<=n;i++){
			scanf("%I64d",&a[i]);
		}
		sort(a+1,a+1+n);
		__int64 ans=0;
		for(int i=1;i<=n;i++){
			ans+=abs(a[i]-i);
		}
		cout<<ans<<endl;
			
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值