zoukankan      html  css  js  c++  java
  • uva 331 Mapping the Swaps 求交换排序的map 纯DFS

    给出一个序列,每次交换两个数,求有几种交换方法能使序列变成升序。

    n不大于5,用dfs做。

    代码:

    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    using namespace std;
    
    int num[8], ans, n;
    
    bool check() {				//check if the array is inorder
    	for (int i = 0; i < n - 1; i++)
    		if (num[i] > num[i + 1])
    			return false;
    	return true;
    }
    
    void dfs(void) {
    	for (int i = 0; i < n - 1; i++)
    		if (num[i] > num[i + 1]) {
    			swap(num[i], num[i + 1]);
    			if (check())
    				ans++;
    			else
    				dfs();
    			swap(num[i], num[i + 1]);
    		}
    }
    
    int main () {
    	int cas = 0;
    	while (scanf("%d", &n) && n) {
    		for (int i = 0; i < n; i++)
    			scanf("%d", &num[i]);
    		ans = 0;
    		if (!check()) dfs();
    		printf("There are %d swap maps for input data set %d.
    ", ans, ++cas);
    	}
    	return 0;
    }


  • 相关阅读:
    Python-内置函数
    Python-匿名函数
    Python-函数递归-二分法
    Python-函数递归
    Day4-函数
    CSS-定位
    CSS-文本属性,文字属性
    CSS-浮动
    CSS-盒模型
    CSS-继承和层叠
  • 原文地址:https://www.cnblogs.com/java20130723/p/3212095.html
Copyright © 2011-2022 走看看