Twenty Questions
DP + bitmasking
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
int F[128]; //feature set
int dp[1 << 11][1 << 11]; //set of question and answer
//denotes bitmask of question and answer
int n, m;
int solve(int Q, int A)
{
if(dp[Q][A] != -1)
return dp[Q][A];
int nObjects = 0; //number of objects remaining after asking Q
for(int i = 0; i < n; i++)
{
if((F[i] & Q) == A)
nObjects++;
}
if(nObjects <= 1)
{
return dp[Q][A] = 0;
}
int nQuestions = m + 1;
//one by one ask each question and take the min number o question required to identify each object
for(int i = 0; i < m; i++)
{
if((Q & (1 << i)) == 0) //ith question is not yet asked
{
nQuestions = min(nQuestions, 1 + max(solve(Q | (1 << i), A),solve(Q | (1 << i), A | (1 << i))));
//solve(Q | (1 << i), A) denotes number of objects which 0 at ith position after asking ith uestion
//solve(Q | (1 << i), (A | (1 << i))) denotes number of objects which 1 at ith positoin after asking ith question
}
}
return dp[Q][A] = nQuestions;
}
int main()
{
while(cin >> m >> n, !(m == 0 && n == 0))
{
for(int i = 0; i < n; i++)
{
string s;
cin >> s;
int feature = 0;
for(int j = 0; j < m; j++)
{
feature |= (s[j] - '0') << j;
}
F[i] = feature;
}
memset(dp, -1, sizeof(dp));
cout << solve(0, 0) << endl;
}
return 0;
}
Comments
Post a Comment