Gym 100971B 水&愚

Description

standard input/output
Announcement
 
  • Statements

    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.

Sample Input

Input
6
6 2 4 3 5 1
Output
1
2 5

题意:使得i!=pi 移动最少的次数 并输出的交换的两者的位置

题解:找到需要交换的所谓的位置 若个数为偶数,则直接两两交换
若为奇数 则最后一个和前一个位置交换
当为的第一个位置时 注意特判。
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int n;
 4 int a[200005];
 5 //int where[200005];
 6 int aa[200005];
 7 int main()
 8 {
 9     scanf("%d",&n);
10     for(int i=1;i<=n;i++)
11         {
12             scanf("%d",&a[i]);
13             //where[a[i]]=i;
14         }
15     int ans=0;
16     for(int i=1;i<=n;i++)
17     {
18         if(a[i]==i)
19         {
20             ans++;
21             aa[ans]=i;
22         }
23     }
24     if(ans%2==0)
25     {
26         cout<<ans/2<<endl;
27         for(int i=1;i<ans;i+=2)
28         cout<<aa[i]<<" "<<aa[i+1]<<endl;
29     }
30     else
31     {
32         cout<<ans/2+1<<endl;
33         for(int i=1;i<ans;i+=2)
34         cout<<aa[i]<<" "<<aa[i+1]<<endl;
35         if(aa[ans]==1)
36             cout<<"1 2"<<endl;
37         else
38             cout<<aa[ans]-1<<" "<<aa[ans]<<endl;
39     }
40     return 0;
41 }

#include<bits/stdc++.h>
using namespace std;
int n;
int a[200005];
//int where[200005];
int aa[200005];
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            //where[a[i]]=i;
        }
    int ans=0;
    for(int i=1;i<=n;i++)
    {
        if(a[i]==i)
        {
            ans++;
            aa[ans]=i;
        }
    }
    if(ans%2==0)
    {
        cout<<ans/2<<endl;
        for(int i=1;i<ans;i+=2)
        cout<<aa[i]<<" "<<aa[i+1]<<endl;
    }
    else
    {
        cout<<ans/2+1<<endl;
        for(int i=1;i<ans;i+=2)
        cout<<aa[i]<<" "<<aa[i+1]<<endl;
        if(aa[ans]==1)
            cout<<"1 2"<<endl;
        else
            cout<<aa[ans]-1<<" "<<aa[ans]<<endl;
    }
    return 0;
}

原文地址:https://www.cnblogs.com/hsd-/p/5662087.html