2.1.4 Healthy Holsteins 健康的好斯坦奶牛 解題報告(二進位制列舉)
阿新 • • 發佈:2018-12-09
Description
農民JOHN以擁有世界上最健康的奶牛為驕傲。他知道每種飼料中所包含的的牛所需的最低的維他命量是多少。請你幫助農夫餵養他的牛,以保持他們的健康,使餵給牛的飼料的種數最少。 給出牛所需的最低的維他命,輸出餵給牛需要哪些種類的飼料,且所需的種類數最少。
Input
第1行:一個整數V(1<=V<=25),表示需要的維他命的種類數。 第2行:V個整數(1<=每個數<=1000),表示牛每天需要的維他命的最小量。 第3行:一個整數G(1<=G<=15),表示可用來喂牛的飼料的數量。下面G行,第i行表示編號為i飼料包含的各種維他命的量的多少。
Output
輸出檔案只有一行,包括: 牛必需的最小的飼料種數P 後面有P個數,表示所選擇的飼料編號(按從小到大排列)。
Sample Input
4 100 200 300 400 3 50 50 50 50 200 300 200 300 900 150 389 399
Sample Output
2 1 3
這個題的G很小,所以只需要對所有情況列舉即可,然後取最小值
這裡從0到2^G跑一遍,然後輸出二進位制數中'1'最少的那一個答案即可
#include <map> #include <cstdlib> #include <cmath> #include <cstdio> #include <string> #include <cstring> #include <fstream> #include <iostream> #include <sstream> #include <algorithm> #define lowbit(a) (a&(-a)) #define _mid(a,b) ((a+b)/2) #define _mem(a,b) memset(a,0,(b+3)<<2) #define fori(a) for(int i=0;i<a;i++) #define forj(a) for(int j=0;j<a;j++) #define ifor(a) for(int i=1;i<=a;i++) #define jfor(a) for(int j=1;j<=a;j++) #define mem(a,b) memset(a,b,sizeof(a)) #define IN freopen("in.txt","r",stdin) #define OUT freopen("out.txt","w",stdout) #define IO do{\ ios::sync_with_stdio(false);\ cin.tie(0);\ cout.tie(0);}while(0) #define mp(a,b) make_pair(a,b); using namespace std; typedef long long ll; const int maxn = 50; const int INF = 0x3f3f3f3f; const int inf = 0x3f; const double EPS = 1e-7; const double Pi = acos(-1); const int MOD = 1e9+7; int a[maxn]; int b[maxn][maxn]; int num[maxn]; int v,g; int getbit(int x,int i){return (x>>i)&1;} int getsum(int x,int level){ //第x種情況的第level種維他命含量 int sum = 0; for(int i=0;i < 15;i++) if(getbit(x,i)) sum += b[i][level]; return sum; } int getone(int x){ //x的二進位制中'1'的數量 int i=0; while(x){ i += x&1; x >>= 1; } return i; } bool juge(int x){ fori(v) if(a[i]>getsum(x,i)) return false; return true; } int main() { //IN; int res = INF; cin >> v; fori(v) cin >> a[i]; cin >> g; fori(g) forj(v) cin >> b[i][j]; fori(1<<g){ if(juge(i)) if(getone(res) > getone(i)) res = i; } cout << getone(res); for(int i=1;res;i++){ if(res & 1) cout <<" " << i; res >>= 1; } cout << endl; return 0; }