扫描线学习
简介¶
扫描线一般运用在图形上面,它和它的字面意思十分相似,就是一条线在整个图上扫来扫去,它一般被用来解决图形面积,周长等问题。
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
**/