前言
传送门 : https://www.acwing.com/problem/content/description/1364/
传送门2: https://www.acwing.com/problem/content/description/1364/
如果用二进制枚举Ac了,他不会提高你的二进制枚举能力,只提高了你debug能力
(代码大概写了5分钟,debug半小时)
前置技能
什么是 二进制枚举
我们高中都学过 二进制系数性质
C ( N , 0 ) + C ( N , 1 ) + C ( N , 2 ) + … + C ( N , N ) = 2 n C(N, 0)+C(N, 1)+C(N, 2)+\ldots+C(N, N)=2^{n} C(N,0)+C(N,1)+C(N,2)+…+C(N,N)=2n
当然没学过也不要紧,你只要知道这是N个数中,选0-N个数的所有选法
又因为每个二进制数唯一,因此我们可以用二进制数表示选的方案
例如 : 5 = 101 表示拿了1号位和0号位
因此我们就有一个枚举模板出来了:
for(int j = 0; j < (1<<n); j++)
if(i & (1 << j))
printf(" %d ",a[j]);
(利用二进制枚举了所有选法)
好了,二进制枚举讲完了:快去A题吧
简单吗?(我在口胡?)
详解版(转载侵删) : https://blog.csdn.net/sugarbliss/article/details/81099340
思路
因此这道题
不就是 用二进制枚举 拿饲料的所有方法吗
时间复杂度也就是(O (1<<N)*G) = 503316480 (5e8 恰好能过,能过就行 awa)
这题又要字典序最小的选法,但是没必要因为二进制枚举过程中,就是按字典序来的
CODE
#include <bits/stdc++.h>
using namespace std;
const int N =30,M= 20;
int g[M][N];
int Need[N];
int n,q;
int num[N];
int ans[N],idx;
int minn = 0x3f3f3f3f;
void init()
{
cin>>n;
for(int i=0; i<n; i++)
cin>>Need[i];
cin>>q;
for(int i=0; i<q; i++)
for(int j = 0; j<n; j++)
cin>>g[i][j];
}
bool check()
{
for(int i=0; i<n; i++)
{
if(num[i]<Need[i])
return false;
}
return true;
}
void solve()
{
init();
for(int i = 1 ; i<(1<<q); i++)
{
for(int j = 0 ; j<q; j++)
{
if(i&(1<<j))
{
//cout<<j<<" ";
for(int k =0; k<n; k++)
num[k] += g[j][k];
}
}
// cout<<endl;
if(check())
{
int cnt = 0 ;
for(int j= 0 ; j<q; j++)
{
if(i&(1<<j))
++cnt;
}
if(minn > cnt)
{
minn = cnt;
idx = 0 ;
for(int j = 0 ; j<q; j++)
if(i&(1<<j))
ans[++idx] = j+1;
}
}
memset(num,0,sizeof num);
continue;
}
cout<<minn<<" ";
for(int i=1; i<=idx; i++)
cout<<ans[i]<<" ";
}
int main()
{
ios::sync_with_stdio(false);
solve();
return 0;
}