usaco2.1.4-----Healthy Holsteins(二進制枚舉)

/*
ID:lvfuan11
PROG:holstein
LANG:C++

translation:
	給出每頭牛需要的維生素,現在有若干種飼料,每種各含有若干量的各種維生素,問最少用多少種飼料可以滿足一頭牛的每日所需
solution:
	直接枚舉即可,可以利用二進制枚舉來加速。
*/
#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>

using namespace std;
const int maxn = 30;

int vita[maxn], v;
int g;
int food[20][maxn];
vector<int> ans;

void get_ans(int x)
{
	int id = 1;
	ans.clear();
	while(x) {
		if(x & 1) {
			ans.push_back(id);
		}
		++id;
		x >>= 1;
	}
}

int count_bit(int x)
{
	if(x == 0)	return 0;
	int cnt = 0;
	while(x) {
		if(x & 1) {
			cnt++;
		}
		x >>= 1;
	}
	return cnt;
}

bool check(int s)
{
	int tmp[30];
	memset(tmp, 0, sizeof(tmp));
	for(int i = 0; i < 15; i++) {
		if(s >> i & 1) {
			for(int j = 0; j < v; j++)
				tmp[j] += food[i][j];
		}
	}

	for(int i = 0; i < v; i++)
		if(tmp[i] < vita[i])	return false;
	return true;
}

int main()
{
	freopen("holstein.in", "r", stdin);
	freopen("holstein.out", "w", stdout);
    while(~scanf("%d", &v)) {
		for(int i = 0; i < v; i++)	scanf("%d", &vita[i]);
		scanf("%d", &g);
		for(int i = 0; i < g; i++) {
			for(int j = 0; j < v; j++) {
				scanf("%d", &food[i][j]);
			}
		}


		int status = -1;
		for(int s = 0; s < (2 << 15); s++) {
			if(check(s) && (status == -1 || count_bit(status) > count_bit(s))) {
				status = s;
			}
		}

		int p = count_bit(status);
		get_ans(status);
		//printf("#%d\n", status);
		printf("%d ", p);
		for(int i = 0; i < ans.size(); i++)
			printf("%d%c", ans[i], i + 1 == ans.size() ? '\n' : ' ');
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章