题目大意:在(0,0)到(10000,10000)的正方形区域内有一些有向直线,求它们左侧面积的交。
思路:半平面交模板题。第一次写半平面交,犯了很多错误。
CODE:
#include <cmath> #include <cstdio> #include <cstring> #include <iomanip> #include <iostream> #include <algorithm> #define MAX 40010 #define EPS 1e-10 #define DCMP(a) (fabs(a) < EPS ? true:false) using namespace std; struct Point{ double x,y; Point(double _ = 0.0,double __ = 0.0):x(_),y(__) {} Point operator -(const Point &a)const { return Point(x - a.x,y - a.y); } Point operator +(const Point &a)const { return Point(x + a.x,y + a.y); } Point operator *(const double &a)const { return Point(x * a,y * a); } void Read() { scanf("%lf%lf",&x,&y); } }ploy[MAX],p[MAX]; struct Line{ Point v,p; double alpha; bool operator <(const Line &a)const { return alpha < a.alpha; } Line(Point _,Point __):v(_),p(__) {} Line() {} void Calc() { alpha = atan2(v.y,v.x); } }line[MAX],q[MAX]; int lines,cnt; void Pretreatment(); inline double Cross(Point p1,Point p2); int HalfPlaneIntersection(); inline Point GetIntersection(Line l1,Line l2); inline bool OnLeft(Line l,Point p); int main() { Pretreatment(); cin >> lines; for(int i = 1;i <= lines; ++i) { Line *now = &line[++cnt]; now->p.Read(); Point temp; temp.Read(); now->v = temp - now->p; } for(int i = 1;i <= cnt; ++i) line[i].Calc(); sort(line + 1,line + cnt + 1); int num = HalfPlaneIntersection(); double ans = Cross(ploy[num],ploy[1]); for(int i = 1;i < num; ++i) ans += Cross(ploy[i],ploy[i + 1]); cout << fixed << setprecision(1) << fabs(ans) / 2.0 << endl; return 0; } void Pretreatment() { line[++cnt] = Line(Point(1,0),Point(0,0)); line[++cnt] = Line(Point(0,1),Point(10000,0)); line[++cnt] = Line(Point(-1,0),Point(10000,10000)); line[++cnt] = Line(Point(0,-1),Point(0,10000)); } inline double Cross(Point p1,Point p2) { return p1.x * p2.y - p1.y * p2.x; } inline Point GetIntersection(Line l1,Line l2) { Point u = l1.p - l2.p; double t = Cross(l2.v,u) / Cross(l1.v,l2.v); return l1.p + l1.v * t; } int HalfPlaneIntersection() { int front = 1,tail = 1; q[tail] = line[1]; for(int i = 2;i <= cnt; ++i) { while(front < tail && !OnLeft(line[i],p[tail - 1])) --tail; while(front < tail && !OnLeft(line[i],p[front])) ++front; if(DCMP(Cross(line[i].v,q[tail].v))) q[tail] = OnLeft(q[tail],line[i].p) ? line[i]:q[tail]; else q[++tail] = line[i]; if(front < tail) p[tail - 1] = GetIntersection(q[tail],q[tail - 1]); } while(front < tail & !OnLeft(q[front],p[tail - 1])) --tail; if(front == tail) return 0; p[tail] = GetIntersection(q[tail],q[front]); int re = 0; for(int i = front;i <= tail; ++i) ploy[++re] = p[i]; return re; } inline bool OnLeft(Line l,Point p) { return Cross(l.v,p - l.p) > 0; }