PAT 1067 Sort with Swap(0, i) 脚标与数组的关系 运行超时问题 燚

版权声明:哈哈 你能采纳 我很开心 https://blog.csdn.net/m0_38090681/article/details/84452843

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

题目大意:给定n个数[0,n-1],只允许交换元素0(非脚标)与其他元素,问最少交换多少次能使这个序列递增。

基本思路(有两个测试样例超时):1.因为元素位0~n-1,刚好与数组下标相对应,假设0元素所在下标位i,元素i的下标为j,数组为array,于是可以将 array[i]与array[j]交换,然后更新0元素下标为j,假如0元素的下标为0,则遍历数组找到第一个array[k]!=k

的元素,然后将array[k]与array[i]交换,之后重复以上过程,直至遍历数组时k==n时说明排序完毕。(因为每次都要查找元素array[j],所以遍历开销较大,超时)

优化后的思路:运用对称性,array[i]中存储元素a ,可理解为a元素占据了i的位置即array[a]==i。将要交换的元素变为数组的角标,可利用数组的随机存储性,在常数时间内找到钥交换的元素,这样就能解决超时问题。(关于数组与脚标的关系,可阅读《剑指offer》c++版第二章)

(超时代码)

#include<iostream>
#include<vector>
#include<algorithm>
#include<stdio.h>
using namespace std;
int number[100000];
int main(){
	int n;
	scanf("%d",&n);
	int indexOfZero;
	for(int i=0;i<n;i++){
		scanf("%d",&number[i]);
		if(number[i]==0)
			indexOfZero=i;//找到元素0所在下标
	}
	int count=0;
	while(true){
        //如果元素0的下标不为0
		if(indexOfZero!=0){
			int j=0;
			for(;number[j]!=indexOfZero;j++){};//遍历数组找到元素0的下标的元素
			number[indexOfZero]=number[j];
		    indexOfZero=j;
		    count++;
		}
       //如果元素0的下标为0
		else{
			int i=1;
			for(;number[i]==i&&i<n;i++){}//找到第一个number[i]!=i的元素
			if(i==n)//如果i==n排序完毕
				break;
			number[indexOfZero]=number[i];
			count++;
			indexOfZero=i;
		}
	}
	printf("%d\n",count);
}

(AC代码) 

#include<iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
int number[100000];
int main(){
	int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		int temp;
		scanf("%d",&temp);
		number[temp]=i;
	}
	int count=0;
	for(int i=0;i<n;i++){
		while(number[0]!=0){
			swap(number[0],number[number[0]]);
			count++;
		}
       //当number[0]==0时查找第一个number[i]!=i的元素
		if(number[i]!=i){
			swap(number[i],number[0]);
			count++;
		}
	}
	printf("%d\n",count);
}

题目大意: 

猜你喜欢

转载自blog.csdn.net/m0_38090681/article/details/84452843