思路很重要啊,一开始看了之后,完全不知道要维护什么,看了网上的思路,咋就没想到呢。。。
将多边形分解成梯形,每次维护当前区间面积,向下传递的梯形上下底(相似三角形)。
ACcode:
#include<cmath>
#include<cstdio>
#include<iostream>
#include<algorithm>
#define eps 1e-4
using std::sort;
using std::swap;
const int nsize=25555;
struct Operate
{
int op,v;
int x[6],y[6];
} c[nsize];
double sum[nsize<<5];
int X[nsize<<3],top;
double len[nsize<<5],lh[nsize<<5],rh[nsize<<5];
int Fin(int key,int len)
{
int l=0,r=len;
while (l<=r)
{
int m=(l+r)>>1;
if (X[m]<key) l=m+1;
else if (X[m]>key) r=m-1;
else return m;
}
return -1;
}
void build(int rt,int l,int r)
{
sum[rt]=lh[rt]=rh[rt]=0;
len[rt]=X[r+1]-X[l];
if (l==r) return ;
int m=(l+r)>>1;
build(rt<<1,l,m);
build(rt<<1|1,m+1,r);
}
void PushUp(int rt)
{
sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
double Cat(double ly,double ry,int dis,int k)
{
return ly+(ry-ly)/dis*k;
}
void PushDown(int rt,int l,int r)
{
if (lh[rt]!=0||rh[rt]!=0)
{
int m=(l+r)>>1;
int t1=rt<<1,t2=t1|1;
double md=Cat(lh[rt],rh[rt],len[rt],X[m+1]-X[l]);
lh[t1]+=lh[rt]; rh[t1]+=md;
lh[t2]+=md; rh[t2]+=rh[rt];
sum[t1]+=len[t1]*(md+lh[rt])/2;
sum[t2]+=len[t2]*(md+rh[rt])/2;
lh[rt]=rh[rt]=0;
}
}
void update(int rt,int l,int r,int L,int R,int ly,int ry)
{
if (L<=l&&r<=R)
{
double ld=Cat(ly,ry,X[R+1]-X[L],X[l]-X[L]);
double rd=Cat(ly,ry,X[R+1]-X[L],X[r+1]-X[L]);
lh[rt]+=ld; rh[rt]+=rd;
sum[rt]+=(ld+rd)/2*len[rt];
return ;
}
PushDown(rt,l,r);
int m=(l+r)>>1;
if (L<=m) update(rt<<1,l,m,L,R,ly,ry);
if (R>m) update(rt<<1|1,m+1,r,L,R,ly,ry);
PushUp(rt);
}
double query(int rt,int l,int r,int L,int R)
{
if (L<=l&&r<=R) return sum[rt];
PushDown(rt,l,r);
int m=(l+r)>>1;
double ans=0;
if (L<=m) ans+=query(rt<<1,l,m,L,R);
if (R>m) ans+=query(rt<<1|1,m+1,r,L,R);
return ans;
}
int main()
{
int i,j,n,m,T,L,R;
char op[5];
scanf("%d",&T);
while (T--)
{
scanf("%d",&n);
for (top=i=0; i<n; i++)
{
scanf("%s",op);
if (op[0]=='Q')
{
c[i].op=0;
scanf("%d %d",&c[i].x[0],&c[i].y[0]);
if (c[i].x[0]>c[i].y[0]) swap(c[i].x[0],c[i].y[0]);
X[top++]=c[i].x[0];
X[top++]=c[i].y[0];
}
else
{
c[i].op=1;
scanf("%d",&c[i].v);
for (j=0; j<c[i].v; j++)
{
scanf("%d %d",&c[i].x[j],&c[i].y[j]);
X[top++]=c[i].x[j];
}
c[i].x[j]=c[i].x[0];
c[i].y[j]=c[i].y[0];
}
}
sort(X,X+top);
for (m=0,i=1; i<top; i++)
if (X[i]!=X[i-1]) X[++m]=X[i];
build(1,0,m);
for (i=0; i<n; i++)
{
if (c[i].op)
{
for (j=0; j<c[i].v; j++)
{
L=Fin(c[i].x[j],m);
R=Fin(c[i].x[j+1],m);
if (L<R) update(1,0,m,L,R-1,-c[i].y[j],-c[i].y[j+1]);
if (L>R) update(1,0,m,R,L-1,c[i].y[j+1],c[i].y[j]);
}
}
else
{
double ans=0;
L=Fin(c[i].x[0],m);
R=Fin(c[i].y[0],m);
if (L<R) ans=query(1,0,m,L,R-1);
if (fabs(ans)<eps) ans=0;
printf("%.3lf\n",ans);
}
}
}
return 0;
}
本文深入探讨了高效算法及数据结构的应用实例,通过详细解析具体案例,展示如何利用算法优化解决问题,提升软件性能。
2227

被折叠的 条评论
为什么被折叠?



