[USACO2007OPENS] City Horizon S

题目描述

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.

输入格式

第一行一个整数N,然后有N行,每行三个正整数ai、bi、Hi。

输出格式

一个数,数列中所有元素的和。

样例 #1

样例输入 #1

4
2 5 1
9 10 4
6 8 2
4 6 3

样例输出 #1

16

提示

\(N<=40000 , a、b、k<=10^9\)

所有的左端点和右端点把线段切成了很多段,每一段的值都是一样的。
把所有左右端点离散一下,然后从左到右枚举每一段。那么就要研究这个时候每一段的值是什么。
可以开一个set维护现在有的高度,这一段的高度就是现有的高度的最大值。我们遇到一个左端点就把对应高度放入set,遇到一个右端点就把对应高度从set中删去。然后一段的面积和就是长度*最大值。加起来即可

#include<iostream>
#include<set>
#include<algorithm>
using namespace std;
int a,b,h;
int n;
long long ans;
multiset<int>s;
struct evt{
	int x,h;
	bool operator<(const evt e)const{
		return x<e.x;
	}
}e[80005];
int main()
{
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>a>>b>>h;
		e[2*i-1]=(evt){a,h};
		e[2*i]=(evt){b,-h};
	}
	sort(e+1,e+2*n+1);
	s.insert(0);
	for(int i=1;i<=2*n;i++)
	{
		if (i!=1&&!s.empty()) ans += (long long)(e[i].x-e[i - 1].x)*(*s.rbegin());
		if(e[i].h>0)
			s.insert(e[i].h);
		else
			s.erase(s.find(-e[i].h));
	}
	cout<<ans<<endl;
}
posted @ 2022-06-02 17:24  灰鲭鲨  阅读(35)  评论(0编辑  收藏  举报