331 - Mapping the Swaps(搜索)

點擊打開鏈接

刷點水題找找感覺。。。。

題意:求亂序到升序冒泡排序有幾種交換法。


#include <iostream>
#include <cstdio>
using namespace std;
const int MAX_N = 5;
int n, ans;
int a[MAX_N];

bool check() 
{
	for(int i = 1; i < n; i++)
		if(a[i-1] > a[i])
			return false;
	return true;
}

void dfs()
{
	for(int i = 1; i < n; i++)
	{
		if(a[i-1] > a[i])
		{
			swap(a[i-1], a[i]);
			if(check())
				ans++;
			else
				dfs();
				
			swap(a[i-1], a[i]);
		}
	}
}

int main()
{
	int T = 1;
	while(scanf("%d", &n), n)
	{
		ans = 0;
		for(int i = 0; i < n; i++)
			scanf("%d", a+i);
		dfs();
		printf("There are %d swap maps for input data set %d.\n", ans, T++);
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章