半平面交自用模板

#include <cstdio>
#include <iostream>
#include <vector>
#include <complex>
#include <cmath>
using namespace std;

typedef complex<double> Point;
typedef vector<Point> Polygon;
typedef pair<Point,Point> Line;
#define x real()
#define y imag()

inline double cross(Point& a,Point& b) {
    return (a.x*b.y)-(a.y*b.x);
}
inline double cross(Point& o,Point& a,Point& b) {
    return (a.x-o.x)*(b.y-o.y)-(a.y-o.y)*(b.x-o.x);
}

double area(Polygon& p) {
    double a=0;
    int n=p.size();
    for(int i=0;i<n;++i)
        a+=cross(p[i],p[(i+1)%n]);
    return fabs(a)/2;
}

Point intersection(Point& a1,Point& a2,Point& b1,Point& b2) {
    Point a=a2-a1, b=b2-b1, s=b1-a1;
    return a1+a*cross(b,s)/cross(b,a);
}

Polygon halfplane_intersection(Polygon& p,Line& line) {
    Polygon q;
    Point p1=line.first, p2=line.second;

    int n=p.size();
    for(int i=0;i<n;++i) {
        double c=cross(p1,p2,p[i]);
        double d=cross(p1,p2,p[(i+1)%n]);
        if(c>=0) q.push_back(p[i]);
        if(c*d<0) q.push_back(intersection(p1,p2,p[i],p[(i+1)%n]));
    }
    return q;
}

Line lines[10];

void demo() {
    Polygon p;
    p.push_back(Point(-1e9,-1e9));
    p.push_back(Point(-1e9,+1e9));
    p.push_back(Point(+1e9,-1e9));
    p.push_back(Point(+1e9,+1e9));

    for(int i=0;i<10;++i) {
        p=halfplane_intersection(p,lines[i]);
        if(area(p)==0) break;
    }
    return;
}

Polygon cur;
Point p[1510];

void work() {
    cur.clear();
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++) {
        double a,b;
        scanf("%lf%lf",&a,&b);
        p[i]=Point(a,b);
        cur.push_back(p[i]);
    }
    for(int i=0;i<n;i++) {
        Point a=p[i], b=p[(i+1)%n];
        Line now=make_pair(b,a);
        cur=halfplane_intersection(cur,now);
    }
    printf("%.2lf\n",area(cur));
    return;
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
#endif // ONLINE_JUDGE
    int cas;
    scanf("%d",&cas);
    while(cas--) work();

    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值