1067. Sort with Swap(0,*) (25)-PAT甲级真题(贪心算法)

1067. Sort with Swap(0,*) (25)-PAT甲级真题(贪心算法)

Sort with Swap(0,*) (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


此题使用贪心算法,思路是用0尽量和其他数字有效交换,(即把其他数字交换到最终位置上)即最优解,当0位于ind[0]时,选择一个尚未回到原位置的数与0交换,因为交换的是位置,可以对下标进行交换,使用ind数组记录每个数的下标ind[ind[0]]表示应该交换到当前0所在位置的那个数的位置。为了避免超时,设置全局辅助undo,表示尚未回到本位的那个数,可以从小到大的遍历,这样用于搜索undo整体时间复杂度为O(n).代码:


#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<vector>
#include<queue>
#include<map>
#include<set>
using namespace std;
int cnt = 0;//判断循环结束 
const int maxn = 100010;
int num[maxn],ind[maxn];
int main(){
    freopen("in.txt","r",stdin);
    int n;
    cin>>n;
    int radix = 0;
    for(int i =0 ;i<n;i++){
        scanf("%d",&num[i]);
        ind[num[i]] = i;
        if(num[i]!=i&&num[i]!=0)cnt++;
        if(num[i]==0)radix = i;

    } 
    int ans = 0;
    int undo = 1;//从上次最小的那个地方找起
    while(cnt>0&&undo<n){
        if(ind[0]!=0){
            swap(ind[ind[0]],ind[0]);
            cnt--;
            ans++;
        }
        else{
            //while(undo<n){//法1
//              if(ind[undo]!=undo){
//                  swap(ind[undo],ind[0]);
//                  ans++;
//                  break;
//              }
//              undo++;
//          }
        while(undo<n&&ind[undo]==undo)undo++;//法2
            if(undo<n){
            swap(ind[0],ind[undo]);
            ans++;
            }
        }

    } 
    printf("%d\n",ans);
    return 0;

}

猜你喜欢

转载自blog.csdn.net/xiyuan1223/article/details/79204273
今日推荐