【PAT】1067. 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.

翻译:给你 {0, 1, 2,…, N-1}的任意一种排列,将它们按照升序排列是很简单的。但是如果只允许通过交换Swap(0, *) 的方式来进行排序呢?举个例子,为了排列{4, 0, 2, 1, 3} ,我们可以通过以下方式交换:

Swap(0, 1) => {4, 1, 2, 0, 3}
Swap(0, 3) => {4, 1, 2, 3, 0}
Swap(0, 4) => {0, 1, 2, 3, 4}

现在你需要找出排序给定的N个非负整数序列的最少交换次数。

INPUT FORMAT

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.

翻译:每个输入文件包含一组测试数据,给你一个正整数N(<=10^5)跟着一个{0, 1, …, N-1}的数列。一行内所有数字之间用空格隔开。

OUTPUT FORMAT

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


解题思路

这道题是一道数学题,假设a个数之间可以通过相互交换归位,我称之为一个子集合,子集合交换情况分为两种可能,一种是包括0的,一种是不包括0的,包括0的子集合中的k个数可以通过k-1次交换得到,而不包括0的子集合中的k个数可以通过k+1次交换得到(手动模拟一下就可以发现)。由于包括0的子集合最多一个,所以可以直接假设每个集合都是第二种,再通过0在输入时是否在0位上来判断是否需要减2。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<algorithm>
#define INF 99999999
using namespace std;
int N,d[100010],v[100010];
int ccount=0;
int dfs(int a){
    int circu=1;
    int temp=d[a];
    while(temp!=a){
        v[temp]=1;
        temp=d[temp];
        circu++;
    }
    v[temp]=1;
    return circu;
}
int main(){
    scanf("%d",&N);
    for(int i=0;i<N;i++){
        scanf("%d",&d[i]);
        if(d[i]==i)v[i]=1;
        if(i==0&&d[0]==0)v[0]=1,ccount+=2;
    }
    for(int i=0;i<N;i++){
        if(!v[i])ccount+=dfs(i)+1;
    }
    printf("%d\n",ccount-2);
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值