PAT甲级练习1067. Sort with Swap(0,*) (25)
来源:互联网 发布:怎么找淘宝主播合作 编辑:程序博客网 时间:2024/05/21 10:58
1067. Sort with Swap(0,*) (25)
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 (<=105) 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 1Sample Output:
9
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <map> #include <set> #include <stack> #include <queue> #include <string> #include <string.h> using namespace std;const int MAX = 1e5+10;int n, num, an, cnt, ind=1, l[MAX];int main() {scanf("%d", &n);for(int i=0; i<n; i++){scanf("%d",&num);l[num] = i;if(i!=num && num!=0) an++;}while(an>0){if(l[0]==0){//零在第零个位置while(ind<n){if(l[ind]!=ind){swap(l[ind], l[0]);cnt++;break;}ind++;}}while(l[0]!=0){swap(l[l[0]], l[0]);cnt++;an--;}}printf("%d", cnt);scanf("%d",&n); return 0;}
- PAT甲级练习1067. Sort with Swap(0,*) (25)
- 【PAT甲级】1067. Sort with Swap(0,*) (25)
- 1067. Sort with Swap(0,*) (25) PAT甲级
- PAT甲级.1067. Sort with Swap(0,*) (25)
- PAT甲级1067. Sort with Swap(0,*) (25)
- PAT 甲级 1067. Sort with Swap(0,*) (25)
- 1067. Sort with Swap(0,*) (25)-PAT甲级真题(贪心算法)
- pat 1067. Sort with Swap(0,*) (25)
- PAT 1067. Sort with Swap(0,*) (25)
- 【PAT】1067. Sort with Swap(0,*) (25)
- pat-1067. Sort with Swap(0,*) (25)
- 【PAT】1067. Sort with Swap(0,*)
- PAT|1067. Sort with Swap(0,*)
- PAT 1067. Sort with Swap(0,*)
- 【PAT】1067. Sort with Swap(0,*)
- pat 1067 Sort with Swap(0,*) (25)
- PAT 1025Sort with Swap(0,*) (25)
- pat-a1067. Sort with Swap(0,*) (25)
- 正则表达式整理
- 分辨率分布统计入口
- 设计模式之策略模式
- EasyUI组件使用
- 深入。NET 第六章上机2+3
- PAT甲级练习1067. Sort with Swap(0,*) (25)
- 蚂蚁分类信息系统 5.8 修改蚂蚁分类信息系统手机端信息图片浏览方式,自动轮播,带当前图片数字和张数,支持放大浏览
- win10系统安装ADS2016
- 大家注意了 这个人是骗子微信 p6666999999 骗子 15982880381 骗子 13880129670 骗子 jishujieda12 骗子
- 328. Odd Even Linked List
- ASP.NET MVC5 实现分页查询
- jvisualvm 连linux下的应用程序(tomcat)
- JRE 和 JDK
- 关于模型抖动解决方案