ZOJ-2730

吐血了。。费了半天用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);
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值