gym100971B



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.

Input

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.

Output

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.

Example
Input
6
6 2 4 3 5 1
Output
1
2 5
直接遍历就好了
ac代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int a[1000005];
int main()
{
    int n;
    while(cin>>n)
    {
        int sum=0;
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            if(a[i]==i)
            {
                sum++;
            }
        }
        if(sum%2==0)
        cout<<sum/2<<endl;
        else
        cout<<sum/2+1<<endl;
        int ans=0;
        int p;
        for(int i=1;i<=n;i++)
        {
           if(a[i]==i)
           {
               ans++;
               if(ans==2)
               {
                   printf("%d %d\n",p,i);
                   int tmp=a[p];
                   a[p]=a[i];
                   a[i]=tmp;
                   ans=0;
               }
               else
               p=i;
           }
        }
        if(sum%2!=0)
        {
           for(int i=1;i<=n;i++)
           {
               if(a[i]!=i)
               {
                   printf("%d %d\n",i,p);
                   break;
               }
           }
        }
    }
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值