1. 程式人生 > >PAT 1067 Sort with Swap(0, i) 腳標與陣列的關係 執行超時問題 燚

PAT 1067 Sort with Swap(0, i) 腳標與陣列的關係 執行超時問題 燚

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);
}

題目大意: