数据结构 10-排序6 Sort with Swap(0, i) (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
题目的目的是 交换次序的公式
参考文章https://blog.csdn.net/qq_39339575/article/details/90343070
单元环 d
多元环 k
如果多元环不含0(flag==true) 交换次数为n-d+k;
如果多元环含0 (flag==false) 交换次数为n-d+k-2;
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main(){ int n; int temp; bool flag{false}; int d{0},k{0}; cin >> n; vector<int> list(n); for(int i=0;i<n;i++){ cin >> temp; list[i]=temp; } for(int i=0;i<n;i++){//单元环数量 if(list[i]==i){ d++; if(i==0)flag=true; } } for(int i=0;i<n;i++){//多元环的数量 if(list[i]!=i){ k++; while(list[i]!=i){ int temp=list[i]; list[i]=i; i=temp; } } } if(flag) cout << n-d+k<<endl;//无0的多元环 else{//有0的多元环 cout << n-d+k-2<<endl; } return 0; }