[HEOI2013]Segment
题面
再次推销自己的博客。
这题和P4254 [JSOI2008]Blue Mary开公司 很像,只不过维护的不是直线,而是线段。
其实没什么区别,按照普通线段树的思路,把线段拆分成不超过
往这些完全被包含的区间中插入线段等同于插入直线。
时间复杂度多了一个
代码有很多细节要调,下面说几点注意事项:
-
注意精度,斜率为小数,注意不能直接比较是否相等,会被 Hack 掉。
-
注意
x0=x1 的问题,题目里也说了,特判否则计算斜率会 RE。 -
注意更新最优线段时要加上判断编号大小。
代码:
#include<bits/stdc++.h>
#define N 40005
#define eps 1e-8
using namespace std;
#define CALC(a,b,c) (a=(a+b-1)%c+1)
int n,lastans,cnt,Best[N<<2];
vector <double> K(1,0),B(1,0);
inline double GetY(int id,int x){
return x*K[id]+B[id];
}
inline bool Cmp(int id1,int id2,int x){
double a(GetY(id1,x)),b(GetY(id2,x));
return abs(a-b)>eps?a>b:id1<id2;
}
#define ls (k<<1)
#define rs (k<<1|1)
#define mid (l+r>>1)
inline void Insert(int k,int l,int r,int s,int t,int id){
if(l>t||r<s) return;
if(s<=l&&r<=t){
if(!Best[k]) return void(Best[k]=id);
if(Cmp(id,Best[k],mid)) swap(id,Best[k]);
if(l==r||abs(K[id]-K[Best[k]])<eps) return;
if(Cmp(id,Best[k],l)) Insert(ls,l,mid,s,t,id);
if(Cmp(id,Best[k],r)) Insert(rs,mid+1,r,s,t,id);
return;
}
Insert(ls,l,mid,s,t,id);
Insert(rs,mid+1,r,s,t,id);
}
inline int Query(int k,int l,int r,int x){
if(l==r) return Best[k];
int res(x<=mid?Query(ls,l,mid,x):Query(rs,mid+1,r,x));
return Cmp(res,Best[k],x)?res:Best[k];
}
int main(){
scanf("%d",&n);
while(n--){
int op;scanf("%d",&op);
if(op){
int a,b,c,d;scanf("%d%d%d%d",&a,&b,&c,&d);
CALC(a,lastans,39989);CALC(b,lastans,1000000000);
CALC(c,lastans,39989);CALC(d,lastans,1000000000);
if(a>c) swap(a,c),swap(b,d);++cnt;
if(a==c) K.push_back(0),B.push_back(max(b,d));
else K.push_back(double(b-d)/(a-c)),B.push_back(b-a*K[cnt]);
Insert(1,0,N,a,c,cnt);
}
else{
int x;scanf("%d",&x);CALC(x,lastans,39989);
printf("%d\n",(lastans=Query(1,0,N,x)));
}
}
return 0;
}