题意:
n∗n(n≤30)的棋盘放置k个互相无法攻击的车的 方法数,答案保证不爆LL
分析:
k>n,答案是0这个是很显然的
dp[i][j]:=i∗i格子放置k个互相不攻击的车的方法数
看上图假如转移到i∗i(4∗4)的,首先我们可以不放dp[i−1][j]
放1个的话,我们可以放在左下3个格子,右上3个格子,右下角1个格子里
由于之前放过j−1个,那么左下和右上的3个格子还能的位置各有(i−1)−(j−1)=i−j个
加上右下角那1个,放1个的方法数是(2∗(i−j)+1)∗dp[i−1][j−1]
放2个的话,只能放在左下和右上了,由于之前放了j−2个,还能放(i−1)−(j−2)=i−j+1个
放2个的方法数是(i−j+1)∗dp[i−1][j−2]
dp[i][j]=dp[i−1][j]+(2∗(i−j)+1)∗dp[i−1][j−1]+(i−j+1)∗dp[i−1][j−2]
代码:
//
// Created by TaoSama on 2015-10-27
// Copyright (c) 2015 TaoSama. All rights reserved.
//
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <set>
#include <vector>
using namespace std;
#define pr(x) cout << #x << " = " << x << " "
#define prln(x) cout << #x << " = " << x << endl
const int N = 1e5 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7;
typedef long long LL;
int n, k;
LL dp[35][35];
int main() {
#ifdef LOCAL
freopen("C:\\Users\\TaoSama\\Desktop\\in.txt", "r", stdin);
// freopen("C:\\Users\\TaoSama\\Desktop\\out.txt","w",stdout);
#endif
ios_base::sync_with_stdio(0);
for(int i = 0; i <= 30; ++i) dp[i][0] = 1;
for(int i = 1; i <= 30; ++i) {
for(int j = 1; j <= i; ++j) {
dp[i][j] = dp[i - 1][j] + (2 * (i - j) + 1) * dp[i - 1][j - 1];
if(j >= 2) dp[i][j] += (i - j + 1) * (i - j + 1) * dp[i - 1][j - 2];
}
}
int t; scanf("%d", &t);
int kase = 0;
while(t--) {
scanf("%d%d", &n, &k);
LL ans = 0;
if(k <= n) ans = dp[n][k];
printf("Case %d: %lld\n", ++kase, ans);
}
return 0;
}
本题还可以用组合数学的思想解决
分析:
放置k个车,行列是不相关的,也就是Ckn,n行里面选择k行放置,列同理,选出来之后由于行列可以任意组合,还要乘上一个排列数Akk
答案是(Ckn)2∗Akk
代码:
//
// Created by TaoSama on 2015-10-27
// Copyright (c) 2015 TaoSama. All rights reserved.
//
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <set>
#include <vector>
using namespace std;
#define pr(x) cout << #x << " = " << x << " "
#define prln(x) cout << #x << " = " << x << endl
const int N = 1e5 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7;
typedef long long LL;
int n, k;
LL C[35][35];
int main() {
#ifdef LOCAL
freopen("C:\\Users\\TaoSama\\Desktop\\in.txt", "r", stdin);
// freopen("C:\\Users\\TaoSama\\Desktop\\out.txt","w",stdout);
#endif
ios_base::sync_with_stdio(0);
for(int i = 0; i <= 30; ++i) {
C[i][i] = C[i][0] = 1;
for(int j = 1; j < i; ++j)
C[i][j] = C[i - 1][j] + C[i - 1][j - 1];
}
int t; scanf("%d", &t);
int kase = 0;
while(t--) {
scanf("%d%d", &n, &k);
LL ans = C[n][k] * C[n][k];
for(int i = 2; i <= k; ++i) ans *= i;
printf("Case %d: %lld\n", ++kase, ans);
}
return 0;
}