#bzoj1506#双塔问题(Dp经典)
2017-09-05 22:04
141 查看
1506: 双塔问题
时间限制:1 Sec 内存限制: 64 MB
题目描述
第三题:双塔问题 2001年9月11日,一场突发的灾难将纽约世界贸易中心大厦夷为平地,Mr. F曾亲眼目睹了这次灾难。为了纪念"9?11"事件,Mr. F决定自己用水晶来搭建一座双塔。 Mr. F有N块水晶,每块水晶有一个高度,他想用这N块水晶搭建两座有同样高度的塔,使他们成为一座双塔,Mr. F可以从这N块水晶中任取M(1≤M≤N)块来搭建。但是他不知道能否使两座塔有同样的高度,也不知道如果能搭建成一座双塔,这座双塔的最大高度是多少。所以他来请你帮忙。给定水晶的数量N(1≤N≤100)和每块水晶的高度Hi(N块水晶高度的总和不超过2000),你的任务是判断Mr. F能否用这些水晶搭建成一座双塔(两座塔有同样的高度),如果能,则输出所能搭建的双塔的最大高度,否则输出"Impossible"。
输入
输入的第一行为一个数N,表示水晶的数量。第二行为N个数,第i个数表示第i个水晶的高度。输出
输出仅包含一行,如果能搭成一座双塔,则输出双塔的最大高度,否则输出一个字符串"Impossible"。样例输入
5 1 3 4 5 2
样例输出
7
定义
Dp[i][j]表示前i个水晶,搭建成高度差为j的双塔的共同最高高度
Dp[i][j] = Dp[i - 1][j],Dp[i - 1][j + H[i]], Dp[i - 1][j - H[i]] + H[i], Dp[i - 1][H[i] - j] + j
Code:
/*
For the i block,
we firstly have two choices, to put i block or not,
if not, we have f[i][j] = f[i - 1][j];
if so, we secondely have two choices, to put it onto the higher one or the shorter one.
the higher one: of course the dissmilarity will change into a bigger one.
we have f[i][j] = f[i - 1][j + H[i]]
the shorter one: we will have two situation for the dissmilarity.
H[i] > j two towers' positions of heights will be exchanged,
and the f will be added j
we have f[i][j] = f[i - 1][H[i] - j] + j
H[i] <= j two towers' positions of heights remain,
adn the f will added H[i]
we have f[i][j] = f[i - 1][j - H[i]] + H[i]
f[i][j]: i refers to there has already been i blocks which are used.
j refers to the dissmilarity between the higher one and the shorter one.
f refers to the height the two towers have.
f[i][j] = f[i - 1][j] not put i in
f[i - 1][j + H[i]] onto the higher
f[i - 1][H[i] - j] + j positions exchanged
f[i - 1][j - H[i]] + H[i] remain
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
using namespace std;
int H[110], f[110][2010];
int main(){
int N;
scanf("%d", &N);
for(int i = 1; i <= N; i++)
scanf("%d", &H[i]);
memset(f[0], -0x3f, sizeof(f[0]));
f[0][0] = 0;
for(int i = 1; i <= N; i++)
for(int j = 0; j <= 2000; j++){
f[i][j] = max(f[i - 1][j], f[i - 1][j + H[i]]);
if(j >= H[i])
f[i][j] = max(f[i][j], f[i - 1][j - H[i]] + H[i]);
else
f[i][j] = max(f[i][j], f[i - 1][H[i] - j] + j);
}
if(f
[0])
printf("%d\n", f
[0]);
else printf("Impossible\n");
return 0;
}
相关文章推荐
- LeetCode.368 Largest Divisible Subset(经典DP问题)
- hdu 2224 经典DP 双调旅行商问题
- 01背包问题——经典DP问题,优化与未优化
- 【DP】经典问题解析
- 【坑式dp】双塔问题
- HDU - 1003 - Max Sum && POJ - 1050 - To the Max (经典DP问题)
- 【bzoj1775】[Usaco2009 Dec]Vidgame 电视游戏问题 dp
- 经典问题-活动选择问题-DP和贪心
- 经典dp(动态规划)问题常用解决策略
- 括号匹配问题 区间DP经典问题
- bzoj 4318 osu 【三次方问题】【dp】
- 动态规划DP问题分类和经典题型
- (NYoj 269) VF --经典DP问题--下一个状态为前多个状态之和
- dp经典问题
- 入门经典--硬币问题dp递归加递推
- 动态规划的经典问题初探: Best Time to Buy and Sell Stock(DP)
- LCS 最长公共子序列(DP经典问题)
- 【转】POJ 1159 Palindrome【经典的DP回文问题】
- DP经典题型:石子合并问题
- bzoj1090(区间dp,字符串折叠问题)