Derangement(AtCoder-3525)
Problem Description
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.
Input
The input is given from Standard Input in the following format:
N
p1 p2 .. pNOutput
Print the minimum required number of operations
Example
Sample Input 1
5
1 4 3 5 2Sample Output 1
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.Sample Input 2
2
1 2Sample Output 2
1
Swapping 1 and 2 satisfies the condition.Sample Input 3
2
2 1Sample Output 3
0
The condition is already satisfied initially.Sample Input 4
9
1 2 4 9 5 8 7 3 6Sample Output 4
3
题意:给出一个长度为 n 的序列 a,序列中的数分别为 1~n,现在可以对序列中相邻元素进行交换,问最少交换多少次能使得 ai≠i
思路:从前向后扫一遍记录是否需要交换即可
Source Program
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<bitset>
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD = 1E9+7;
const int N = 100000+5;
const int dx[] = {-1,1,0,0,-1,-1,1,1};
const int dy[] = {0,0,-1,1,-1,1,-1,1};
using namespace std;
int a[N];
int main() {
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
int res=0;
for(int i=1;i<=n-1;i++){
if(a[i]==i){
swap(a[i],a[i+1]);
res++;
}
}
if(a[n]==n)
res++;
printf("%d\n",res);
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】