[BZOJ1645][Usaco2007 Open]City Horizon 城市地平线(扫描线+线段树)

题目描述

传送门

题解

简单的扫描线问题,因为楼的底都是一样的,所以离散化没有那么麻烦。

代码

#include
#include
#include
#include
using namespace std;
#define LL long long

const int max_n=4e4+5;
const int max_tree=max_n*4;

int n,x,y,z,tot,last;
int a[max_n],b[max_n],c[max_n],p[max_n],h[max_n],re[max_n];
int sum[max_tree],delta[max_tree];
struct hp{int loc,h,f;}edge[max_n*2];
LL ans;

inline int cmp(int x,int y)
{
    return c[x]int cmp1(hp a,hp b)
{
    return a.locint now)
{
    sum[now]=sum[now<<1]+sum[now<<1|1];
}
inline void pushdown(int now,int l,int r,int mid)
{
    if (delta[now])
    {
        sum[now<<1]+=delta[now]*(mid-l+1);
        sum[now<<1|1]+=delta[now]*(r-mid);
        delta[now<<1]+=delta[now];
        delta[now<<1|1]+=delta[now];
        delta[now]=0;
    }
}
inline void interval_change(int now,int l,int r,int lrange,int rrange,int v)
{
    int mid=(l+r)>>1;
    if (lrange<=l&&r<=rrange)
    {
        sum[now]+=v*(r-l+1);
        delta[now]+=v;
        return;
    }
    pushdown(now,l,r,mid);
    if (lrange<=mid) interval_change(now<<1,l,mid,lrange,rrange,v);
    if (mid+1<=rrange) interval_change(now<<1|1,mid+1,r,lrange,rrange,v);
    update(now);
}
inline int query(int now,int l,int r)
{
    int mid=(l+r)>>1;
    if (l==r)
    {
        if (sum[now]) return l;
        else return l-1;
    }
    pushdown(now,l,r,mid);
    if (!sum[now<<1|1]) return query(now<<1,l,mid);
    else return query(now<<1|1,mid+1,r);
}
int main()
{
    scanf("%d",&n);
    for (int i=1;i<=n;++i) scanf("%d%d%d",&a[i],&b[i],&c[i]),p[i]=i;
    sort(p+1,p+n+1,cmp);
    for (int i=1;i<=n;++i) h[p[i]]=i,re[i]=c[p[i]];
    for (int i=1;i<=n;++i)
    {
        x=a[i]; y=b[i]; z=h[i];
        edge[++tot].loc=x; edge[tot].h=z; edge[tot].f=1;
        edge[++tot].loc=y; edge[tot].h=z; edge[tot].f=2;
    }
    sort(edge+1,edge+tot+1,cmp1);
    for (int i=1;i<=tot;++i)
    {
        ans+=(LL)re[last]*(LL)(edge[i].loc-edge[i-1].loc);
        if (edge[i].f==1) interval_change(1,1,n,1,edge[i].h,1);
        else interval_change(1,1,n,1,edge[i].h,-1);
        last=query(1,1,n);
    }
    printf("%lld\n",ans);
}

你可能感兴趣的:(题解,线段树,扫描线)