Educational Codeforces Round 1 F Cut Length(计算几何)

这篇博客介绍了如何解决计算几何中的一道问题:给定一个包含多个点的简单多边形和多条直线,求它们的公共部分长度。文章分析了使用常规方法会超时的情况,并提出了优化策略,包括采用锯齿形思路和处理多点共线的情况。通过标记交点并计算方向向量的系数来减少计算量,确保答案的准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:

N103,,线
M100线,线

分析:

0.5s,,线,O(mn2)T,线
齿


这里写图片描述
AB线,CN
2CDDEABQK,QK,KL
,Q+2,K2,0,QK2,KL0,QK
G2,GR
线,,1,+线
线,线,2,线
线,,,,

代码:

//
//  Created by TaoSama on 2016-01-19
//  Copyright (c) 2015 TaoSama. All rights reserved.
//
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <set>
#include <vector>

using namespace std;
#define pr(x) cout << #x << " = " << x << "  "
#define prln(x) cout << #x << " = " << x << endl
const int N = 1e5 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7;

#define double long double
const double EPS = 1e-8;

int sgn(double x) {
    return x < -EPS ? -1 : x > EPS;
}

struct Point {
    double x, y;
    Point() {}
    Point(double x, double y): x(x), y(y) {}
    void read() {cin >> x >> y;}
    Point operator-(const Point& p) {
        return Point(x - p.x, y - p.y);
    }
    double operator*(const Point& p) {
        return x * p.x + y * p.y;
    }
    double operator^(const Point& p) {
        return x * p.y - y * p.x;
    }
    double length() {return hypotl(x, y);}
} poly[N];

using Vec = Point;

double getIntersection(Point p, Vec v, Point q, Vec w) {
    return (w ^ (p - q)) / (v ^ w);
}

int n, q;

double gao(Point p, Vec v) {
    double ret = 0;
    vector<pair<double, int> > pos;
    for(int i = 1; i <= n; ++i) {
        int s1 = sgn(v ^ (poly[i] - p));
        int s2 = sgn(v ^ (poly[i + 1] - p));
        if(s1 == s2) continue; //collinear or no intersection
        double o = getIntersection(p, v, poly[i], poly[i + 1] - poly[i]);
        if(s1 > s2) pos.push_back({o, s1 && s2 ? 2 : 1});
        else pos.push_back({o, s1 && s2 ? -2 : -1});
    }
    sort(pos.begin(), pos.end());
    int flag = 0;
    for(int i = 0; i + 1 < pos.size(); ++i) {
        flag += pos[i].second;
        if(flag) ret += pos[i + 1].first - pos[i].first;
    }
    return ret * v.length();
}

int main() {
#ifdef LOCAL
    freopen("C:\\Users\\TaoSama\\Desktop\\in.txt", "r", stdin);
//  freopen("C:\\Users\\TaoSama\\Desktop\\out.txt","w",stdout);
#endif
    ios_base::sync_with_stdio(0);

    cin >> n >> q;
    for(int i = 1; i <= n; ++i) poly[i].read();
    poly[n + 1] = poly[1];
    while(q--) {
        Point A, B;
        A.read(); B.read();
        cout << fixed << setprecision(20) << gao(A, B - A) << '\n';
    }
    return 0;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值