PTA10-排序6 Sort with Swap(0, i)

本文解析了在仅允许Swap(0,*)操作的情况下,如何通过找出排列中的环结构来确定最少交换次数对非负整数数组进行排序的方法。涉及单环处理、环中包含0元素与不包含0元素的计数策略。

PTA10-排序6 Sort with Swap(0, i)


原题链接
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
结尾无空行

分析

PPT为陈越姥姥的课的PPT
在这里插入图片描述
环有三种情况:
1.单环。
A[i]==i,元素在它所在的排序的位置上,不需要调动。

2.环里有n个元素,包括0,需要n-1次交换
如图,每个非0下标的值与0下标的值进行交换即可得到排序好的结果
在这里插入图片描述

3.环里有n个元素,不包括0,需要n+1从交换
(1)将0元素加入到该环中,具体而言,需要做交换A[0]和A[tail](tail为环的结尾下标)【1】
(2)每个非0下标的值与0下标的值进行交换即可得到排序好的结果,共有n+1个元素进行交换,需要交换【(n+1)-1】次
所以总共需要做1+(n+1)-1=n+1次
在这里插入图片描述

注意

1.0在单环里面,则不会出现在环中;若0不是单环那么肯定会出现在某一个环中
2.若0在单环里,没不会出现情况2,总的次数=求和ni+1*circle=count+circle(count为记录每个环中的元素个数的值)
3.寻找环的时候,没找到最后一个时,模拟排序交换

A[t]=t;//将当前位置设置成排序后的结果,不影响后续的循环

code

#include<iostream>
using namespace std;
int main(){
    int N,temp,flag=0,circle=0,single=0,count=0;//single表示单圆环,circle表示多圆环,count表示多圆环中元素个数
    scanf("%d",&N);
    int A[N];
    for(int i=0;i<N;i++){
        scanf("%d",&A[i]);
        if(A[i]==i){
            if(i==0){
                flag=1;//0在单环里面,则不会出现在环中;若0不是单环那么肯定会出现在某一个环中
            }
            single++;
        }
    }
    for(int i=0;i<N;i++){
        if(A[i]!=i){
            circle++;
            while(A[i]!=i){
                int t=i;
                i=A[i];
                A[t]=t;//将当前位置设置成排序后的结果,不影响后续的循环
                count++;
            }
        }
    }
    if(flag){//0在单环里
        printf("%d",circle+count);
    }else{
        printf("%d",N-single+circle-2);
    }
    return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值