[計算幾何]圓與三角形是否相交

Aurora141592發表於2021-01-03

https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1298
把三角形的每條邊單獨判斷,先判斷兩個點是否都在裡面,是否一個點在裡面一個點在外面,直接return。
然後判斷點到直線的距離是否小於等於r,是的話用餘弦定理判斷和圓是否有交點,原理畫圖就能明白,如果沒有交點的話在圓外的兩個角必定有一個是鈍角,用餘弦定理判斷是否小於0即可。
順便一提,如果不需要用到double型別就都用long long型別,提高精度,點積叉積兩點間距離的平方都是整數。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
struct vec{
    ll x, y;
}c;
ll r;
ll dot(const vec &a, const vec &b){ return a.x * b.x + a.y * b.y; }
ll cross(const vec &a, const vec &b){ return a.x * b.y - a.y * b.x; }
vec sub(const vec &a, const vec &b){ return vec{b.x - a.x, b.y - a.y}; }
ll dist2(const vec &a, const vec &b){ return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); }
bool judge(const vec &a, const vec &b)
{
    if (dist2(c, a) < r * r && dist2(c, b) < r * r) return 0;
    if (dist2(c, a) <= r * r && dist2(c, b) >= r * r || dist2(c, b) <= r * r && dist2(c, a) >= r * r) return 1;
    if (cross(sub(a, c), sub(a, b)) * cross(sub(a, c), sub(a, b)) > r * r * dist2(a, b)) return 0;
    if (dist2(a, b) + dist2(b, c) < dist2(a, c) || dist2(b, a) + dist2(a, c) < dist2(b, c)) return 0;
    else return 1;
}
inline ll in()
{
    ll res=0,p=1;
    char c=getchar();
    while(c<'0'||c>'9') {if(c=='-') p=-1; c=getchar();}
    while(c>='0'&&c<='9') res=res*10+c-48,c=getchar();
    return p*res;
}
int main()
{
    int t;
    t = in();
    vec p1, p2, p3;
    while (t--){
        c.x = in(), c.y = in(), r = in();
        p1.x = in(), p1.y = in(), p2.x = in(), p2.y = in(), p3.x = in(), p3.y = in();
        if (judge(p1, p2) || judge(p2, p3) || judge(p3, p1)) puts("Yes");
        else puts("No");
    }
    return 0;
}

相關文章