文章标题 Gym100971B :Derangement
来源:互联网 发布:mac电脑开机问号文件夹 编辑:程序博客网 时间:2024/05/01 16:19
Derangement
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.
Examples
Input
6
6 2 4 3 5 1
Output
1
2 5
题意:给你一数字的序列,有n个数,1~n,然后要求每个位置与他们的权值不一样,一样的话就得交换,问要将所有的位置和权值的通过交换变成位置和权值不一样的。问最少的交换次数,然后把每次交换的数给列出来
分析:先将位置和权值一样的给找出来,个数为ans。然后如果ans为偶数,则需要ans/2次,奇数需要ans/2+1次。然后将操作的给列出来。
代码:
#include<iostream>#include<string>#include<cstdio>#include<cstring>#include<vector>#include<math.h>#include<map>#include<queue> #include<algorithm>using namespace std;const int inf = 0x3f3f3f3f;int n;int a[200005];int main (){ while (scanf ("%d",&n)!=EOF){ for (int i=1;i<=n;i++){ scanf ("%d",&a[i]); } vector <int> v; for (int i=1;i<=n;i++){ if (a[i]==i){ v.push_back(i);//记录权值和位置一样的 } } int ans=v.size(); if (ans%2==0){ printf ("%d\n",ans/2); int k=0; for (int i=0;i<ans/2;i++){ printf ("%d %d\n",v[k++],v[k++]); } } else if (ans==1){ printf ("1\n"); for (int i=1;i<=n;i++){ if (i!=v[0]){ printf ("%d %d",i,v[0]); break; } } } else { int k=0; printf ("%d\n",ans/2+1); for (int i=0;i<ans/2-1;i++){ printf ("%d %d\n",v[k++],v[k++]); } printf ("%d %d\n",v[k],v[k+1]); printf ("%d %d\n",v[k],v[k+2]); } } return 0;}
- 文章标题 Gym100971B :Derangement
- gym100971B
- 文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题 文章标题 文章标题 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- Leetcode 95. Unique Binary Search Trees II (Medium) (cpp)
- 【Easy】88. Merge Sorted Array
- BZOJ 1024 SCOI2009 生日快乐 暴搜
- Liberty版本Neutron LBaas学习
- mysql 数设置据库编码及避免导入乱码问题
- 文章标题 Gym100971B :Derangement
- 【Hard】23. Merge k Sorted Lists
- 火车硬座车厢座位分布表
- 如何在 CentOS 7 用 cPanel 配置 Nginx 反向代理
- codeforcse基础题——#357(div2)C
- 送给大一新生的一些话
- 简单记事本的实现(JAVA)
- Android Logger 日志框架源码分析
- Java控制小数位,获得随机数