您的位置:首页 > 其它

LintCode "Coins in a Line II" !

2015-11-09 12:57 483 查看
Nice one to learn: DP + Game Theory
https://lefttree.gitbooks.io/leetcode/content/dynamicProgramming2/coinsInLine2.html

In game theory, we assume the other player always take optimal step too. Combining with DP, we put this assumption together with each DP selection.

class Solution {
public:
/**
* @param values: a vector of integers
* @return: a boolean which equals to true if the first player will win
*/
bool firstWillWin(vector<int> &values) {
int n = values.size();
if(n<2) return true;

// Backward DP: since dp[a] -> dp[b] where a > b
vector<long long> dp(n, 0);
// init
dp[n-1] = values[n-1]; // pick 1
dp[n-2] = values[n-2] + values[n-1]; // pick 2

for(int i = n - 3; i >= 0; i --)
{
int dp2 = 0,dp3 = 0, dp4 = 0;
if(i < n - 4) dp4 = dp[i + 4];
if(i < n - 3) dp3 = dp[i + 3];
if(i < n - 2) dp2 = dp[i + 2];

// we pick min because the other player is smart too
int v1 = values[i] + min(dp2, dp3); // pick 1
int v2 = values[i] + values[i + 1] + min(dp3, dp4); // pick 2
dp[i] = max(v1, v2);
}

long long suma = accumulate(values.begin(), values.end(), 0);
return dp[0] > (suma - dp[0]);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: