Robberies 01背包

题目表述:

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. 

输入:

The first line of input gives T, the number of cases. For each scenario, the first line of input gives a floating point number P, the probability Roy needs to be below, and an integer N, the number of banks he has plans for. Then follow N lines, where line j gives an integer Mj and a floating point number Pj . 
Bank j contains Mj millions, and the probability of getting caught from robbing it is Pj .

输出:

For each test case, output a line with the maximum number of millions he can expect to get while the probability of getting caught is less than the limit set. 

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

大体题意就是,给出一个被抓的概率,要在这个概率之下(超过这个概率就会被抓了),拿到最多的钱。可以把sum(所有的钱的和)看作背包体积,概率看作财富。状态转移方程为f[j]=max(f[j],f[j-mj[i]]*(1-pj[i]),意思是拿j这么多钱的时候,选择逃跑概率大的哪一个。至于为什么要用逃脱的概率而不是用被抓的概率,借用别人的理解:

只要抢一所银行被抓,那么无论后面如何发展,其状态都应为被抓,被抓的概率乘被抓的概率也就没有了实际意义,而转化成不被抓的概率,则避免了这个问题。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
double max(double a,double b)//输出大的哪一个数
{
    return a>b?a:b;
}
int main()
{
    int t,m;
    int mj[110];
    double pj[110],f[10000],p;//f的范围要定义的大一点,因为n的范围是大于0小于100,所以sum的范围肯定大于100
    cin>>t;
    while(t--)
    {
        int sum=0;
        memset(f,0,sizeof(f));
        cin>>p>>m;
        for(int i=1;i<=m;i++)
        {
            cin>>mj[i]>>pj[i];//这里的p[i]是被抓概率,和下面的要区别开
            sum+=mj[i];
            pj[i]=1-pj[i];//让p[i]成为逃脱概率

        }
        f[0]=1;//这里的意思是一分钱都不拿的情况下逃脱的概率为1
        for(int i=1;i<=m;i++)
        {
            for(int j=sum;j>=mj[i];j--)
            {
                f[j]=max(f[j],f[j-mj[i]]*pj[i]);
            }
        }
        for(int i=sum;i>=0;i--)
        {
            if(f[i]>(1-p))//因为i是从大到小的,所以拿到i的钱逃脱的概率只要大于(1-p),那就直接输出i,这就是我们在可以逃脱情况下可以拿到最多的钱
            {
                cout<< i <<endl;
                break;
            }
        }
    }
    return 0 ;
}
 

猜你喜欢

转载自blog.csdn.net/zhangjinlei321/article/details/81395936