判断两直线是否相交以及求交点模板 以ICPC2021昆明I题为例

题目链接直接上牛客竞赛搜索2021昆明即可找到

#include <bits/stdc++.h>
const int N = 1e3 + 5;
const double eps = 1e-10;
using namespace std;

struct point
{
    double x, y;
} p[N];
point s, t;

point operator+(const point &a, const point &b) { return {a.x + b.x, a.y + b.y}; }
point operator-(const point &a, const point &b) { return {a.x - b.x, a.y - b.y}; }
point operator/(const point &a, const double b) { return {a.x / b, a.y / b}; }       //向量数除
point operator*(const point &a, const double b) { return {a.x * b, a.y * b}; }       //向量数乘
double operator*(const point &a, const point &b) { return (a.x * b.y - b.x * a.y); } //向量叉积

double dist(point a) { return (s.x - a.x) * (s.x - a.x) + (s.y - a.y) * (s.y - a.y); } //求两点距离的平方

bool parallel(point a, point b, point c, point d) { return abs((a - b) * (c - d)) < eps; } //判断是否平行

point cross(point a, point b, point c, point d) //求两条直线交点,先手动判断是否平行再调用此函数
{
    double s1 = (a - c) * (a - d);
    double s2 = (b - d) * (b - c);
    return a + (((b - a) * s1) / (s1 + s2));
}

bool cmp(point a, point b) { return dist(a) < dist(b); }

int main()
{
    vector<point> v;
    int n, m;
    scanf("%d%d", &n, &m);
    scanf("%lf%lf%lf%lf", &s.x, &s.y, &t.x, &t.y);
    for (int i = 1; i <= n; i++)
        scanf("%lf%lf", &p[i].x, &p[i].y);
    while (m--)
    {
        v.clear();
        int h, k;
        scanf("%d%d", &h, &k);
        if (k >= n)
        {
            printf("-1\n");
            continue;
        }
        for (int i = 1; i <= n; i++) //将查询的点与其他点构成直线然后求交点
        {
            if (i == h || parallel(s, t, p[i], p[h])) continue; //与路线平行
            point cp = cross(s, t, p[h], p[i]);
            if ((cp.x < s.x && cp.x > t.x) || (cp.x > s.x && cp.x < t.x)) //交点位于起点和终点之间
                v.push_back(cp);
        }
        if (v.size() < k) //交点少于k个
            printf("-1\n");
        else
        {
            sort(v.begin(), v.end(), cmp);                     //按照距离起点的位置进行排序
            printf("%.10lf %.10lf\n", v[k - 1].x, v[k - 1].y); //输出第k个交点位置
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值