置换 p 是整数 p1, p2, ..., pn 的有序集合,由 n 个不同的正整数组成,每个不超过 n。我们将置换 p 的第 i 个元素表示为 pi。我们将数字 n 称为排列 p1, p2, ..., pn 的大小或长度。
你有一个整数序列 a1, a2, ..., an。在一个动作中,您可以将任何数字减少或增加一。计算从该序列构建排列所需的最小移动次数。
输入
第一行包含整数 n (1 ≤ n ≤ 3·105) — 寻求排列的大小。第二行包含 n 个整数 a1, a2, ..., an ( - 109 ≤ ai ≤ 109)。
输出
打印一个数字——最小的移动次数。
请不要使用 %lld 说明符在 C++ 中读取或写入 64 位整数。最好使用 cin、cout 流或 %I64d 说明符。
例子
输入复制
2
3 0
输出复制
2
输入复制
3
-1 -1 2
输出复制
6
笔记
在第一个示例中,您应该将第一个数字减一,然后将第二个数字加一。得到的排列是 (2, 1)。
在第二个示例中,您需要 6 次移动来构建排列 (1, 3, 2)。
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- using namespace std;
- #define debug <<"qwq"<<
- #define fast ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
- typedef long long ll;
- const int N=4e5+10;
- const ll M=1e18+10;
- ll a[N],sum[N];
- priority_queue<int,vector<int>,greater<int> >pq;
- set<int>se;
- map<int,int>mp;
- queue<int>qu;
- vector<int>v;
- deque<int>de;
- struct Node
- {
- int x, y;
-
- }aaa[N];
- bool cmp(Node a,Node b)
- {
- if(a.x!=b.x)return a.x
//升序 - return a.y
- }
- int n,m,k,aa,bb;
- ll x;
- void solve()
- {
- cin>>n;
- for(int i=0;i
>a[i]; - sort(a,a+n);
- ll ans=0;
- if(a[n-1]>n)//最后一位最容易变成n
- {
- ans+=a[n-1]-n;
- a[n-1]=n;
- }
- else
- {
- ans=n-a[n-1];
- a[n-1]=n;
- }
- for(int i=n-1;i>=1;i--)//每项之间应该差1
- {
- if(a[i]>a[i-1]+1)
- {
- ans+=a[i]-a[i-1]-1;
- a[i-1]=a[i]-1;
- }
- {
- ans+=a[i-1]+1-a[i];
- a[i-1]=a[i]-1;
- }
- }
- cout<
- }
- int main()
- {
- int t=1;
- //cin>>t;
- while(t--)
- {
- solve();
- }
- }
-
相关阅读:
数据库系统原理与应用教程(061)—— MySQL 练习题:操作题 21-31(五)
vue+element如何实现可编辑表格?
【信创】 JED on 鲲鹏(ARM) 调优步骤与成果 | 京东云技术团队
LeetCode 0174. 地下城游戏
2022上海省赛(A,E,G,H,M,N)
Android 错把setLayerType当成硬件加速
Java中java.util.Arrays参考指南
FastDFS(分布式文件系统)使用介绍
使用vue自定义实现Tree组件和拖拽功能
洛谷 P3588 【[POI2015]PUS】题解
-
原文地址:https://blog.csdn.net/qq_62079079/article/details/126541349