Title Address
https://pta.patest.cn/pta/test/16/exam/4/question/678
5-16 Sort with Swap (0, I) (25 points)
Given any permutation of the numbers {0, 1, 2,..., N-1N? 1}, it is an easy-to-sort them in increasing order. But what if was the only operation that was allowed to use Swap(0, *)
? For example, to sort {4, 0, 2, 1, 3} We'll apply the swap operations in the following:
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 is asked to find the minimum number of swaps need to sort the given permutation of the first nN nonne gative integers.
Input Specification:
Each input file contains one test case, which gives a positiveNN\le 10^5< Span class= "base textstyle uncramped" >≤10?5??) followed by a permutation sequence of {0, 1, ..., n-1n? 1}. All the numbers in a line is 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:
103 5 7 2 6 4 9 0 8 1
Sample Output:
9
/* Evaluation result time result score Topic compiler spents (MS) memory (MB) User 2017-07-07 11:35 answer correct 255-16g++242 test point results Score/out of Use (MS) memory (MB) test point 1 answer correct 15/ 1521 Test point 2 answer correct 3/3242 test point 3 answer correct 3/3121 test point 4 answer correct 2/221 test point 5 answer correct 1/121 test point 6 answer correct 1/121 a bit tricky topic, MOOC, mainly looking for sort of ring. There are 0 cycles of n-1, no 0 ring for n+1 built three arrays, a is the number of storage, B is where I put the element placed in which position, checked is put this element has not been visited. Pit: You must add a global variable to do a memo for the start of the search function, or the search function repeatedly calls will cause a timeout */#include <stdio.h> #define MAXN 100000int a[maxn],b[maxn],checked[ Maxn];int gfindbeginposition=0;int findunchecked (int N) {int i;for (i=gfindbeginposition;i<n;i++) {if (! Checked[i]) return gfindbeginposition=i;} return-1;} int main () {int i,n,p,sum;int ringcount=0;int ncount=0;int zeroinposition=0;scanf ("%d", &n); for (i=0;i<n;i++) { scanf ("%d", &a[i]); B[a[i]]=i;} if (a[0]==0) Zeroinposition=0;elsezeroinposition=-2;while ((p=findunchecked (N)) +1) {checked[p]=1;if (A[p]!=p) nCount ++;else Continue;while (! CHECKED[B[P]]) {p=b[p]; checked[p]=1;ncount++;} ringcount++;} sum=ncount+ringcount+zeroinposition;printf ("%d", sum);}
PTA 10-sorting 6 sort with Swap (0, i) (25 min)