蒙德里安的梦想

2021-03-21  本文已影响0人  Wilbur_

这道题是状态压缩相关的,还是需要练习……CSAPP这本书里有介绍状态压缩的基本原理,我觉得还是很有用的。
下面是代码

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = 12, M = 1 << N;
        long[][] dp = new long[N][M];
        boolean[] st = new boolean[M];
        while (true) {
            String[] s1 = br.readLine().split(" ");
            int n = Integer.parseInt(s1[0]), m = Integer.parseInt(s1[1]);
            if (n == 0 && m == 0) break;
            for (int i = 0; i < (1<<n); i++) {
                st[i] = true;
                int count = 0;
                for (int j = 0; j < n; j++) {
                    if ((i >> j & 1) == 1) {
                        if ((count & 1) == 1) {
                            st[i] = false;
                        }
                        count = 0;
                    } else count++;
                }
                if ((count & 1) != 0) st[i] = false;
            }
            dp = new long[N][M];
            dp[0][0] = 1;
            for (int i = 1; i <= m; i++) {
                for (int j = 0; j < 1 << n; j++) {
                    for (int k = 0; k < 1 << n; k++) {
                        if (((j & k) == 0) && st[j | k]) {
                            dp[i][j] += dp[i-1][k];
                        }
                    }
                }
            }
            System.out.println(dp[m][0]);
        }

    }
}
上一篇下一篇

猜你喜欢

热点阅读