//
// main.cpp
// POJ 1661 DP
//
// Created by 鄭喆君 on 8/12/14.
// Copyright (c) 2014 itcast. All rights reserved.
//
#include<cstdio>
#include<cstring>
#include<iostream>
#include<iomanip>
#include<queue>
#include<cmath>
#include<stack>
#include<map>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;
typedef long long LL;
const int int_max = 0x07777777;
const int int_min = 0x80000000;
struct Node {
int x,y,h;
//Node(int _x, int _y, int _h):x(_x),y(_y),h(_h){}
};
int cmp (const void* a, const void* b){
return ((Node*)b)->h - ((Node*)a)->h;
}
int N,X,Y,MAXH;
Node nodes[1100];
int dp[1100][2];
int main(int argc, const char * argv[])
{
int t;
scanf("%d", &t);
while (t--) {
scanf("%d %d %d %d", &N, &X, &Y, &MAXH);
for(int i = 0; i < N; i++){
int x,y,h;
scanf("%d %d %d", &x, &y, &h);
Node temp;
temp.x = x;
temp.y = y;
temp.h = h;
nodes[i] = temp;
}
qsort(nodes, N, sizeof(nodes[0]), cmp);
memset(dp, -1, sizeof(dp));
int starti = -1;
for(int i = 0; i < N; i++){
if(Y-nodes[i].h<=MAXH && X>=nodes[i].x && X<=nodes[i].y){
starti = i;
dp[i][0] = Y-nodes[i].h + X-nodes[i].x;
dp[i][1] = Y-nodes[i].h + nodes[i].y-X;
break;
}
}
if(starti==-1){
printf("%d\n", Y);
continue;
}
for(int i = starti; i < N; i++){
if(dp[i][0]==-1) continue;
for(int j = i+1; j < N; j++){
if(nodes[i].h-nodes[j].h > MAXH) break;
if(nodes[i].x>=nodes[j].x && nodes[i].x<=nodes[j].y){
int xx = nodes[i].h-nodes[j].h + nodes[i].x-nodes[j].x;
int yy = nodes[i].h-nodes[j].h + nodes[j].y-nodes[i].x;
if(dp[j][0]==-1 || dp[j][0]>dp[i][0]+xx) dp[j][0] = dp[i][0]+xx;
if(dp[j][1]==-1 || dp[j][1]>dp[i][0]+yy) dp[j][1] = dp[i][0]+yy;
break;
}
}
for(int j = i+1; j < N; j++){
if(nodes[i].h-nodes[j].h > MAXH) break;
if(nodes[i].y>=nodes[j].x && nodes[i].y<=nodes[j].y){
int xx = nodes[i].h-nodes[j].h + nodes[i].y-nodes[j].x;
int yy = nodes[i].h-nodes[j].h + nodes[j].y-nodes[i].y;
if(dp[j][0]==-1 || dp[j][0]>dp[i][1]+xx) dp[j][0] = dp[i][1]+xx;
if(dp[j][1]==-1 || dp[j][1]>dp[i][1]+yy) dp[j][1] = dp[i][1]+yy;
break;
}
}
}
int result = int_max;
for(int i = N-1; i >= 0; i--){
if(dp[i][0]==-1) continue;
if(nodes[i].h > MAXH) break;
int j;
for(j = i+1; j < N; j++){
if(nodes[i].h-nodes[j].h<=MAXH && ((nodes[i].x>=nodes[j].x&&nodes[i].x<=nodes[j].y)))
break;
}
if(j==N) result = (result > dp[i][0]+nodes[i].h ? dp[i][0]+nodes[i].h : result);
}
for(int i = N-1; i >= 0; i--){
if(dp[i][0]==-1) continue;
if(nodes[i].h > MAXH) break;
int j;
for(j = i+1; j < N; j++){
if(nodes[i].h-nodes[j].h<=MAXH && ((nodes[i].y>=nodes[j].x&&nodes[i].y<=nodes[j].y)))
break;
}
if(j==N) result = (result > dp[i][1]+nodes[i].h ? dp[i][1]+nodes[i].h : result);
}
printf("%d\n",result);
}
}
POJ 1661 DP 注意邊界條件。。。WA了好幾次
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.