Source:

PAT A1067 Sort with Swap(0, i) (25 分)

Description:

Given any permutation of the numbers {0, 1, 2,..., N−1}, it is easy to sort them in increasing order. But what if Swap(0, *) is the ONLY operation that is allowed to use? For example, to sort {4, 0, 2, 1, 3} we may apply the swap operations in the following way:

Swap(0, 1) => {4, 1, 2, 0, 3}
Swap(0, 3) => {4, 1, 2, 3, 0}
Swap(0, 4) => {0, 1, 2, 3, 4}

Now you are asked to find the minimum number of swaps need to sort the given permutation of the first N nonnegative integers.

Input Specification:

Each input file contains one test case, which gives a positive N (≤) followed by a permutation sequence of {0, 1, ..., N−1}. All the numbers in a line are separated by a space.

Output Specification:

For each case, simply print in a line the minimum number of swaps need to sort the given permutation.

Sample Input:

10
3 5 7 2 6 4 9 0 8 1

Sample Output:

9

Keys:

Code:

 /*
Data: 2019-07-22 19:54:12
Problem: PAT_A1067#Sort with Swap(0, i)
AC: 29:14 题目大意:
排序,只能交换0和任意其他数,给出需要的最少步数 基本思路:
1.0在几号位就跟相应的数字换位置,每次操作可以将一个数字归位;
2.若0回到了0号位,则再与任意一个不在自己位置上的数字交换;
3.重复第一步,直至所有数字都归位;
*/ #include<cstdio>
#include<algorithm>
using namespace std;
const int M=1e5+;
int pos[M]; int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("Test.txt", "r", stdin);
#endif int n,num,left=,cnt=,st=;
scanf("%d", &n);
for(int i=; i<n; i++)
{
scanf("%d", &num);
pos[num]=i;
if(num!=i && num!=)
left++;
}
while(left!=)
{
if(pos[]==){
for(int i=st; i<n; i++){
if(pos[i]!=i){
swap(pos[],pos[i]);
st=i;break;
}
}
cnt++;
}
swap(pos[],pos[pos[]]);
cnt++;
left--;
}
printf("%d", cnt); return ;
}

最新文章

  1. 【C#】MVC项目中搭建WebSocket服务器
  2. [C#对Oracle操作]C#操作调用Orcale存储过程有参数
  3. POJ 2031 Building a Space Station
  4. win10 + VS2015 + EF6 + MySQL
  5. mysql创建/删除表的例子
  6. tornado解析http body的过程分析
  7. ReactNative 踩坑小计
  8. sharedevelop iis express
  9. IPAD之分割视图 SplitViewController
  10. Robot Framework自动化测试(二)第一个用例
  11. Day04 - Python 迭代器、装饰器、软件开发规范
  12. ashx页面中context.Session[&quot;xxx&quot;]获取不到值的解决办法
  13. hdu1507 Uncle Tom&#39;s Inherited Land* 二分匹配
  14. Java 第二周总结
  15. Lab 10-2
  16. Git Extensions 和 Tortoisegit 到底是什么?Git For VS(Git For Visual Studio)(Visual Studio 中使用 Git)
  17. VAE (variational autoencoder)
  18. LINQ 查询
  19. C# ListView用法
  20. DLL入门

热门文章

  1. php把网络图片转Base64编码。(php将图片链接直接转化为base64编码)
  2. MySQL 时间戳与日期格式的相互转换(转)
  3. CSS3 resize 属性
  4. 关于char(M)和varchar(N)的区别
  5. Sqlplus常用指令
  6. python之路——操作系统的发展史
  7. mySQL单表限制大小
  8. mySQL学习入门教程——2.创建表
  9. 针对利用tzselect修改时间及ln -sf 修改系统时间不好使的情况 linux 6.5
  10. glog 与 zlog