UVAlive-4643 Twenty Questions

来源:互联网 发布:淘宝申述不成功怎么办 编辑:程序博客网 时间:2024/04/28 04:20

题目大意:

有m个问题,n个人,给出这n个人对这m个问题的回答,只有“Yes”和“No”这两种回答,所以用1表示yes,0表示no,然后问你最少用几次询问问题能分别出所有人。

一个例子,比如

3 4
001
011
100
000

用两次即可,先问第3个问题,如果是1则问第2个问题,如果是0则为第1个问题,得到的答案是2而不是3!

解题思路:

状态压缩动态规划+记忆化搜索

我是看着这篇博客写出来的。链接在这里

不得不说这个博主很强大。

我一开始虽然也想的是状态压缩动态规划+记忆化搜索,奈何dp[i][j]表示什么却一直弄错,也不出来。最后看了博主的博客,惊为天人!

唉,但是看了别人博客,写的程序都跟别人一模一样,这就是看别人博客的后果,思路被别人影响,代码都会一模一样。唉。具体写法直接看原博客吧。

代码:

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int maxn = 150;const int INF = 0x3f3f3f3f;const int maxs = (1 << 11) + 11;int n, m;int st[maxn];char str[maxn];int dp[maxs][maxs];int dfs(int status, int res) {if (dp[status][res] != -1) return dp[status][res];int cnt = 0;for (int i = 0; i < n; ++i) {if ((st[i] & status) == res) ++cnt;}if (cnt <= 1) return dp[status][res] = 0;int ans = INF;for (int i = 0; i < m; ++i) {if (status & (1 << i)) continue;dp[status | (1 << i)][res] = dfs(status | (1 << i), res);dp[status | (1 << i)][res | (1 << i)] = dfs(status | (1 << i), res | (1 << i));ans = min(ans, max(dp[status | (1 << i)][res], dp[status | (1 << i)][res | (1 << i)]) + 1);}return dp[status][res] = ans;}int main() {while (~scanf("%d%d", &m, &n)) {if (!n && !m) break;memset(st, 0, sizeof(st));for (int i = 0; i < n; ++i) {scanf(" %s", str);for (int j = 0; j < m; ++j) {if(str[j] == '1')st[i] |= (1 << j);}}memset(dp, -1, sizeof(dp));printf("%d\n", dfs(0, 0));}return 0;}


0 0
原创粉丝点击