【DP】 HDOJ 3516 Tree Construction

1606 단어 HDU
돌멩이 합병 그 문제와 유사하다...사각형으로 최적화하면 돼...
#include <iostream>
#include <queue> 
#include <stack> 
#include <map> 
#include <set> 
#include <bitset> 
#include <cstdio> 
#include <algorithm> 
#include <cstring> 
#include <climits>
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 1005
#define maxm 300006
#define eps 1e-10
#define mod 1315423911
#define INF 1e9
#define lowbit(x) (x&(-x))
#define mp make_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid 
#define rson o<<1 | 1, mid+1, R 
typedef long long LL;
typedef unsigned long long ULL;
//typedef int LL;
using namespace std;

struct node
{
	int x, y;
}p[maxn];
int dp[maxn][maxn];
int s[maxn][maxn];
int n;

void read(void)
{
	for(int i = 1; i <= n; i++) scanf("%d%d", &p[i].x, &p[i].y);
}

void work(void)
{
	for(int i = 0; i <= n; i++)
		for(int j = 0; j <= n; j++)
			dp[i][j] = INF;
	for(int i = 1; i <= n; i++) dp[i][i] = 0, s[i][i] = i;
	for(int len = 2; len <= n; len++) {
		for(int i = 1; i + len -1 <= n; i++) {
			int j = i + len - 1, kk;
			int a = s[i][j-1], b = min(s[i+1][j], j-1);
			for(int k = a; k <= b; k++) {
				int w = p[k+1].x - p[i].x + p[k].y - p[j].y;
				if(dp[i][j] > dp[i][k] + dp[k+1][j] + w)
					kk = k, dp[i][j] = dp[i][k] + dp[k+1][j] + w;
			}
			s[i][j] = kk;
		}
	}
	printf("%d
", dp[1][n]); } int main(void) { while(scanf("%d", &n)!=EOF) { read(); work(); } return 0; }

좋은 웹페이지 즐겨찾기