问题 J: Derangement
时间限制: 1 Sec 内存限制: 128 MB
提交: 426 解决: 219
[提交] [状态] [讨论版] [命题人:admin]
题目描述
You are given a permutation p1,p2,…,pN consisting of 1,2,..,N. You can perform the following operation any number of times (possibly zero):
Operation: Swap two adjacent elements in the permutation.
You want to have pi≠i for all 1≤i≤N. Find the minimum required number of operations to achieve this.
Constraints
2≤N≤105
p1,p2,..,pN is a permutation of 1,2,..,N.
输入
The input is given from Standard Input in the following format:
N
p1 p2 .. pN
输出
Print the minimum required number of operations
样例输入
5 1 4 3 5 2
样例输出
2
提示
Swap 1 and 4, then swap 1 and 3. p is now 4,3,1,5,2 and satisfies the condition. This is the minimum possible number, so the answer is 2.
【题目大意】:
给你一个序列p,通过交换相邻的两个数字,使得序列里的数字与位置的编号不同,即 p[i] != i (下标从1开始),求最小的交换次数。
思路:
因为只能相邻的数字两两交换,要使得交换次数最小,数字与后一个交换即可。
用一个数组b来存需要交换的数字。
- 如果两个相邻的数字都需要交换,即abs(b[i]-b[i+1])=1,则交换一次就可以使两个数字满足要求,同时 i++,跳过下一个要交换的数b[i+1],因为已经满足要求了;
- 如果两个相邻数字仅一个要交换,则直接 交换次数+1 就行了;
- 如果b数组长度与n相等,即 整个序列都不满足条件,通过举例可以得到规律,
交换的次数是 :
- 当 n为偶数, ans = n/2;
- 当 n为奇数,ans = n/2+1;
代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int a[N];
int b[N];
int main()
{
int n;
while(cin >> n)
{
int ans = 0;
for(int i=1; i<=n; i++)
cin >> a[i];
int cnt = 0;
for(int i=1; i<=n; i++)
{
if(a[i] == i)
b[cnt++] = i;
}
if(cnt == n)
{
if(n%2 == 0)
cout << n/2 << endl;
else
cout << n/2+1 << endl;
continue;
}
else
{
for(int i=0; i<cnt; i++)
{
if(abs(b[i]-b[i+1]) == 1)
{
ans += 1;
i ++;
}
else
{
ans += 1;
}
}
}
cout << ans << endl;
}
return 0;
}
欢迎指正与交流