AcWing 1243. 糖果
原题链接
中等
作者:
wjie
,
2020-08-11 16:42:53
,
所有人可见
,
阅读 542
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
const int N = (1 << 20);
vector<int> colState[25];
int n, m, k, mylog2[N];
int res;
int lowbit(int x)
{
return x & (-x);
}
void dfs(int state, int numbers)
{
if (numbers >= res) return;
if (state == (1 << m) - 1)
{
res = numbers;
return;
}
int col = -1;
for (int i = ((1 << m) - 1) ^ state; i; i -= lowbit(i))
{
int tempCol = mylog2[lowbit(i)];
// cout << i << " " << tempCol << endl;
if (col == -1 || colState[tempCol].size() < colState[col].size()) col = tempCol;
}
// cout << col << " " << colState[col].size() << endl;
if(col == -1) return;
for (int i = 0; i < colState[col].size(); ++i) dfs(state | colState[col][i], numbers+1);
}
int main()
{
scanf("%d %d %d", &n ,&m, &k);
for (int i = 0; i < m; ++i) mylog2[1 << i] = i;
res = m + 1;
for (int i = 0; i < n; ++i)
{
int tempState = 0;
for (int j = 0; j < k; ++j)
{
int d;
scanf("%d", &d);
tempState |= (1 << (d-1));
}
for (int j = 0; j < m; ++j)
{
if ((tempState >> j) & 1)
{
colState[j].push_back(tempState);
}
}
}
// for (int i = 0; i < m; ++i) cout << colState[i].size() << " " ;
// cout << endl;
dfs(0, 0);
if (res == m + 1) res = -1;
printf("%d", res);
return 0;
}