编程之美1.2

prefixSort.cpp
#include<iostream>
#include<assert.h>
using namespace std;

int cakeCount;//用于存储一共有多少个cake
int uperBound;
int *cakeArray;//保存初始cake排列的情况
int *cakeSwapArray;//保存对cake进行翻转得到的临时Array情况
int *swapNumArray;//保存每次翻转的第几个cake(按照数组的顺序)
int *swapNumArrayTemp;
void reverse(int *a, int cur){//交换第cur位
	int length = cur + 1;
	assert(a != NULL);
	assert(length > 0);
	for (int i = 0; i < length/2; i++){
		int temp = a[i];
		a[i] = a[length - i - 1];
		a[length - i - 1] = temp;
	}

}
int lowerBound(int *a, int length){
	int reverseCount = 0;
	for (int i = 1; i<length; i++){
		int t = a[i - 1] - a[i];
		if (t == 1 || t == -1){
			;
		}
		else{
			reverseCount++;
		}
	}
	return reverseCount;
}
bool isSorted(int *a, int length){
	assert(a != NULL);
	assert(length > 0);
	for (int i = 1; i < length; i++){
		if (a[i] - a[i - 1] != 1){
			return false;
		}
	}
	return true;
}
void init(int *a, int length){
	cakeCount = length;
	cakeArray = new int[length];
	cakeSwapArray = new int[length];
	for (int i = 0; i < length; i++){
		cakeArray[i] = a[i];
		cakeSwapArray[i] = a[i];
	}
	uperBound = 2 * cakeCount;//初始化最大的上界限
	swapNumArray = new int[uperBound];
	swapNumArrayTemp = new int[uperBound];
}
void printArray(int *a, int length){
	assert(a != NULL);
	assert(length > 0);
	for (int i = 0; i < length; i++){
		printf("%d  ", a[i]);
	}
	printf("\n");
}
void search(int step){
//	cout << "uperBound:" << uperBound << endl;
	
	if (step > uperBound){
		return;
	}
	if (isSorted(cakeSwapArray, cakeCount)){
		if (uperBound > step){
			uperBound = step;
			for (int i = 0; i < step; i++){
				swapNumArrayTemp[i] = swapNumArray[i];
			}
		}
		return;
	}
	for (int i = 1; i < cakeCount; i++){
//		cout << "i:"<<i << endl;
		reverse(cakeSwapArray, i);
//		cout << "step:" << step << endl;
		swapNumArray[step] = i;		
		search(step + 1);
		reverse(cakeSwapArray, i);
	}
}
int main(){
	int a[8] = {2,7,5,6,4,0,3,1};
	init(a, 8);
//	printArray(a, 3);
//	reverse(a, 1);
//	printArray(a,3);
	search(0);
	for (int i = 0; i < uperBound; i++){
		cout << swapNumArrayTemp[i] << " ";
	}
	cout << endl;
	cout <<"uperBound:"<< uperBound << endl;
	return 0;
}

《编程之美1.2》

    原文作者:li9213
    原文地址: https://blog.csdn.net/lisongfeng92130/article/details/40149377
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞