dp入门经典——01背包(3)<变式>
Robberies
The aspiring Roy the Robber has seen a lot of American movies, and knows that the bad guys usually gets caught in the end, often because they become too greedy. He has decided to work in the lucrative business of bank robbery only for a short while, before retiring to a comfortable job at a university.
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.
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背包的变式题,运用乘法原理来计算拿到i不被抓的最大概率
状态转移方程:dp[j]=max(dp[j],dp[j-bank[i].money]*bank[i].pi)
*/
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct Bank
{
int money;
double pi; //不被抓的概率
}bank[100+10];
double dp[10000+10]; //拿到i钱后不被抓的最大概率
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
double p;
int maxn=0,n;
scanf("%lf %d",&p,&n);
p=1.0-p; //转换为逃跑概率
for(int i=1;i<=n;i++){
scanf("%d %lf",&bank[i].money,&bank[i].pi);
bank[i].pi=1-bank[i].pi; //不被抓概率
maxn+=bank[i].money;
}
memset(dp,0,sizeof(dp));
dp[0]=1.0; //不拿钱时不被抓概率为1
for(int i=1;i<=n;i++)
for(int j=maxn;j>=bank[i].money;j--)
dp[j]=max(dp[j],dp[j-bank[i].money]*bank[i].pi);
for(int i=maxn;i>=0;i--)
{
if(dp[i]>p)
{
printf("%d\n",i); //i为拿到的钱数
break;
}
}
}
return 0;
}