标签:
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
思路:输入的时候存储方式改变一下,这样比较好移动,此题比较有特点。
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 #define MAX 100010 5 int data[MAX]; 6 int main(int argc, char *argv[]) 7 { 8 int N; 9 int step=0; 10 scanf("%d",&N); 11 int index; 12 int min=1; 13 int leave=N-1; 14 for(int i=0;i<N;i++) 15 { 16 int num; 17 scanf("%d",&num); 18 data[num]=i; 19 } 20 for(int i=1;i<N;i++) 21 { 22 if(data[i]==i) 23 { 24 leave--; 25 } 26 27 } 28 while(leave>0) 29 { 30 if(data[0]!=0) 31 { 32 leave--; 33 int temp=data[data[0]]; 34 data[data[0]]=data[0]; 35 data[0]=temp; 36 step++; 37 if(leave<=0) 38 break; 39 } 40 else 41 { 42 while(data[min]!=min) 43 { 44 int temp=data[min]; 45 data[min]=data[0]; 46 data[0]=temp; 47 step++; 48 break; 49 } 50 min++; 51 } 52 } 53 printf("%d\n",step); 54 return 0; 55 }
标签:
原文地址:http://www.cnblogs.com/GoFly/p/4293655.html