PAT(Advanced) 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.

解答:

该题我刚开始始终不太理解,后来自己用笔模拟了一下过程有了比较清晰的思路。

即,用0和这个位置上本应该存在的数交换,如果0在过程中被换到了0位置上,而还存在其他没有换的数,那么将0和其他未换的随机一个数进行交换,使交换过程继续进行 ,使得最后序列有序。

但是,如果用一个数组存储初始序列,下标i对应输入的第i个数时,应该也可以解决问题,但是N <= 10^5让我们警惕,即可能出现超时情况,因此我们可以利用输入数的唯一性,将输入数作为下标,数组中存储位置信息i,这样便省去了O(n)查找的麻烦。

AC代码如下:

#include<iostream>
#include<cstdio>
#include<vector>

using namespace std;

int main()
{
	int n, val, ans = 0, count = 0, index = 1;
	
	scanf("%d", &n);
	vector<int> loc(n);
	
	for(int i = 0; i < n; i++)
	{
		scanf("%d", &val);
		loc[val] = i;
		if(val != i && val != 0) 
			count++;
	}
	
	while(count)
	{
		if(loc[0] == 0)
		{
			while(index < n)
			{
				if(loc[index] != index)
				{
					swap(loc[index], loc[0]);
					ans++;
					break;
				}
				index++;
			}
		}
		while(loc[0] != 0)
		{
			swap(loc[loc[0]], loc[0]);
			ans++;
			count--;
		}
	}

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值