Coins in a Line
来源:互联网 发布:中国电信cn2网络 编辑:程序博客网 时间:2024/05/01 11:40
题目来源: http://leetcode.com/2011/02/coins-in-line.html
二维DP。代码如下:
#include <iostream>#include <vector>#include <cassert>using namespace std;const int MAX_N = 100; void printMoves(int P[][MAX_N], int A[], int N) { int sum1 = 0, sum2 = 0; int m = 0, n = N-1; bool myTurn = true; while (m <= n) { int P1 = P[m+1][n]; // If take A[m], opponent can get... int P2 = P[m][n-1]; // If take A[n] cout << (myTurn ? "I" : "You") << " take coin no. "; if (P1 <= P2) { cout << m+1 << " (" << A[m] << ")"; m++; } else { cout << n+1 << " (" << A[n] << ")"; n--; } cout << (myTurn ? ", " : ".\n"); myTurn = !myTurn; } cout << "\nThe total amount of money (maximum) I get is " << P[0][N-1] << ".\n";}int maxMoney(int A[], int N) { int P[MAX_N][MAX_N] = {0}; int a, b, c; for (int i = 0; i < N; i++) { for (int m = 0, n = i; n < N; m++, n++) { assert(m < N); assert(n < N); a = ((m+2 <= N-1) ? P[m+2][n] : 0); b = ((m+1 <= N-1 && n-1 >= 0) ? P[m+1][n-1] : 0); c = ((n-2 >= 0) ? P[m][n-2] : 0); P[m][n] = max(A[m] + min(a,b), A[n] + min(b,c)); } } printMoves(P, A, N); return P[0][N-1];}int maxMoney2(int A[], int n){int P[MAX_N][MAX_N] = {0};for(int i=0; i<n; i++)P[i][i] = A[i];for(int len=2; len<=n; len++){for(int i=0; i+len<=n; i++){int j = i+len-1;if(len == 2){P[i][j] = max(A[i], A[j]);}else{int a1 = A[i] + min(P[i+2][j], P[i+1][j-1]);int a2 = A[j] + min(P[i+1][j-1], P[i][j-2]);P[i][j] = max(a1, a2);}}}printMoves(P, A, n);return P[0][n-1];}int main(){int A[] = { 3, 2, 2, 3, 1, 2 };int res1 = maxMoney(A, 6);int res2 = maxMoney2(A, 6);cout << res1 << " " << res2 << endl;return 0;}
0 0
- Coins in a Line
- coins in a line
- Coins in a Line
- lintcode:Coins in a Line
- [LintCode]Coins in a Line
- #394 Coins in a Line
- **[Lintcode]Coins in a Line
- Coins in a line II lintcode
- [LintCode] Coins in a line II
- #395 Coins in a Line II
- **[Lintcode]Coins in a Line II
- LeetCode题-coins in a line
- 【LintCode】Coins in a Line 硬币排成行
- lintcode coins-in-a-line 硬币排成线
- lintcode coins-in-a-line-ii 硬币排成线ii
- 03动态规划-04coins-in-a-line
- dynamica programming coins in line
- 394.Coins in a Line-硬币排成线(中等题)
- uva 227
- 程序填充题2
- 大数乘法
- 最大子数组问题及C语言实现
- objective-c中的SEL
- Coins in a Line
- 9种排序算法性能之比较之----插入排序
- (待解决)XNA “System.OutOfMemoryException” 内存溢出?
- Linux 目录和文件的默认访问权限——umask
- linux0.11学习笔记(2)
- 1的个数
- [leetcode] Maximum Product Subarray
- 二叉树前序遍历的非递归实现(京东笔试考过)
- java获取中国城市代码 中国城市ID(天气预报可用哦)