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
解题思路:permutation记录的是数字的排列,pos记录的是每个数字所在的位置,ans记录已经在最终位置的数字的个数,cnt记录交换次数。贪心法:尽可能保证每一次交换都能够让一个数字归位。
当ans==n:所有数字均已在自己的位置,结束
当ans<n&&数字0不在0处,为使得次数最少,要让数字0,与0所在位置本来应该在的位置交换。cnt每次这样交换后,一定至少加一,若0也恰好归位,则cnt加二
当ans<n&&数字在0处,为使得次数最少,要让数字0与第一个待归位的数交换,在寻找这个数的时候,一定要留意,为避免每次都从头开始找,我们可以直接从上次的值开始寻找。这样交换之后,cnt需要减一。
#include <iostream>
#include <vector>
using namespace std;
int n, cnt = 0, cur = 1, ans = 0;
int main(){
scanf("%d", &n);
vector<int>pos(n), val(n);
for(int i = 0; i < n; ++ i){
scanf("%d", &val[i]);
pos[val[i]] = i;
ans += (val[i] == i);
}
while(ans != n){
if(pos[0] == 0){
while(pos[cur] == cur)
++ cur;
swap(pos[0], pos[cur]);
swap(val[pos[0]], val[pos[cur]]);
-- ans;
}
else{
swap(pos[0], pos[pos[0]]);
swap(val[pos[0]], val[pos[pos[0]]]);
ans += (pos[0] == 0 ? 2 : 1);
}
++ cnt;
}
printf("%d", cnt);
}