H. City Horizon
Farmer John has taken his cows on a trip to the city! As the sun sets, the cows gaze at the city horizon and observe the beautiful silhouettes formed by the rectangular buildings.
The entire horizon is represented by a number line with N (1 ≤ N ≤ 40,000) buildings. Building i's silhouette has a base that spans locations Ai through Bi along the horizon (1 ≤ Ai < Bi ≤ 1,000,000,000) and has height Hi (1 ≤ Hi ≤ 1,000,000,000). Determine the area, in square units, of the aggregate silhouette formed by all N buildings.
Input
Lines 2.. N+1: Input line i+1 describes building i with three space-separated integers: Ai, Bi, and Hi
Output
Sample Input
4 2 5 1 9 10 4 6 8 2 4 6 3
Sample Output
16
一个JB题,坑了我2个小时。。。
就因为把sort(w+1,w+1+n)写成了sort(w,w+n,cmp)
离散化+线段树
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
const int N=80001;
struct acm
{
int lt;
int rt;
long long h;
}node[N*4];
struct wp
{
int s;
int e;
long long height;
}w[N];
int p[N];
long long ans;
void build(int l,int r,int id)
{
node[id].rt=r;
node[id].lt=l;
node[id].h=0;
if(r-l==1)
return;
int mid=(l+r)>>1;
build(l,mid,id<<1);
build(mid,r,id<<1|1);
}
void push_down(int id){
if(node[id].h){
node[id<<1].h=node[id<<1|1].h=node[id].h;
node[id].h=0;
}
}
void update(int l,int r,long long hh,int id)
{
if(node[id].rt==r&&node[id].lt==l)
{
node[id].h=hh;
return;
}
if(node[id].lt==node[id].rt-1)
return;
push_down(id);
int mid=(node[id].lt+node[id].rt)>>1;
if(r<=mid)
update(l,r,hh,id<<1);
else if(l>=mid)
update(l,r,hh,id<<1|1);
else
{
update(l,mid,hh,id<<1);
update(mid,r,hh,id<<1|1);
}
}
void query(int id)
{
if(node[id].h>0)
{
//cout<<p[node[id].rt-1]<<" "<<p[node[id].lt-1]<<" "<<node[id].h<<endl;
ans+=(p[node[id].rt-1]-p[node[id].lt-1])*node[id].h;
return;
}
if(node[id].lt+1==node[id].rt)
return;
query(id<<1);
query(id<<1|1);
}
int cmp( wp a, wp b)
{
return a.height<b.height;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
build(1,N,1);
int cnt=0;
for(int i=1;i<=n;i++)
{
scanf("%d%d%lld",&w[i].s,&w[i].e,&w[i].height);
p[cnt++]=w[i].s;
p[cnt++]=w[i].e;
}
sort(p,p+cnt);
sort(w+1,w+n+1,cmp);
cnt=unique(p,p+cnt)-p;
for(int i=1;i<=n;i++)
{
int ll=lower_bound(p,p+cnt,w[i].s)-p+1;
int rr=lower_bound(p,p+cnt,w[i].e)-p+1;
update(ll,rr,w[i].height,1);
}
ans=0;
query(1);
printf("%lld\n",ans);
}
return 0;
}