每日一题之 hiho206 Guess Number with Lower or Higher Hints

描述
There is a game about guessing number between 1 and N. This game is played by two people A and B. When A guesses a number(e.g. 5), he needs to pay that amount of dollars($5). Then B will give a hint whether A’s guess is lower, higher or correct. B will choose the hint that forces to gain maximal amount of earning as long as it’s not conlict with previous hints.

Assume they are both smart enough. What is the minimal amount that A needs to pay to finish this game? That is, there is only one number left and A will surely guess it right. Careful: B does not have a fixed number in mind.

输入
An integer N. (1 <= N <= 200)

输出
The minimal amount A needs to pay.

样例输入
5
样例输出
6

题意:

两个人玩猜数字的游戏,范围是1到N,B心中想一个数,然后A猜一个数k,并付 k dollar的费用,这时候B会告诉A,猜的数是高了,低了,还是猜对了,并且B每次的提示都要和前面所有的提示不冲突。B要使得尽可能的让A多出钱,而A要尽可能的少出钱,求A猜对B心中想的数要付出的最小代价

思路:

刚开始扫一眼的时候以为是博弈论的问题,读完题目之后感觉是道dp,正好最近想练习一下dp,说说思路,我们可以用dp[l][r]来表示猜对B心中的数要付出的最小的代价,那么A可以猜区间 [l,r]内的任意一个数,假设现在A猜了k,由于B会使得自己的收益最大,那么肯定会考虑区间[l,k-1],[k+1,r]这连个区间的代价谁更大,并且选择那个区间让A继续猜。根据这个思想,我们可以用区间DP来解决这个问题,先枚举小区间,得到小区间的最优解,再合并成大区间得到全局最优解。最后dp[1][n]就是答案。

#include <cstdio>
#include <iostream>
#include <vector>

using namespace std;

const int maxn = 1e9+7;

int main()
{

    int n;
    int dp[205][205];
    cin >> n;

    for (int l = n; l > 0; --l) {
        for (int r = l+1; r <= n; ++r) {
            dp[l][r] = maxn;
            for (int k = l; k <= r; ++k) {
                dp[l][r] = min(dp[l][r],max(dp[l][k-1],dp[k+1][r]) + k);
            }
        }
    }

    cout << dp[1][n] << endl;


    return 0;
}

猜你喜欢

转载自blog.csdn.net/u014046022/article/details/80637561
今日推荐