Number of squares (1)
Time Limit: 10000/5000 MS (Java/others) memory limit: 32768/32768 K (Java/Others)
Problem description gives you an N * n checkboard. Each checkboard contains a non-negative number.
Take out several numbers from them so that the lattice of any two numbers does not have a public edge. That is to say, the two grids of the obtained number cannot be adjacent and the sum of the obtained numbers is the largest.
Input includes multiple test instances. Each test instance includes an integer N and N x N non-negative numbers (n <= 20)
Output for each test instance, the maximum sum possible for the output
Sample Input
375 15 21 75 15 28 34 70 5
Sample output
188
Analysis: DP [I] [J] indicates the sum of values of the first I row and the first I row in the J state, DP [I] [J] = max (DP [I] [J], DP [I-1] [k] + sum [I] [J]). sum [I] [J] indicates the sum of values in the status J of row I.
Because n <= 20, it can be found that there are a maximum of 17711 valid states.
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int N = 21;const int M = 17720; //合法状态最多有17711个int n, p;int a[N][N];int dp[N][M];int s[M];int sum[N][M];bool checkA(int x) { //判断本行状态是否冲突 return !(x & (x >> 1));}bool checkB(int x, int y) { //判断本行和上一行是否冲突 return !(x & y);}int get_sum(int r, int state) { //求第i行状态为state时的取值总和 int res = 0; for(int i = 0; i < n; i++) if((state >> i) & 1) res += a[r][n - 1 - i]; return res;}void Init() { p = 0; memset(sum, 0, sizeof(sum)); for(int i = 0; i < (1 << n); ++i) //求出所有合法状态 if(checkA(i)) s[p++] = i; for(int i = 0; i < n; ++i) { //求第i行取第j个状态时的取值总和 for(int j = 0; j < p; ++j) { sum[i][j] = get_sum(i, s[j]); } }}void solve() { memset(dp, 0, sizeof(dp)); for(int i = 0; i < p; i++) dp[0][i] = sum[0][i]; for(int i = 1; i < n; i++) { //行数 for(int j = 0; j < p; j++) { //本行状态 for(int k = 0; k < p; k++) { //上一行的状态 if(checkB(s[j], s[k])) { dp[i][j] = max(dp[i][j], dp[i-1][k] + sum[i][j]); } } } } int ans = dp[n-1][0]; for(int i = 1; i < p; i++) if(ans < dp[n-1][i]) ans = dp[n-1][i]; printf("%d\n", ans);}int main() { while(~scanf("%d", &n)) { for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) scanf("%d", &a[i][j]); Init(); solve(); } return 0;}
HDU 1565 square fetch (1) (State compression DP)