国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

leecode 解題總結:3383. Ransom Note

2019-11-06 08:20:18
字體:
來源:轉載
供稿:網友
#include <iostream>#include <stdio.h>#include <vector>#include <string>using namespace std;/*問題:We are playing the Guess Game. The game is as follows:I pick a number from 1 to n. You have to guess which number I picked.Every time you guess wrong, I'll tell you whether the number I picked is higher or lower.However, when you guess a particular number x, and you guess wrong, you pay $x. You win the game when you guess the number I picked.Example:n = 10, I pick 8.First round:  You guess 5, I tell you that it's higher. You pay $5.Second round: You guess 7, I tell you that it's higher. You pay $7.Third round:  You guess 9, I tell you that it's lower. You pay $9.Game over. 8 is the number I picked.You end up paying $5 + $7 + $9 = $21.分析:明顯得,如果把答案設置在為n,采用二分法需要獲取的代價是最多的。假設n=10,最終選取的也是10,剛開始low = 1 , high=10 , mid=(1+10)/2=5,付出5  , (low + high)/2low = 6 , high=10 , mid=8,    ( (low+high)/2 + 1 + high ) / 2 = 3/4 * high + 1/4 * low + 1/2 low = 9 , high=10, mid=9 ,low = 10, high=10 , mid=10,猜中總共花費=5 + 8 + 9 = 22n=9,5+7+8=20輸入:109輸出:1614用動態規劃來做:關鍵:1 參考:http://blog.csdn.net/adfsss/article/details/51951658設任意猜一個數為i,保證獲勝說花的錢:i + max( dp(1,i-1) , dp(i+1,n) )這里dp(x,y)表示猜范圍在(x,y)的數保證能贏應花的錢遍歷1~n作為猜的數,求出其中的最小值就是答案。2//遞歸計算,因為要保證贏,我們一直假設當前猜數i是猜錯的,然后一直到最后start >= end,就可以說明猜正確,最后一次耗費0int temp = i + max( cost(dp , start , i - 1 ) , cost(dp , i+1 , end) );//對于每個初始猜數i,計算其最多需要多少錢才能猜正確,然后從里面選擇一個初始猜數最小的即可result = min(temp , result);dp.at(start).at(end) = result;//記錄最終結果,便于記憶化搜索*/class Solution {public:	int cost(vector< vector<int> >& dp , int start , int end)	{		if(dp.empty() ||start < 0 || end >= dp.size() || start >= end)		{			return 0;		}		if(dp.at(start).at(end) != 0)		{			return dp.at(start).at(end);		}		int result = INT_MAX;		for(int i = start ; i <= end ; i++)		{			//遞歸計算,因為要保證贏,我們一直假設當前猜數i是猜錯的,然后一直到最后start >= end,就可以說明猜正確,最后一次耗費0			int temp = i + max( cost(dp , start , i - 1 ) , cost(dp , i+1 , end) );			//對于每個初始猜數i,計算其最多需要多少錢才能猜正確,然后從里面選擇一個初始猜數最小的即可			result = min(temp , result);		}		dp.at(start).at(end) = result;//記錄最終結果,便于記憶化搜索		return result;	}    int getMoneyAmount(int n) {		vector< vector<int> > dp(n + 1 , vector<int>(n+1 , 0));		int result = cost(dp , 1 , n);		return result;	}};void PRocess(){	 int num;	 Solution solution;	 while(cin >> num )	 {		 int result = solution.getMoneyAmount(num);		 cout << result << endl;	 }}int main(int argc , char* argv[]){	process();	getchar();	return 0;}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 白玉县| 江陵县| 全椒县| 天全县| 康保县| 罗甸县| 湘潭县| 庆阳市| 历史| 滨海县| 勐海县| 堆龙德庆县| 葫芦岛市| 班玛县| 昌江| 会宁县| 阿克陶县| 泸定县| 明星| 广东省| 乌海市| 余姚市| 枣庄市| 朔州市| 乐山市| 固原市| 綦江县| 嵩明县| 台江县| 元谋县| 瑞金市| 丹阳市| 宜川县| 通州市| 科技| 宿松县| 乐陵市| 潮州市| 江油市| 定西市| 吴堡县|