Robberies
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8013 Accepted Submission(s): 3031
![](https://i-blog.csdnimg.cn/blog_migrate/931cc59be308ad18cd98b5c8caec6454.jpeg)
For a few months now, Roy has been assessing the security of various banks and the amount of cash they hold. He wants to make a calculated risk, and grab as much money as possible.
His mother, Ola, has decided upon a tolerable probability of getting caught. She feels that he is safe enough if the banks he robs together give a probability less than this.
Bank j contains Mj millions, and the probability of getting caught from robbing it is Pj .
Notes and Constraints
0 < T <= 100
0.0 <= P <= 1.0
0 < N <= 100
0 < Mj <= 100
0.0 <= Pj <= 1.0
A bank goes bankrupt if it is robbed, and you may assume that all probabilities are independent as the police have very low funds.
3 0.04 3 1 0.02 2 0.03 3 0.05 0.06 3 2 0.03 2 0.03 3 0.05 0.10 3 1 0.03 2 0.02 3 0.05
2 4 6
这道题是我做的第二道01背包的,有关01背包的问题都比较明显,但需要一定的思考和转换。这道题,当我刚开始做的时候,我天真以为 概率的精度只会有两位,同时 只要 所偷的银行的概率的和 小于给定概率 就可以了。于是写了一个程序,测试数据是通过了,后来我发现我的想法太天真了。。。。orz
比如偷了a银行被抓的概率是pa,偷了b银行被抓的概率是pb 那么 偷了两家银行后 安全的概率不是1-pa-pb 而是 (1-pa)*(1-pb);
所有 当给出最大的被抓概率时,我们应该转为为这个人最低的安全概率为p=1-p;
所以这道题的状态转移方程为:
opt[j]=max(opt[j],opt[j-cost[i]]*w[i]);
解释一下:我们用opt【j】数组表示 当我们偷取金额j元时,所能得到的最大安全概率。
也就是 如果我们不偷第i件物品,如果之前可以获得j元,那么概率仍是opt【j】;
如果我们偷取第i件物品,那么概率就等于 偷取j-cost【i】元的安全概率 乘 偷取的第i件物品的安全概率。
到最后,我们从后向前循环,寻找大于最低安全概率的最大值j元 并输出
(擦,刚开始的p=1-p 我忘写了 结果多坚持了 1小时 !!!orz)
#include<iostream>
using namespace std;
int cost[105];
double w[105];
double opt[10500];
double max(double a,double b)
{
return a>b?a:b;
}
int zeroonepack(int n,int m,double p)
{
memset(opt,0,sizeof(opt));
opt[0]=1;
int i,j,t;
for(i=1;i<=n;i++)
{
for(j=m;j>=cost[i];j--)
opt[j]=max(opt[j],opt[j-cost[i]] * w[i]);
}
for(i=m;i>=1;i--)
{
if(opt[i]-p>0.00000000001)
break;
}
return i;
}
int main()
{
int cas,n,i,ans,sumcost;
double p;
cin>>cas;
while(cas--)
{
cin>>p>>n;
p=1-p;
sumcost=0;
for(i=1;i<=n;i++)
{
cin>>cost[i]>>w[i];
w[i]=1-w[i];
sumcost+=cost[i];
}
ans=zeroonepack(n,sumcost,p);
cout<<ans<<endl;
}
return 0;
}