Robberies-逆向思维01背包

HDU - 2955

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.
Input
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 .
Output
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.
Sample Input
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
Sample Output
2
4
6

题意:
可以抢劫n家银行,小偷要中保证在他抢劫中被抓的概率低于P(最高的被抓概率)的前提下,抢劫获得最大的钱。给出每个银行可获得的钱和被抓的概率
思路
首先同一以下概率,因为题中要计算安全的情况,我们只看成功的概率 p=1.0-p 表示最低的成功概率。对于每家银行保存pi=1-pi,表示不被抓的概率。
因为这道题p为浮点数,用dp数组不能把它当成费用来看了。
这是一道稍逆向思维的dp。
用dp[j]表示获得j价值的最大成功概率。状态转移方程为:
dp[j]=max(dp[j-v[i]]*p[i],dp[j])
核心代码
dp[0]=1;
for(int i=1;i<=n;i++)
  for(int j=sum;j>=w[i];j–)
    dp[j]=max(dp[j-v[i]]*p[i],dp[j])

最后从后向前遍历dp,当dp[j]>=p时,j即为不被抓的前提获得的最大钱

c++代码

#include
    #include
    #include
    #include
    #include
    using namespace std;
    const double eps = 1e-5;
    const int maxn=1e5;
    int v[maxn];
    double dp[maxn];
    double p[maxn];
    int main(){
    	int T,n;
    	double P;
    	scanf("%d",&T);
    	while(T--){
    		memset(dp,0,sizeof dp);
    		memset(v,0,sizeof v);
    		memset(p,0,sizeof p);
    		scanf("%lf %d",&P,&n);
    		int sum=0;
    		P=1.0-P; //最低成功概率 
    		for(int i=1;i<=n;i++){
    			scanf("%d %lf",&v[i],&p[i]);
    			p[i]=1.0-p[i]; //一次成功的概率 
    			sum+=v[i];
    		}
    		dp[0]=1;//偷0 成功1 
    		for(int i=1;i<=n;i++){				//获得价值为j时,最高的成功概率 
    			for(int j=sum;j>=v[i];j--){
    				dp[j] = max(dp[j-v[i]]*p[i] ,dp[j]);  //p*p表示dp加上的vi都成功了 
    			}
    		}
    		for(;sum>=0;sum--){	
    			if(dp[sum]>=P) break;
    		}
    		cout<<sum<<endl;
    	}
    	return 0;
    }

你可能感兴趣的:(I,like,for,you,to,be,still)