ZOJ-2730

来源:互联网 发布:gif编辑文字软件 编辑:程序博客网 时间:2024/06/04 18:10

吐血了。。费了半天用python写完了,结果n最大49的时候递归栈就不够用了!!网上搜了搜MS python对递归支持不好。。没办法只能用JAVA去重写,感觉代码已经丑陋不堪了。。特别是python代码。。又浪费好多时间,坑啊,其实本题算法正确还有待验证,因为我DFS到n*(n-1)的时候就结束了,默认这个时候有解。。好像事实上是这样的

import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Scanner;public class Main{static int n;static Map<String, Boolean> map = new HashMap<String, Boolean>();static List<Integer> temp = new ArrayList<Integer>();static boolean finish = false;static void fill_map(List<Integer> list){if (list.size() == 2)map.put(list.get(0) + "" + list.get(1), false);else{for (int i = 0; i < n; i++)if (list.size() == 0 || i > list.get(0)){list.add(i);fill_map(list);list.remove(list.size() - 1);}}}static void dfs(int depth, int[] res){if (depth == 1 + n * (n - 1) / 2){finish = true;System.out.println(depth - 1);for (int i = 0; i < depth - 1; i++)System.out.format(i > 0 ? " %d" : "%d", res[i]);System.out.println();}if (finish)return;for (int i = 0; i < n; i++){if (depth == 0){res[0] = i;dfs(depth + 1, res);}else if (i != res[depth - 1]){String key = i < res[depth - 1] ? i + "" + res[depth - 1]: res[depth - 1] + "" + i;if (!map.get(key)){map.put(key, true);res[depth] = i;dfs(depth + 1, res);map.put(key, false);}}}}public static void main(String[] args){Scanner sc = new Scanner(System.in);int res[] = new int[1200];while (sc.hasNext()){n = sc.nextInt();map.clear();temp.clear();fill_map(temp);finish = false;dfs(0, res);}}}



0 0