原题链接: http://acm.hdu.edu.cn/showproblem.php?pid=4152
测试样例
Sample Input
4
100 200 300 400
3
100 100 400 500
100 -10 50 300
100 100 -50 -50
Sample Output
2 1 3
题意: 你有 n n n个目标和 m m m个习惯,每个目标都有一个对应的要求。现在你的每个习惯对你的 n n n个目标都有影响,求最多保存的习惯数量使得达成要求。
解题思路: 这道题我们不确定是选择哪种方案,不确定哪种是最优的。这则可以采用dfs爆搜,让计算机去计算,返回最优解,记住我们每次都要更新最优解的分配方案。OK,具体看代码。
AC代码
/*
*邮箱:unique_powerhouse@qq.com
*blog:https://me.csdn.net/hzf0701
*注:文章若有任何问题请私信我或评论区留言,谢谢支持。
*
*/
#include<bits/stdc++.h> //POJ不支持
#define rep(i,a,n) for (int i=a;i<=n;i++)//i为循环变量,a为初始值,n为界限值,递增
#define per(i,a,n) for (int i=a;i>=n;i--)//i为循环变量, a为初始值,n为界限值,递减。
#define pb push_back
#define IOS ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
#define fi first
#define se second
#define mp make_pair
using namespace std;
const int inf = 0x3f3f3f3f;//无穷大
const int maxn = 30;//最大值。
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
//*******************************分割线,以上为自定义代码模板***************************************//
int n,m;//目标数和习惯数。
int goals[maxn],habbits[maxn][maxn];
bool vis[maxn];//判断习惯是否被选取。
bool result[maxn];//存储最优解。
int ans=0;
bool junge(){
int temp=0;
rep(i,0,n-1){
temp=0;
rep(j,0,m-1){
if(vis[j])temp+=habbits[j][i];
}
if(temp<goals[i])
return false;
}
return true;
}
void dfs(int cnt){
if(cnt==m){
if(junge()){
int tot=0;
rep(i,0,m-1){
if(vis[i]){
tot++;
}
}
if(ans<tot){
ans=tot;
rep(i,0,m-1){
result[i]=vis[i];
}
}
}
return;
}
vis[cnt]=true;dfs(cnt+1);
vis[cnt]=false;dfs(cnt+1);
}
int main(){
//freopen("in.txt", "r", stdin);//提交的时候要注释掉
IOS;
while(cin>>n){
rep(i,0,n-1){
cin>>goals[i];
}
cin>>m;
rep(i,0,m-1){
rep(j,0,n-1){
cin>>habbits[i][j];
}
}
memset(vis,false,sizeof(vis));
memset(result,false,sizeof(vis));
ans=0;
dfs(0);
cout<<ans;
rep(i,0,m-1){
if(result[i])
cout<<" "<<i+1;
}
cout<<endl;
}
return 0;
}