PAT 1067 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 (≤10
​5
​​ ) 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

以下是自己在pad上画的一个案例
自己在pad上画的

以下是AC代码:

#include<iostream>
#include<cmath>
#include<cstring>
#include<string>
#include<cstdio>
#include<ctime>
#include<algorithm>
#include<iterator>
#include<vector>
#include<stack>
#include<set>
#include<queue>
#include<map>
#include<utility>
using namespace std;
const int N=1e5+2;
int n;
int pos[N]; //pos[i] 表示数字i 在序列中的位置
int main()
{
	ios::sync_with_stdio(false);
    while(cin>>n){
        int num=0;//记录除了0以外不在本位上的数【手推一次即可看出】
        int ans=0;
        int x;
        for(int i=0;i<n;i++){
            cin>>x;
            pos[x]=i;
            if(pos[i]!=i){      //变成if(x!=0&&pos[i]!=i)  竟会有一个案例过不了??!!!
                num++;  //不在本位的数
            }
        }
        //num--;  //否则排好序后num仍然为1
        int exchange=1;
        while(num>0){
            if(pos[0]==0){//如果0在0号位置上
                //随意选择一个没有在本位的数进行交换,由于是随意,但是每次
                //都用一个for循环来找第一个不在本位的数会超时,所以利用每个移回本位的数在后续
                //操作中不再移动的特点,定义一个exchange来表示目前序列中不在本位上的最小数(初始化1)
                while(exchange<n){
                    if(pos[exchange]!=exchange){
                        swap(pos[0],pos[exchange]); //将0与exchange 交换位置
                        ans++;
                        break;
                    }
                    exchange++;
                }
            }else{
                while(pos[0]!=0){
                    swap(pos[0],pos[pos[0]]);
                    //   swap(3,4)            pos[0]=3       pos[3]=4
                    ans++;
                    num--;
                }
            }
        }
        cout<<ans<<endl;
       
    }
    system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值