您的位置:首页 > 其它

UVA10154->区间DP

2016-07-26 11:04 381 查看
题意:给出一些乌龟的重量和力量,求这些乌龟能叠出的龟塔的最大高度

题解:区间DP,dp[i][j]代表前i只乌龟叠j层的最小重量,从层数开始扩展转移,先求从1-n每个区间叠一层的质量,再求叠两层,以此类推

       状态转移方程:if(turtle[i].strength >= dp[i-1][j-1])
dp[i][j] = min(dp[i-1][j] , dp[i-1][j-1]+turtle[i].weight) ;
else
dp[i][j] = dp[i-1][j] ;

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
#include <cmath>
using namespace std ;
#define MAX 5700
#define INF 0x3f3f3f3f
int dp[MAX][MAX] ;
struct Node
{
int weight ;
int strength ;
}turtle[MAX];
bool comp(const struct Node &x ,const struct Node &y)
{
//if(x.strength == y.strength) return x.weight < y.weight ;
return x.strength < y.strength ;
}
int main()
{
int a , b , cnt = 1;
while(scanf("%d%d" , &a , &b) != EOF )
{
turtle[cnt].weight = a ;
turtle[cnt].strength = b - a ;
cnt ++ ;
}
//cout << cnt << endl ;
sort(turtle+1 , turtle + cnt+1 , comp) ;
memset(dp , INF , sizeof(dp)) ;
dp[0][0] = 0 ;
int ans = 0;
for(int j = 0 ; j <= cnt ; j ++)
{
for(int i = j + 1 ; i <=cnt ; i ++)
{
if(turtle[i].strength >= dp[i-1][j-1])
dp[i][j] = min(dp[i-1][j] , dp[i-1][j-1]+turtle[i].weight) ;
else
{
dp[i][j] = dp[i-1][j] ;
}
if(dp[i][j] != INF)
{
ans = max(ans , j) ;
//cout << ans << ' ' <<i <<' ' << j <<endl ;
}

}
}
printf("%d\n", ans);
return 0 ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: