先预处理出每种牌的张数,对于花色只要考虑一下排列组合即可
那么设dp[i][j],表示用到第i张牌,相邻位置为相同花色有j个,然后枚举当前的牌要分成几堆,几堆插入到相同花色位置,剩下插入到不同花色位置,这样去转移即可
代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef unsigned long long ll;
const char card[15] = {"0A23456789TJQK"};
int to[300], to2[300];
int t, n, cnt[14][4];
char s[3];
ll C[55][55], dp[14][55];
int main() {
for (int i = 0; i <= 50; i++) {
C[i][0] = C[i][i] = 1;
for (int j = 1; j < i; j++)
C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
}
for (int i = 1; i <= 13; i++) to[card[i]] = i;
to2['S'] = 0; to2['H'] = 1; to2['D'] = 2; to2['C'] = 3;
scanf("%d", &t);
int cas = 0;
while (t--) {
scanf("%d", &n);
memset(cnt, 0, sizeof(cnt));
ll ans = 1;
while (n--) {
scanf("%s", s);
cnt[to[s[0]]][to2[s[1]]]++;
}
for (int i = 1; i <= 13; i++) {
int sum = 0;
for (int j = 0; j < 4; j++) sum += cnt[i][j];
for (int j = 0; j < 4; j++) ans *= C[sum][cnt[i][j]], sum -= cnt[i][j];
}
int tot = 0;
memset(dp, 0, sizeof(dp));
dp[0][0] = 1;
for (int i = 1; i <= 13; i++) {
int sum = 0;
for (int j = 0; j < 4; j++) sum += cnt[i][j];
if (sum == 0) {
for (int j = 0; j <= max(0, tot - 1); j++)
dp[i][j] = dp[i - 1][j];
continue;
}
for (int j = 0; j <= max(0, tot - 1); j++) {
for (int k = 1; k <= sum; k++) {
for (int x = 0; x <= k; x++) {
if (j + sum - k - x < 0) continue;
dp[i][j + sum - k - x] += dp[i - 1][j] * C[sum - 1][k - 1] * C[j][x] * C[tot + 1 - j][k - x];
}
}
}
tot += sum;
}
printf("Case #%d: %llu\n", ++cas, dp[13][0] * ans);
}
return 0;
}