2021-08-17 一步步学习扫描线

扫描线学习

简介¶
扫描线一般运用在图形上面,它和它的字面意思十分相似,就是一条线在整个图上扫来扫去,它一般被用来解决图形面积,周长等问题。

https://www.luogu.com.cn/problem/P5490

https://oi-wiki.org/geometry/scanning/

简单来讲 这个问题先用最简单的方法解决。这个也是扫描线的解决方法
优化就是把线的更新和查询替换成线段树。

#include<iostream>
#include <map>
#include <vector>
using namespace  std;

//把矩形变成两根线
struct Line{
    Line(int xs, int xt, int val, int high) : xs(xs), xt(xt), val(val), high(high) {}
    int xs , xt;
    int val = -1;
    int high  = -1;
};
const int maxn = 1e5 +6;
int arr[maxn];
vector<Line> lines ;

bool  cmp(Line &x , Line &y){
    if(x.high != y.high) {
        return x.high < y.high;
    }else{
        return x.val > y.val;
    }
}

//更新线
void update(int l , int r ,int val){
    for(int i = l ; i < r; ++i){
        arr[i] += val;
    }
}

//获取长度
int getLen(){
    int count =  0;
    for(int i = 0 ; i < 1000 ; ++i){
        if(arr[i] > 0){
            count += 1;
        }
    }
    return count;
}

void run(int n ){
    int xs,ys,xt,yt;;
    for(int i = 0 ; i < n; ++i){
        //输入矩形
        cin>>xs >> ys >> xt >> yt;
        Line line1(xs  , xt , 1 , ys) ;
        Line line2(xs  , xt , -1 , yt) ;
        lines.push_back(line1);
        lines.push_back(line2);
    }

    sort(lines.begin() , lines.end() , cmp);
    int his_len  = 0 , his_high = 0  , res  = 0;
    for(Line line : lines){
        update(line.xs , line.xt , line.val );
        res += his_len * (line.high - his_high);
        //cout<<his_high <<' '<<his_len <<' '<<res<<endl;
        his_len = getLen();
        his_high = line.high;
    }
    cout<<res<<endl;
}

int main() {
    int n;
    cin>>n;
    run(n);
}

/**
 * input
2
100 100 200 200
150 150 250 255

2
0 0 2 2
1 1 2 2

**/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值