题目链接:http://lightoj.com/volume_showproblem.php?problem=1005
1005 - Rooks
Time Limit: 1 second(s) | Memory Limit: 32 MB |
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 numbersn and k, your job is to determine the number of ways one can putk rooks on an n x n chessboard so that no two of them are in attacking positions.
Input
Input starts with an integerT (≤ 350), denoting the number of test cases.
Each case contains two integersn (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 * n 的棋盘,要放m个车子,要求每个车子不在同行同列,问有几种方案
思路:
高中学过的排列组合派上用场了!!!可以在 n 行取 m 行,即C(n,m),然后在这几行中每列放一个车子
(共 n 列),即A(n,m),所以答案就是C(n,m)*A(n,m) 记为 dp[ n ][ m ]。
状态方程:dp[ i ][ j ]=dp[ i ][ 1 ] * dp[ i-1 ][ j-1 ] / j;
其中 i为棋盘大小n,j为车子数m , dp[ i ][ 1 ]=i*i, dp[ i ][ 0 ]=1这里要注意哦!!!
代码如下:
#include <stdio.h>
#include <cstring>
using namespace std;
long long dp[35][35];
int main()
{
int t,n,m,i,j,k=1;
memset(dp,0,sizeof(dp));
for(i=1;i<35;i++)
{
dp[i][0]=1;
dp[i][1]=i*i;
}
for(i=2;i<35;i++)
{
for(j=2;j<=i;j++)
dp[i][j]=dp[i][1]*dp[i-1][j-1]/j;
}
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&m);
printf("Case %d: %lld\n",k++,dp[n][m]);
}
return 0;
}
|
|