http://poj.org/problem?id=1661
1 #include <stdio.h> 2 #include <string.h> 3 #include <iostream> 4 #include <algorithm> 5 #include<math.h> 6 #define INF 100000000 7 using namespace std; 8 9 int n,m,maxx,num; 10 struct len{int l,r;}d[2002]; 11 struct point{int x,y,h;}p[2002]; 12 int cmp(point a,point b) 13 { 14 return a.h>b.h; 15 } 16 17 void solve(int k) 18 { 19 if(d[k].l!=INF||d[k].r!=INF) 20 return ; 21 for(int i=k+1;i<=n&&(p[k].h-p[i].h)<=maxx;i++) 22 { 23 if(p[k].x>=p[i].x&&p[k].x<=p[i].y) 24 { 25 if(i==n) 26 d[k].l=0; 27 else 28 { 29 solve(i); 30 d[k].l=min(d[i].r+abs(p[i].y-p[k].x),d[i].l+abs(p[i].x-p[k].x)); 31 } 32 break; 33 } 34 } 35 for(int i=k+1;i<=n&&(p[k].h-p[i].h)<=maxx;i++) 36 { 37 if(p[k].y>=p[i].x&&p[k].y<=p[i].y) 38 { 39 if(i==n) 40 d[k].r=0; 41 else 42 { 43 solve(i); 44 d[k].r=min(d[i].r+abs(p[i].y-p[k].y),d[i].l+abs(p[i].x-p[k].y)); 45 } 46 break; 47 } 48 } 49 } 50 51 52 53 int main() 54 { 55 int t; 56 scanf("%d",&t); 57 while(t--) 58 { 59 scanf("%d%d%d%d",&n,&p[0].x,&p[0].h,&maxx); 60 p[0].y=p[0].x; 61 int a,b; 62 for(int i=1;i<=n;i++) 63 { 64 scanf("%d%d%d",&a,&b,&p[i].h); 65 p[i].x=min(a,b); p[i].y=max(a,b); 66 } 67 p[++n].x=-INF; p[n].y=INF; p[n].h=0; 68 for(int i=0;i<n;i++) 69 d[i].l=d[i].r=INF; 70 sort(p,p+n+1,cmp); 71 d[n].l=0; d[n].r=0; 72 solve(0); 73 printf("%d ",min(d[0].l,d[0].r)+p[0].h); 74 } 75 return 0; 76 }