- C 比 D 难。
思路
使用 dfs 枚举所有可能,对于每个摊位,有选与不选两种可能,每次选后进行检查,检查每种爆米花是否已经全部买到,如果全部买到,就统计购买摊位个数的最小值,否则继续 dfs。
记得回溯。
时间复杂度 。
Code
#include <bits/stdc++.h>
#define endl '\n'
#define ll long long
using namespace std;
const int E = 1e1 + 5;
ll n, m, ans = 1e18;
string a[E];
ll s[E];
inline bool check()
{
for (int i = 0; i < m; i++)
if (s[i] == 0)
return 0;
return 1;
}
inline void dfs(ll i, ll step)
{
// cout << "ok" << " " << i;
if (i == n)
{
if (check())
ans = min(ans, step);
return;
}
// cout << "ok " << i;
bool s1[E];
//-------------------------
for (int j = 0; j < m; j++)
s1[j] = s[j];
//---------------------------回溯准备
//-----------------------------
for (int j = 0; j < m; j++)
if (a[i][j] == 'o')
s[j] = 1;
//-----------------------------统计爆米花购买情况
//---------------------------------
dfs(i + 1, step + 1);
for (int j = 0; j < m; j++)
s[j] = s1[j];
//--------------------------------回溯
dfs(i + 1, step);
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i++)
cin >> a[i];
dfs(0, 0);
cout << ans;
return 0;
}