洛谷_1382 楼房(线段树)

楼房

题目链接:https://www.luogu.com.cn/problem/P1382

题解:

假设初始在点(-INF,0),那么之后的每次都可以看做一次水平移动加上一次垂直移动。类似于扫描线,将线段分为两部分,左端点为入,右端点为出。
线段树维护最大值。将x坐标相同的作为一组。若当前点为左端点,则在线段树中加上h的信息,为右端点,则在线段树中删去h的信息。 最后求出当前h的最大值,即为yy, 此时的x轴坐标为xx。设上次移动后,点为(x,y)。若 y y ! = y yy!=y yy!=y,则在答案中加入(xx, y), (xx, yy)。 再更新(x,y)即可。

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<map>
#include<vector>
#include<queue>
#include<iterator>
#include<unordered_map>
#define dbg(x) cout<<#x<<" = "<<x<<endl;
#define INF 0x3f3f3f3f
#define LLINF 0x3f3f3f3f3f3f3f3f
#define eps 1e-6

using namespace std;
typedef long long LL;
typedef pair<int, int> P;
const int maxn = 100100;
const int mod = 100003;
struct node{
    int h, pos, op;
    bool operator<(node b)const{
        return pos<b.pos;
    }
}p[maxn*3];
int a[maxn], b[maxn], sum[maxn*4], h[maxn], l[maxn], r[maxn];
int top, ax[maxn*8], ay[maxn*8];
int lisan(int n, int a[]);
int query(int l, int r, int k);
void Update(int l, int r, int x, int y, int k);

int main()
{
    int n, m, i, j, k, x, y, yy, cnt = 0;
    scanf("%d", &n);
    for(i=1;i<=n;i++){
        scanf("%d %d %d", &h[i], &l[i], &r[i]);
        a[i] = h[i];
    }
    m = lisan(n, a);
    for(i=1;i<=n;i++){
        p[++cnt].h = lower_bound(a+1, a+1+m, h[i])-a;
        p[cnt].op = 1, p[cnt].pos = l[i];
        p[++cnt].h = lower_bound(a+1, a+1+m, h[i])-a;
        p[cnt].op = -1, p[cnt].pos = r[i];
    }
    sort(p+1, p+1+cnt);
    i = 1, x = -INF, y = 0;
    while(i<=cnt){
        for(j=i;j<=cnt;j++){
            if(p[j].pos != p[i].pos)break;
            Update(1, m, p[j].h, p[j].op, 1);
        }
        if(sum[1] == 0)yy = 0;
        else yy = a[query(1, m, 1)];
        if(yy != y){
            ax[++top] = p[i].pos;ay[top] = y;
            ax[++top] = p[i].pos;ay[top] = yy;
        }
        x = p[i].pos, y =yy;
        i = j;
    }
    printf("%d\n", top);
    for(i=1;i<=top;i++)
        printf("%d %d\n", ax[i], ay[i]);
    return 0;
}

int lisan(int n, int a[])
{
    sort(a+1, a+1+n);
    int top = 1, i;
    for(i=2;i<=n;i++)
        if(a[top] != a[i])a[++top] = a[i];
    return top;
}

void Update(int l, int r, int x, int y, int k)
{
    sum[k]+=y;
    if(l ==r)return;
    int mid = (l+r)/2;
    if(x<=mid)Update(l, mid, x, y, 2*k);
    else Update(mid+1, r, x, y, 2*k+1);
}

int query(int l, int r, int k)
{
    if(l == r)return l;
    int mid = (l+r)/2;
    if(sum[2*k+1])return query(mid+1, r, 2*k+1);
    else return query(l, mid, 2*k);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值