UVAlive-4643 Twenty Questions

題目大意:

有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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章