110801 Little Bishops


// Refer to http://blog.csdn.net/metaphysis/article/details/6553011 to see the design of following program.

import java.util.*;

public class Main {
	private static void ClearArray(long[][] data, int rows, int cols)
	{
		for (int i = 1; i <= rows; ++i)
			for (int j = 1; j <= cols; ++j)
				data[i][j] = -1;
	}
	
	private static int GetRowCols(int totalRows, int currentRow, boolean isWhite)
	{
		int start = 0;
		if (isWhite)
			start = 2 - (totalRows % 2);
		else
			start = 1 + (totalRows % 2);

		return start + ((currentRow - 1) / 2) * 2;
	}
	
	private static long GetCombinations(long[][] results, int totalRows, int bishops, int currentRow, boolean isWhite)
	{
		if (bishops <= 0)
			return 1;
		
		if (results[currentRow][bishops] >= 0)
			return results[currentRow][bishops];
		
		long result = 0;		

		if (currentRow == 1)
		{
			if (bishops > 1)
				result = 0;
			else
				result = GetRowCols(totalRows, currentRow, isWhite);
		}
		else
		{
			result = GetCombinations(results, totalRows, bishops, currentRow - 1, isWhite);
			int freeCols = GetRowCols(totalRows, currentRow, isWhite) - (bishops - 1);
			if (freeCols > 0)
				result += GetCombinations(results, totalRows, bishops - 1,  currentRow - 1, isWhite) * freeCols; 
		}
		
		results[currentRow][bishops] = result;
		return result;
	}
	
	private static long GetCombinations(int n, int k)
	{
		if (k == 0)
			return 1;
		
		if (n == 0)
			return 0;
		
		if (k == 1)
			return n * n;
		
		if (n == 1)
			return (k <= 1) ? 1 : 0;

		int whiteRows = ((n - 1) / 2) * 2 + 1;
		int blackRows = 2 * n - 1 - whiteRows;
		
		ClearArray(s_whiteCombinations, whiteRows, k);
		ClearArray(s_blackCombinations, blackRows, k);
		
		long sum = 0;
		for (int i = 0; i <= k; ++i)
			sum += GetCombinations(s_whiteCombinations, n, i, whiteRows, true) *
					GetCombinations(s_blackCombinations, n, k - i, blackRows, false);
		return sum;
	}
	
	public static void main(String[] args)
	{
		int n, k;
		Scanner inScanner = new Scanner(System.in);
		while(true)
		{
			n = inScanner.nextInt();
			k = inScanner.nextInt();
			
			if ((n | k) == 0)
				return;

			System.out.println(GetCombinations(n, k));
		}
	}
	
	private static final int MAX_ROWS = 8;
	private static final int MAX_BISHOPS = MAX_ROWS * MAX_ROWS;
	private static long[][] s_whiteCombinations = new long[MAX_ROWS][MAX_BISHOPS + 1];
	private static long[][] s_blackCombinations = new long[MAX_ROWS + 1][MAX_BISHOPS + 1];
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值