博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Codeforces Round #175 (Div. 2) C. Building Permutation(贪心)
阅读量:6702 次
发布时间:2019-06-25

本文共 2263 字,大约阅读时间需要 7 分钟。

C. Building Permutation
time limit per test
2 seconds
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 С++. It is preferred to use the cin, cout streams or the %I64d specifier.

Sample test(s)
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).

思路:对于若a[i]满足0<a[i]<=n,则标记tag[a[i]]=1,否则tag[a[i]]=1.对于集合A={a[i]|a[i]<=0 || a[i]>n},进行不降序排列,集合B=[1,n]-{a[i]|0<a[i]<=n}也不降序排列,A中元素转化为B中位置对应相同的元素。

AC Code:

1 #include 
2 #include
3 #include
4 #include
5 #include
6 #include
7 #include
8 #include
9 #include
10 #include
11 #include
12 #include
13 #include
14 using namespace std;15 #define ll long long16 #define cti const int17 #define ctll const long long18 #define dg(i) cout << '*' << i << endl;19 20 int p[300002], pi;21 bool tag[300002];22 23 int main()24 {25 int n, x;26 ll cnt;27 while(scanf("%d", &n) != EOF)28 {29 memset(tag, false, sizeof(tag));30 pi = 0;31 for(int i = 0; i < n; i++)32 {33 scanf("%d", &x);34 if(x < 1 || x > n || tag[x]) p[pi++] = x;35 else tag[x] = true;36 }37 sort(p, p + pi);38 cnt = 0;39 for(int i = 0, j = 1; i < pi; i++, j++)40 {41 while(tag[j]) j++;42 cnt += (ll)abs(p[i] - j);43 }44 printf("%I64d\n", cnt);45 }46 return 0;47 }

 

转载地址:http://qbgoo.baihongyu.com/

你可能感兴趣的文章
swift实现ios类似微信输入框跟随键盘弹出的效果
查看>>
MySQL索引背后的数据结构及算法原理
查看>>
Linq之group子句
查看>>
jQuery图片轮播特效
查看>>
【转】人生应该接受的教育
查看>>
键盘收回方法
查看>>
docker 使用教程(2)常用命令
查看>>
在Java中>、>>、>>>三者的区别
查看>>
Android 手机卫士--home界面布局
查看>>
Android NDK 同时编译多个Module
查看>>
poi API
查看>>
8 -- 深入使用Spring -- 2...2 指定Bean的作用域
查看>>
MapReduce实战(一)自定义类型
查看>>
切换横屏幕 onCreate 多次执行问题
查看>>
A guide to analyzing Python performance
查看>>
export,source
查看>>
Android添加全屏启动画面
查看>>
6月最后一天
查看>>
使用注解校验参数
查看>>
CSU1256 天朝的单行道(spfa)
查看>>