Lightoj 1005 Rooks(DP)

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[i][j]代表前i行放j个车的方案数。则dp[i][j]=dp[i-1][j]+dp[i-1][j-1]*(n-(j-1));

或者使用组合数学做。答案是C(n,k)*A(n,k)

/* ***********************************************
Author :guanjun
Created Time :2016/6/9 16:02:10
File Name :1005.cpp
************************************************ */
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <iomanip>
#include <list>
#include <deque>
#include <stack>
#define ull unsigned long long
#define ll long long
#define mod 90001
#define INF 0x3f3f3f3f
#define maxn 10010
#define cle(a) memset(a,0,sizeof(a))
const ull inf = 1LL << ;
const double eps=1e-;
using namespace std;
priority_queue<int,vector<int>,greater<int> >pq;
struct Node{
int x,y;
};
struct cmp{
bool operator()(Node a,Node b){
if(a.x==b.x) return a.y> b.y;
return a.x>b.x;
}
}; bool cmp(int a,int b){
return a>b;
}
ll dp[][];
int n,k;
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
//freopen("out.txt","w",stdout);
int T;
cin>>T;
for(int t=;t<=T;t++){
cin>>n>>k;
printf("Case %d: ",t);
if(k>n){
puts("");continue;
}
cle(dp);
dp[][]=;
for(int i=;i<=n;i++){
for(int j=;j<=i;j++){
if(j)dp[i][j]=dp[i-][j]+dp[i-][j-]*(n-j+);
else dp[i][j]=dp[i-][j];
}
}
printf("%lld\n",dp[n][k]);
}
return ;
}
上一篇:hibernate查询部分字段转换成实体bean


下一篇:获取minist数据并转换成lmdb