【题目链接】
【算法】
线段树扫描线
推荐一篇比较容易理解的线段树扫描线的文章 : https://blog.csdn.net/u013480600/article/details/22548393
【代码】
注意此题输出格式若使用"%.2lf"会离奇Wrong Answer,要改为"%.2f"
#include <algorithm> #include <bitset> #include <cctype> #include <cerrno> #include <clocale> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <exception> #include <fstream> #include <functional> #include <limits> #include <list> #include <map> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <ostream> #include <queue> #include <set> #include <sstream> #include <stdexcept> #include <streambuf> #include <string> #include <utility> #include <vector> #include <cwchar> #include <cwctype> #include <stack> #include <limits.h> using namespace std; #define MAXN 110 int i,n,l1,l2,l,L,R,TC; double xa,ya,xb,yb,area; double a[MAXN*2],x[MAXN*2],arr[MAXN*2]; struct info { double l,r,h,opt; } y[MAXN*2]; struct SegmentTree { struct Node { int l,r,c; double m; } Tree[MAXN*4]; inline void build(int index,int l,int r) { int mid; Tree[index].l = l; Tree[index].r = r; Tree[index].m = 0.0; Tree[index].c = 0; if (l == r) return; mid = (l + r) >> 1; build(index<<1,l,mid); build(index<<1|1,mid+1,r); } inline void update(int index) { if (Tree[index].c > 0) Tree[index].m = arr[Tree[index].r+1] - arr[Tree[index].l]; else if (Tree[index].l == Tree[index].r) Tree[index].m = 0; else Tree[index].m = Tree[index<<1].m + Tree[index<<1|1].m; } inline void add(int index,int l,int r,int val) { int mid; if (Tree[index].l == l && Tree[index].r == r) { Tree[index].c += val; update(index); return; } mid = (Tree[index].l + Tree[index].r) >> 1; if (mid >= r) add(index<<1,l,r,val); else if (mid + 1 <= l) add(index<<1|1,l,r,val); else { add(index<<1,l,mid,val); add(index<<1|1,mid+1,r,val); } update(index); } inline double query() { return Tree[1].m; } } T; bool cmp(info a,info b) { return a.h > b.h; } int main() { while (scanf("%d",&n) != EOF && n) { l = l1 = l2 = 0; for (i = 1; i <= n; i++) { scanf("%lf%lf%lf%lf",&xa,&ya,&xb,&yb); x[++l1] = xa; x[++l1] = xb; y[++l2] = (info){xa,xb,ya,-1}; y[++l2] = (info){xa,xb,yb,1}; } sort(x+1,x+l1+1); x[0] = -1; for (i = 1; i <= l1; i++) { if (x[i] != x[i-1]) arr[++l] = x[i]; } T.build(1,1,l-1); sort(y+1,y+l2+1,cmp); area = 0.0; for (i = 1; i < l2; i++) { L = lower_bound(arr+1,arr+l+1,y[i].l) - arr; R = lower_bound(arr+1,arr+l+1,y[i].r) - arr - 1; T.add(1,L,R,y[i].opt); area += T.query() * (y[i].h - y[i+1].h); } printf("Test case #%d Total explored area: %.2f ",++TC,area); } return 0; }