SDUT 2021 Winter Individual Contest - N(B-Derangement)

B - Derangement

题目链接: link.
原题描述:
A permutation of n numbers is a sequence of integers from 1 to n where each number is occurred exactly once. If a permutation p1, p2, …, pn has an index i such that pi = i, this index is called a fixed point.

A derangement is a permutation without any fixed points.

Let’s denote the operation swap(a, b) as swapping elements on positions a and b.

For the given permutation find the minimal number of swap operations needed to turn it into derangement.
The first line contains an integer n (2 ≤ n ≤ 200000) — the number of elements in a permutation.

The second line contains the elements of the permutation — n distinct integers from 1 to n.
In the first line output a single integer k — the minimal number of swap operations needed to transform the permutation into derangement.

In each of the next k lines output two integers ai and bi (1 ≤ ai, bi ≤ n) — the arguments of swap operations.

If there are multiple possible solutions, output any of them.
样例

输入
6
6 2 4 3 5 1
输出
1
2 5

题目大意为给你1-n个数,这一串数不能让a[i]=i,类似于错排 。碰到a[i]=i的时候要和其他数进行交换,使其满足a[i]!=i。这道题的坑比较多,测试点也很多。要考虑总数,比如奇数的时候,可能会出现单的情况,这时候就只需判断这个数是不是1,如果是则把这个数和最开始的数交换(只写出一种交换情况就行),不是1的话直接把它和1交换即可。那么若一共偶数个的话,就两两交换即可。

代码如下:

#include <bits/stdc++.h>
using namespace std;
const int N=200001;
int a[N],b[N];
int main()
{
    int n,j=0;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
        if(a[i]==i) b[j++]=a[i];//将不满足条件的存入一个新数组中
    }
    cout<<(j+1)/2<<endl;
    for(int i=0;i+1<j;i=i+2)
    {
        printf("%d %d\n",b[i],b[i+1]);
    }
    if(j&1)//二进制判断是否为奇数,运行时间会更短
    {
        if(b[j-1]!=1)
        printf("%d 1\n",b[j-1]);
        else printf("%d %d\n",b[j-1],n);
    }

   return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值