当前位置:网站首页>2021-3-23-美团-正则序列
2021-3-23-美团-正则序列
2022-07-17 00:02:00 【茴薏】
题目描述:
我们称一个长度为n的序列为正则序列,当且仅当该序列是一个由1~n组成的排列,即该序列由n个正整数组成,取值在[1,n]范围,且不存在重复的数,同时正则序列不要求排序
有一天小团得到了一个长度为n的任意序列,他需要在有限次操作内,将这个序列变成一个正则序列,每次操作他可以任选序列中的一个数字,并将该数字加一或者减一。
请问他最少用多少次操作可以把这个序列变成正则序列?
输入描述:
输入第一行仅包含一个正整数n,表示任意序列的长度。(1<=n<=20000)
输入第二行包含n个整数,表示给出的序列,每个数的绝对值都小于10000。
输出描述:
输出仅包含一个整数,表示最少的操作数量。
示例1
输入
5
-1 2 3 10 100
输出
103
//贪心算法,我们要让每一个数字移动的步数最少,
//或者说让每个数字找[1,n]最近的坑位填
//我们可以先排序,然后将所有的数字按照[1,n]的坑位从小到大填
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> vecNums;
int nTemp = 0;
for (int i = 0; i < n; i++)
{
cin >> nTemp;
vecNums.push_back(nTemp);
}
sort(vecNums.begin(), vecNums.end());
int k = 1;
int ans = 0;
for (int i = 0; i < n; i++)
{
ans += abs(k - vecNums[i]);
k++;
}
cout << ans << endl;
return 0;
}
边栏推荐
- “husky install“ command already exists in prepare script, skipping./Users/982471938qq.com/Desktop
- Which is the best bag grabbing tool (violent theft foreplay)
- 1.两数之和
- By voting for the destruction of STI by Dao, seektiger is truly community driven
- 华为云服务器
- 在mysql数据库插入中文值出现的乱码解决
- (零七)Flask有手就行——初识数据库(Flask-SQLAlchemy)
- Vite3.0 release
- Go BitSet of one library per day
- [MySQL] Error 1130 problem solution
猜你喜欢

cmd中文乱码解决方案

Switch and router technology: Integrated Experiment of hot backup routing protocols HSRP, HSRP and spvstp

Press and hold day 27: Service
![[MariaDB] solution: error 1045 (28000): access denied for user 'root' @ 'localhost' (using password: yes)](/img/a6/410d81ad374e32e5cabd2eb242a183.png)
[MariaDB] solution: error 1045 (28000): access denied for user 'root' @ 'localhost' (using password: yes)

利用 Redis 的 sorted set 做每周热评的功能

Leetcode 242: valid Letter ectopic words

面试官:怎么不用定时任务实现关闭订单?

64 bit interrupt assembly cannot be used

高等数学---第八章多元函数微分学---多元函数的极值与最值

异步编程&协程
随机推荐
UVA11362 Phone List 题解
如何解决图神经网络过相关?一个IBM的新视角!
Food chain (DFS memorization)
JSP basic grammar experiment
12. Integer to Roman numerals ●●
玩转CSDN编辑器
并查集
深入详细理解矩阵 (矩阵的加减乘、转置、共轭、共轭转置)
[MariaDB] solution: error 1045 (28000): access denied for user 'root' @ 'localhost' (using password: yes)
2022年3月盗取微软源代码的 APT组织 lapsus$完整资料汇总
[Clickhouse] calculation of weeks
Photoshop网页设计教程
ROS 通信机制进阶
[daily training] sword finger offer II 041 Average value of sliding window
“husky install“ command already exists in prepare script, skipping./Users/982471938qq.com/Desktop
How to solve the over correlation of graph neural network? A new perspective of IBM!
QT打开外部程序并嵌入Qt界面
[Linux] release jar package, dynamically view logs, view program progress, and end programs
【著色器實現Wave效果_Shader效果第一篇】
How to right-click to create a servlet in the idea development servlet project