链接:https://ac.nowcoder.com/acm/contest/889/J
题目描述:
Initially, the entire coordinate plane is colored white. N rectangles were painted black. The i-th rectangle has bottom-left corner (i-1, Li) and top-right corner (i, Ri) for 1 <= i <= n. You want to paint some of the black area white so that the remaining black part has a horizontal axis of symmetry. Find the maximum possible area of the remaining black part.
输入数据:
The first line of input contains a single integer N (1 <= N <= 300000), denoting the number of rectangles.
The next N lines of input contain two space-separated integers each, denoting Li, Ri (1 <= Li < Ri <= 109).
输出数据:
Output a single integer, the answer to the problem.
输入:
3
1 5
4 7
2 3
输出:
4
解:
题目就是把一些黑色矩形涂白,求出剩下有水平对称轴的黑色矩形的最大面积。
首先就是思考对称轴能在哪里,(下面针对一个矩形的情况讨论,多个矩形类似) 有三种情况,第一种在这个矩形的下方,那么这个矩形就全涂白了,这个面积就不需要,这个时候记为yl;第二种情况就是在矩形内部,那么随着对称轴从下到上动,要涂白的部分是先减少后增加的,在矩形中间的时候最小为0,这个点记为 ymid;第三种情况, 在矩形上方,那么这个矩形还是不需要,这个时候记为yr。对于此题来说,对称轴必定在某个矩形的ymid位置出现,那么我们就预处理出来这三个位置,排序,之后边计算面积边找就可以了。
AC代码
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 9e5+10;
typedef long long ll;
struct qwq
{
ll a, b;
}p[N];
bool cmp(qwq a, qwq b)
{
return a.a < b.a;
}
int main()
{
int n, cnt = 0;
scanf("%d", &n);
for(int i = 0; i < n; ++i)
{
ll l, r;
scanf("%lld%lld", &l, &r);
l *= 2, r *= 2;
p[++cnt].a = l, p[cnt].b = 1;
p[++cnt].a = (l+r) >> 1, p[cnt].b = -2;//过了对称轴之后面积会变小
p[++cnt].a = r, p[cnt].b = 1;
}
sort(p+1, p+cnt+1, cmp);
ll ans = 0, ma = 0, tmp = 0, pre = 0;
for(int i = 1; i < cnt; ++i)
{
pre += p[i].b;
tmp = p[i+1].a - p[i].a;
ma += pre * tmp;
ans = max(ans, ma);
}
printf("%lld\n", ans);
}