1067. Sort with Swap(0,*) (25)-PAT甲级真题(贪心算法)
2018-01-30 11:56
501 查看
1067. Sort with Swap(0,*) (25)-PAT甲级真题(贪心算法)
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 1
Sample Output:
9
此题使用贪心算法,思路是用0尽量和其他数字有效交换,(即把其他数字交换到最终位置上)即最优解,当0位于ind[0]时,选择一个尚未回到原位置的数与0交换,因为交换的是位置,可以对下标进行交换,使用ind数组记录每个数的下标ind[ind[0]]表示应该交换到当前0所在位置的那个数的位置。为了避免超时,设置全局辅助undo,表示尚未回到本位的那个数,可以从小到大的遍历,这样用于搜索undo整体时间复杂度为O(n).代码:
#include<cstdio> #include<iostream> #include<cstring> #include<string> #include<algorithm> #include<vector> #include<queue> #include<map> #include<set> using namespace std; int cnt = 0;//判断循环结束 const int maxn = 100010; int num[maxn],ind[maxn]; int main(){ freopen("in.txt","r",stdin); int n; cin>>n; int radix = 0; for(int i =0 ;i<n;i++){ scanf("%d",&num[i]); ind[num[i]] = i; if(num[i]!=i&&num[i]!=0)cnt++; if(num[i]==0)radix = i; } int ans = 0; int undo = 1;//从上次最小的那个地方找起 while(cnt>0&&undo<n){ if(ind[0]!=0){ swap(ind[ind[0]],ind[0]); cnt--; ans++; } else{ //while(undo<n){//法1 // if(ind[undo]!=undo){ // swap(ind[undo],ind[0]); // ans++; // break; // } // undo++; // } while(undo<n&&ind[undo]==undo)undo++;//法2 if(undo<n){ swap(ind[0],ind[undo]); ans++; } } } printf("%d\n",ans); return 0; }
相关文章推荐
- 1033. To Fill or Not to Fill (25)-PAT甲级真题(贪心算法)
- 1037. Magic Coupon (25)-PAT甲级真题(贪心算法)
- 1067. Sort with Swap(0,*) (25)-PAT甲级真题(贪心算法)
- PAT甲级真题及训练集(25)--1094. The Largest Generation (25)
- 1062. Talent and Virtue (25)-PAT甲级真题
- 1098. Insertion or Heap Sort (25)-PAT甲级真题(堆排序)
- 1021. Deepest Root (25)-PAT甲级真题(图的遍历,dfs,连通分量的个数)
- PAT甲级真题及训练集(18)--1097. Deduplication on a Linked List (25)
- 1093. Count PAT’s (25)-PAT甲级真题
- PAT甲级真题及训练集(26)--1106. Lowest Price in Supply Chain (25)
- 1040. Longest Symmetric String (25)-PAT甲级真题
- 1094. The Largest Generation (25)-PAT甲级真题(bfs,dfs,树的遍历)
- 1016. Phone Bills (25)-PAT甲级真题
- 1039. Course List for Student (25)-PAT甲级真题
- PAT甲级真题及训练集(16)--1032. Sharing (25)
- 1090. Highest Price in Supply Chain (25)-PAT甲级真题
- 1029. Median (25)-PAT甲级真题(two points)
- 1078. Hashing (25)-PAT甲级真题(二次方探查法)
- 1121. Damn Single (25)-PAT甲级真题
- PAT甲级真题及训练集(6)--1051. Pop Sequence (25)