简单的区间dp
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 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*n的棋盘,要放入k个相同的棋子,问有多少种方法使任意两个棋子既不同行,也不同列。
虽然说是简单区间dp,我自己花了好几个小时去做这个题,一开始我考虑的状态时dp[y][x][k],
代表一个y*x的矩形里面放k个棋子的方法数,结果这种方法不仅会超时,而且极其复杂,根本就无法考虑。
因为题目问的是正方形棋盘,所以后来思考dp[x][k],代表长宽为x的矩形,放k个棋子的方法数。
此题精华之处在于,因为放了一个棋子,剩余的部分又可以成为一个dp[x-1][k-1]的子问题。
(除此之外要想办法计算,使之不重复。)
/**==========================================
* This is a solution for ACM/ICPC problem
*
* @source:lightoj 1005 - Rooks
* @type: dp
* @author: wust_ysk
* @blog: http://blog.csdn.net/yskyskyer123
* @email: 2530094312@qq.com
*===========================================*/
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
const int INF =0x3f3f3f3f;
const int maxn= 30 ;
int n,k;
ll dp[maxn+3][maxn+3];
void work()
{
dp[1][1]=1;
dp[1][0]=1;
for(int i=2;i<=maxn;i++)
{
dp[i][0]=1;
for(int num=1;num<=i;num++)
{
dp[i][num]=dp[i-1][num-1]*i*i/num; //这个地方有的时候要先除再乘,这个地方先除不能保证整除,所以先乘
}
}
}
ll DP()
{
if(k>n) return 0;
return dp[n][k];
}
int main()
{
int T,kase=0; scanf("%d",&T);
work();
while(T--)
{
scanf("%d%d",&n,&k);
printf("Case %d: %lld\n",++kase,DP());//%lld 啊!! 心碎。
}
return 0;
}