UVa 10401 Injured Queen Problem(简单DP)
题意:
受伤的皇后只能攻击它这一列的,和它周围的九个格子。
给定一个字符串,如果第i个字符是?则表示皇后能放在任意位置,如果不是?则表示它指定了必须放在哪一行,问有几种放法。
思路:
这种格子题目类似于小明回家,有几条路径可以选择一样,只不过初始点和结束状态不怎么一样而已。
dp[i, j]表示(i, j)坐标最多有几种放法,dp[i, j]取决于dp[i-1, k],k取决于题目条件。
#include <cstdio> #include <cstdlib> #include <cstring> #include <cctype> const int MAXN = 20; char b[MAXN]; long long int dp[MAXN][MAXN]; int main() { while (scanf("%s", b) == 1) { int n = strlen(b); memset(dp, 0, sizeof(dp)); if (b[0] == '?') { for (int i = 0; i < n; ++i) dp[0][i] = 1; } else { if (isdigit(b[0])) { int k = b[0] - '1'; dp[0][k] = 1; } else { int k = b[0] - 'A' + 9; dp[0][k] = 1; } } for (int i = 1; i < n; ++i) { if (b[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; if (isdigit(b[i])) j = b[i] - '1'; else j = b[i] - 'A' + 9; 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 int ans = 0; for (int i = 0; i < n; ++i) ans += dp[n-1][i]; printf("%lld\n", ans); } return 0; }
-------------------------------------------------------
kedebug
Department of Computer Science and Engineering,
Shanghai Jiao Tong University
E-mail: kedebug0@gmail.com
GitHub: http://github.com/kedebug
-------------------------------------------------------