10237-bishops
Time limit:3.000 seconds
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem= 1178
A bishop is a piece used in the game of chess which be played on a board of square grids. A Bishop can only move diagonally from it current position and two bishops attack all other if one are on the path of the Other. In the following figure, the dark squares represent the reachable locations of the for Bishop form it current B1. The figure also shows the Bishops B1 and B2 are in attacking positions the whereas B1 andB3. B2 and B3 are also in non-attacking positions.
Now, given two numbers n and K, your job are to determine the number of ways one can put K bishops on a NXN chessboard s o that no two of the them are in attacking positions.
Input
The input file may contain multiple test cases. Each test case is occupies a single line in the input file and contains two integers n (1≤n≤30) andk (0≤K≤N2).
A test case containing two zeros for N and K terminates the input and your won ' t need to process this particular input.
Output
For the, the input print a line containing the total number of ways one can put the given number of Bishops O n a chessboard of the given size so this no two of them are in attacking positions. You may safely assume the this number would be less than 1015.
Sample Input
8 6
4 4
20 40
30 5
0 0
Sample Output
5599888
260
0
3127859642656
Complete code:
/*0.049s*/
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int M = 30 + 5;
const int N = 30 * 30 + 5;
ll Rb [M] [N], Rw [M] [N], B [M], W [M]; /// B = Black, W = White
void calc (int n, int k, ll R [] [N], ll C [])
{
int i, j;
memset (R, 0, sizeof (R));
for (i = 0; i <= n; i ++)
R [i] [0] = 1;
for (i = 1; i <= n; i ++)
for (j = 1; j <= C [i]; j ++)
R [i] [j] = R [i-1] [j] + R [i-1] [j-1] * (C [i]-j + 1);
}
int main ()
{
int i, j, n, k;
ll ans;
while (scanf ("% d% d", & n, & k), n)
{
memset (B, 0, sizeof (B));
memset (W, 0, sizeof (W));
for (i = 1; i <= n; i ++)
for (j = 1; j <= n; j ++)
{
if ((i + j) & 1) ++ W [(i + j) >> 1];
else ++ B [(i + j) >> 1]; /// Calculate the number of diagonal grids of black and white, so that you do not need to consider the parity of n
}
sort (B + 1, B + n + 1);
sort (W + 1, W + n);
calc (n, k, Rb, B);
calc (n-1, k, Rw, W); /// Calculate the number of schemes on the white grid and the black grid, respectively
ans = 0;
for (i = 0; i <= k; i ++)
ans + = Rb [n] [i] * Rw [n-1] [k-i];
printf ("% lld \ n", ans);
}
return 0;
}
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/