Light OJ 1031---Easy Game(区间DP)
题目链接
http://lightoj.com/volume_showproblem.php?problem=1031
Description
You are playing a two player game. Initially there are n integer numbers in an array and player A and B get chance to take them alternatively. Each player can take one or more numbers from the left or right end of the array but cannot take from both ends at a time. He can take as many consecutive numbers as he wants during his time. The game ends when all numbers are taken from the array by the players. The point of each player is calculated by the summation of the numbers, which he has taken. Each player tries to achieve more points from other. If both players play optimally and player A starts the game then how much more point can player A get than player B?
Input
Input starts with an integer T (≤ 100), denoting the number of test cases.
Each case contains a blank line and an integer N (1 ≤ N ≤ 100) denoting the size of the array. The next line contains N space separated integers. You may assume that no number will contain more than 4 digits.
Output
For each test case, print the case number and the maximum difference that the first player obtained after playing this game optimally.
Sample Input |
Output for Sample Input |
2 4 4 -10 -20 7 4 1 2 3 4 |
Case 1: 7 Case 2: 10 |
题意:有n个数排成一行,现在A和B两人从两端取任意个数(每次至少取一个),直到取完所有的数,A先取,求A取得数的和比B大多少?
思路:区间DP,dp[i][j] 表示区间i~j A取得数的和比B大多少,那么可以这样分析:对于区间i~j A先取sum[k]-sum[i-1]或sum[j]-sum[k](只能从两端取),然后该B取了,即对于区间k+1~j和i~k DP转换为B比A大多少了,所以状态转移方程为 dp[i][j]=max(dp[i][j],max(sum[k]-sum[i-1]-dp[k+1][j],sum[j]-sum[k]-dp[i][k]));
代码如下:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
int sum[];
int dp[][]; ///A比B大多少? int main()
{
int T,Case=;
int n;
cin>>T;
while(T--)
{
sum[]=;
scanf("%d",&n);
for(int i=;i<=n;i++)
{
scanf("%d",&sum[i]);
sum[i]+=sum[i-];
}
memset(dp,,sizeof(dp));
for(int i=;i<=n;i++)
dp[i][i]=sum[i]-sum[i-];
for(int len=;len<n;len++)
{
for(int i=;i<=n;i++)
{
if(i+len>n) break;
dp[i][i+len]=sum[i+len]-sum[i-];
for(int k=i;k<i+len;k++)
{
dp[i][i+len]=max(dp[i][i+len],max(sum[k]-sum[i-]-dp[k+][i+len],sum[i+len]-sum[k]-dp[i][k]));
}
}
}
printf("Case %d: %d\n",Case++,dp[][n]);
}
}
最新文章
- 浅谈Android样式开发之布局优化
- centos7 mariadb
- rake :You have already activated rake 10.1.0
- 【SAP BO】【DI】DataService 服务无法启动。错误1069:由于登录失败而无法启动服务
- IOS block使用中碰到的一个小坑
- 内核移植和文件系统制作(4):UBIFS根文件系统制作总结
- 如何获取DIV的id
- CentOS 7 内核更新后删除旧内核
- C#和asp.net执行外部EXE程序
- Introduction to REST #Reprinted#
- springMVC实现增删改查
- mysql explain结果含义
- Python 工厂函数和内建函数
- Mybatis获取传参
- TabHost实现底部导航栏
- 多个inputstream的情况下,watermark的值怎么赋值? kakfa中多个partition提取 watermark
- JVM类加载机制总结
- Vue.js更改调试地址端口号
- bzoj 2571: Getting Rid of the Holidays
- c++ 多态总结