As Harry Potter series is over, Harry has no job. Since he wants to make quick money, (he wants everything quick!) so he decided to rob banks. He wants to make a calculated risk, and grab as much money as possible. But his friends - Hermione and Ron have decided upon a tolerable probability P of getting caught. They feel that he is safe enough if the banks he robs together give a probability less than P.
Input starts with an integer T (≤ 100), denoting the number of test cases.
Each case contains a real number P, the probability Harry needs to be below, and an integer N (0 < N ≤ 100), the number of banks he has plans for. Then follow N lines, where line j gives an integer Mj (0 < Mj ≤ 100) and a real number Pj . Bank j contains Mj millions, and the probability of getting caught from robbing it is Pj. A bank goes bankrupt if it is robbed, and you may assume that all probabilities are independent as the police have very low funds.
For each case, print the case number and the maximum number of millions he can expect to get while the probability of getting caught is less than P.
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
Case 1: 2
Case 2: 4
Case 3: 6
For the first case, if he wants to rob bank 1 and 2, then the probability of getting caught is 0.02 + (1 - 0.02) * .03 = 0.0494 which is greater than the given probability (0.04). That's why he has only option, just to rob rank 2.
网上题解跟我最初的想法是不太一样的,其实是因为自己最初的想法无法实现,没办法才去看的题解。
自己的思路也是01背包,但是我的想啊是直接求解出答案的01背包。
我的方法(理论可以,实际不行):把一开始输入概率当做背包容量,每一个银行的概率当做物品的重量,发现如果这样去做的话背包的重量不好去遍历,因为是浮点数,所以这个方法不太好。
网上的解法是把各个银行金钱的和当做背包容量去做,dp【i】就代表了金钱为i的时候的最大成功概率。最后的时候筛选一下符合条件的数值就可以了
#include<bits/stdc++.h>
using namespace std;
const int M=240000;
int val[M];
double p[M],dp[M];
int main()
{
int kase;
scanf("%d",&kase);
for(int k=1; k<=kase; k++)
{
memset(dp,0,sizeof(dp));
dp[0]=1.0;///不抢100%不会被抓
double lim;
int n,v=0;
scanf("%lf%d",&lim,&n);
for(int i=1; i<=n; i++)
{
scanf("%d%lf",&val[i],&p[i]);
p[i]=1.0-p[i];
v+=val[i];
}
for(int i=1; i<=n; i++)
{
for(int j=v; j>=val[i]; j--)
{
dp[j]=max(dp[j],dp[j-val[i]]*p[i]);
}
}
for(int i=v; i>=0; i--)
{
if(lim>=1-dp[i])///判断是否合法,第一个合法值即为最大值
{
printf("Case %d: %d\n",k,i);
break;
}
}
}
}