uva 10401 Injured Queen Problem(dp)
题目链接:10401 - Injured Queen Problem
题目大意:给出一个字符串,要求在n * n(n为字符串的长度)的棋盘上摆放n个受伤的皇后,受伤的皇后只能攻击到同一列和它周围8个格子,如果字符串中第i个字符为'?'表示第i + 1个皇后可以摆放在任意行,如果为1 ~ F表示第i+1个皇后必须摆放在第str[i]行, 问,有多少种不同的摆法?
解题思路:一开始用递归 + 记忆化, 结果超时了, 后来发现其实可以写成递推,dp[i][j]代表第i个皇后摆放在第j行的摆法种类, dp[i][j] = dp[i - 1][k] ( 0 < k < n && abs (j - k) > 1)。
#include <stdio.h> #include <string.h> const int N = 20; char str[N]; long long n, dp[N][N]; int change(char c) { if (c >= '1' && c <= '9') return c - '1'; else return c - 'A' + 9;; } void init() { n = strlen(str); memset(dp, 0, sizeof(dp)); if (str[0] == '?') { for (int i = 0; i < n; i++) dp[0][i] = 1; } else dp[0][change(str[0])] = 1; } long long solve() { init(); for (int i = 1; i < n; i++) { if (str[i] == '?') { for (int j = 0; j < n; j++) { for (int k = 0; k < j - 1; k++) dp[i][j] += dp[i - 1][k]; for (int k = j + 2; k < n; k++) dp[i][j] += dp[i - 1][k]; } } else { int j = change(str[i]); for (int k = 0; k < j - 1; k++) dp[i][j] += dp[i - 1][k]; for (int k = j + 2; k < n; k++) dp[i][j] += dp[i - 1][k]; } } long long sum = 0; for (int i = 0; i < n; i++) sum += dp[n - 1][i]; return sum; } int main() { while (scanf("%s", str) == 1) { printf("%lld\n", solve()); } return 0; }