题目连接:http://acm.pku.edu.cn/JudgeOnline/problem?id=24871
1,这道题与其说是个搜索题目,不如说是一个贪心选择题
2,题目的解应该是一个子集,所以按照子集树的算法框架写了一个程序,超时了!
3,降序排序,每次选择最多的就可以了!
版本一:
#include <iostream>
using namespace std;
#define MAX 1000
struct Prob
{
int num[MAX];
int size;
int tar;
int left;
int res;
int cur;
int rx;
int cx;
void Init()
{
left = res = cur = 0;
rx = 1001;
cx = 0;
}
void Work(int cur)
{
if(cur == size)
{
if(res >= tar && cx < rx)
rx = cx;
}
else
{
if(res < tar)
{
res += num[cur];
++cx;
Work(cur+1);
--cx;
res -= num[cur];
}
left -= num[cur];
if(res + left >= tar)
Work(cur+1);
left += num[cur];
}
}
};
int main()
{
freopen("in.txt","r",stdin);
Prob pb;
int i,j,t;
cin >> t;
i = 1;
while(i <= t)
{
pb.Init();
cin >> pb.tar >> pb.size;
for(j = 0;j < pb.size;++j)
{
cin >> pb.num[j];
pb.left += pb.num[j];
}
if(pb.left < pb.tar)
printf("Scenario #%d:/nimpossible/n/n",i);
else
{
pb.Work(0);
printf("Scenario #%d:/n%d/n/n",i,pb.rx);
}
++i;
}
return 0;
}
版本二:
#include <iostream>
#include <algorithm>
using namespace std;
#define MAX 1000
bool less(int a,int b)
{
return a > b;
}
int main()
{
freopen("in.txt","r",stdin);
int num[MAX],size,tar,res;
int i,j,t;
cin >> t;
i = 1;
while(i <= t)
{
cin >> tar >> size;
for(j = 0;j < size;++j)
cin >> num[j];
sort(num,num+size,less);
for(res = j = 0;j < size;++j)
{
res += num[j];
if(res >= tar)
break;
}
if(j == size)
printf("Scenario #%d:/nimpossible/n/n",i);
else
printf("Scenario #%d:/n%d/n/n",i,j+1);
++i;
}
return 0;
}