POJ_1661,dfs,通过二维记忆数组缩短时间
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
struct plat{
int x1,x2,height;
};
vector <plat> plats;
int maxheight;
int times[1010][2];
bool comp(plat p1,plat p2){
return p1.height>p2.height;
}
int l_or_r(int x,int currplat){
if(plats[currplat].height==0){
times[currplat][0]=0;
times[currplat][1]=0;
return 0;
}
if(times[currplat][0]!=-1 && times[currplat][1]!=-1)
return min(times[currplat][0]+x-plats[currplat].x1,times[currplat][1]+plats[currplat].x2-x);
int l_plat,r_plat;
for(l_plat=currplat+1;l_plat<plats.size();l_plat++)
if(plats[currplat].x1>=plats[l_plat].x1 && plats[currplat].x1<=plats[l_plat].x2) break;
for(r_plat=currplat+1;r_plat<plats.size();r_plat++)
if(plats[currplat].x2>=plats[r_plat].x1 && plats[currplat].x2<=plats[r_plat].x2) break;
if(plats[currplat].height-plats[l_plat].height>maxheight)
times[currplat][0]=999999;
if(plats[currplat].height-plats[r_plat].height>maxheight)
times[currplat][1]=999999;
if(times[currplat][0]==-1) times[currplat][0]=l_or_r(plats[currplat].x1,l_plat);
if(times[currplat][1]==-1) times[currplat][1]=l_or_r(plats[currplat].x2,r_plat);
return min(times[currplat][0]+x-plats[currplat].x1,times[currplat][1]+plats[currplat].x2-x);
}
int main(){
int test;
for(cin>>test;test>0;test--){
int n,x,y;
cin>>n>>x>>y>>maxheight;
int alltime=y,start=0;
plats.clear();
memset(times,-1,sizeof(times));
plat curr;
for(int i=0;i<n;i++){
int x1,x2;
cin>>x1>>x2>>curr.height;
curr.x1=min(x1,x2);
curr.x2=max(x1,x2);
plats.push_back(curr);
}
curr.x1=-999999;
curr.x2=999999;
curr.height=0;
plats.push_back(curr);
sort(plats.begin(),plats.end(),comp);
for(;start<n;start++)
if(y>=plats[start].height && x>=plats[start].x1 && x<=plats[start].x2) break;
if(start==n){
cout<<alltime<<endl;
continue;
}
cout<<alltime+l_or_r(x,start)<<endl;
}
return 0;
}