Source:
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:
1 /* 2 Data: 2019-07-22 19:54:12 3 Problem: PAT_A1067#Sort with Swap(0, i) 4 AC: 29:14 5 6 题目大意: 7 排序,只能交换0和任意其他数,给出需要的最少步数 8 9 基本思路: 10 1.0在几号位就跟相应的数字换位置,每次操作可以将一个数字归位; 11 2.若0回到了0号位,则再与任意一个不在自己位置上的数字交换; 12 3.重复第一步,直至所有数字都归位; 13 */ 14 15 #include<cstdio> 16 #include<algorithm> 17 using namespace std; 18 const int M=1e5+10; 19 int pos[M]; 20 21 int main() 22 { 23 #ifdef ONLINE_JUDGE 24 #else 25 freopen("Test.txt", "r", stdin); 26 #endif 27 28 int n,num,left=0,cnt=0,st=0; 29 scanf("%d", &n); 30 for(int i=0; i<n; i++) 31 { 32 scanf("%d", &num); 33 pos[num]=i; 34 if(num!=i && num!=0) 35 left++; 36 } 37 while(left!=0) 38 { 39 if(pos[0]==0){ 40 for(int i=st; i<n; i++){ 41 if(pos[i]!=i){ 42 swap(pos[0],pos[i]); 43 st=i;break; 44 } 45 } 46 cnt++; 47 } 48 swap(pos[0],pos[pos[0]]); 49 cnt++; 50 left--; 51 } 52 printf("%d", cnt); 53 54 return 0; 55 }