1. 程式人生 > >Light OJ 1005 - Rooks 數學題解

Light OJ 1005 - Rooks 數學題解

A rook is a piece used in the game of chess which is played on a board of square grids. A rook can only move vertically or horizontally from its current position and two rooks attack each other if one is on the path of the other. In the following figure, the dark squares represent the reachable locations for rook R1

 from its current position. The figure also shows that the rook R1 and R2 are in attacking positions where R1 and R3 are not. R2 and R3 are also in non-attacking positions.

Now, given two numbers n and k, your job is to determine the number of ways one can put k

 rooks on an n x n chessboard so that no two of them are in attacking positions.

Input

Input starts with an integer T (≤ 350), denoting the number of test cases.

Each case contains two integers n (1 ≤ n ≤ 30) and k (0 ≤ k ≤ n2).

Output

For each case, print the case number and total number of ways one can put the given number of rooks on a chessboard of the given size so that no two of them are in attacking positions. You may safely assume that this number will be less than 1017

.

Sample Input

Output for Sample Input

8

1 1

2 1

3 1

4 1

4 2

4 3

4 4

4 5

Case 1: 1

Case 2: 4

Case 3: 9

Case 4: 16

Case 5: 72

Case 6: 96

Case 7: 24

Case 8: 0



本題有點像n-queen的問題的變形,只是和n-queen有本質的不同,由於簡化了對角線,那麼就能夠使用數學的方法求解了。

思考了我好久,最終發現這個是inclusion-exclusion原理的應用。

1 當k等於0的時候為1。 當k等於1的時候,那麼就等於n^2

2 能夠這樣選擇的:先選擇n^2中的一格,那麼就剩下(n-1)^2格能夠選擇了,然後在選一格。那麼又剩下(n-2)^2格選擇了

3 這樣能夠利用乘法原理得到f(n, k) = f(n^2, 1) * f((n-1)^2, 1) * f((n-2)^2, 1)...*f((n-k+1)^2, 1);

4 相當於分別在n, n-1, n-2... (n-k+1)個方格中分別選擇一格。

5 可是這樣選擇有反覆。由於選擇出來的數不須要排序,那麼就把其排序的方法的次數除去,這是依據除法原理計演算法

6 最終得到:f(n, k) = f(n^2, 1) * f((n-1)^2, 1) * f((n-2)^2, 1)...*f((n-k+1)^2, 1) / P(k); P(k)是k個數的全排序

比如求f(4, 3) = f(4, 1) * f(3, 1) * f (2,, 1) / 3!;

f(4, 4) = f(4, 1), *f(3, 1), *f(2, 1) / 4!;

由於f(3, 3) = f(3, 1) * f (2, 1) / 3!;

所以能夠化簡:f(4, 4) = f(3, 3) * f(4, 1) / 4; 最後就利用這個公式,加上動態規劃法,能夠先計算出一個表,然後直接查表得到答案,速度奇快。

#pragma once
#include <stdio.h>
#include <vector>
using namespace std;

class Rooks1005
{
	const static int SIZE = 31;
	vector<vector<long long> > tbl;

	void genTbl()
	{
		for (int i = 1; i < SIZE; i++)
		{
			tbl[i][0] = 1;
			tbl[i][1] = i * i;
		}

		for (int i = 2; i < SIZE; i++)
		{
			for (int j = 2; j <= i; j++)
			{
				tbl[i][j] = tbl[i][1] * tbl[i-1][j-1] / j;
			}
		}
	}
public:
	Rooks1005():tbl(SIZE, vector<long long>(SIZE))
	{
		genTbl();

		int T, n, k;
		scanf("%d", &T);
		for (int i = 1; i <= T; i++)
		{
			scanf("%d %d", &n, &k);
			if (k > n) printf("Case %d: %d\n", i, 0);
			else printf("Case %d: %lld\n", i, tbl[n][k]);
		}
	}
};