题解:T739180 4B - 研学的游戏 2

· · 个人记录

思路

首先我们可以容易地判定这个点是否在三角形边界上,要求其在某一条边所在直线上且横坐标在两端点横坐标之间即可。

接下来考虑如何处理点在三角形内情况。我们对于每一条边,计算该点和三角形除这条边两个端点以外的端点是否在同侧。若三次都在同侧,则该点在三角形内,反之在三角形外。证明见下图。

实现时使用直线的标准式 Ax+By+C=0 带入两点检查左侧符号是否相同,相同即在同侧,反之不在。

实现细节

全部使用整数避免精度误差。如果你用浮点数会又 TLE 又 WA。

代码

:::warning[真的要查看代码吗?]

#include <bits/stdc++.h>
using namespace std;
// #define ll __int128
// #define int long long
#define ll long long
int n;
vector<pair<int,int>> pts;
static ll calc(ll x,ll y,ll x1,ll y1,ll x2,ll y2)
{
    return (x-x1)*(y2-y1)-(y-y1)*(x2-x1);
}
signed main()
{
    ios::sync_with_stdio(0),cin.tie(0);
    cin>>n;
    for(int i=1;i<=3;i++)
    {
        int x,y;
        cin>>x>>y;
        pts.push_back(make_pair(x,y));
    }
    while(n--)
    {
        int x,y;
        cin>>x>>y;
        for(int i=0;i<3;i++)
            for(int j=i+1;j<3;j++)
            {
                int x1=pts[i].first,y1=pts[i].second;
                int x2=pts[j].first,y2=pts[j].second;
                int ot=0;
                for(int k=0;k<3;k++)
                    if(k!=i&&k!=j)
                        ot=k;
                int x3=pts[ot].first,y3=pts[ot].second;
                ll tmp1=calc(x,y,x1,y1,x2,y2);
                ll tmp2=calc(x3,y3,x1,y1,x2,y2);
                assert(tmp2!=0);
                if((tmp1<0&&tmp2>0)||(tmp1>0&&tmp2<0))
                {
                    cout<<"MISS\n";
                    goto end;
                }
                else if(tmp1==0)
                {
//                  cout<<"BORDER\n";
//                  goto end;
                    if(min(x1,x2)<=x&&x<=max(x1,x2)&&min(y1,y2)<=y&&y<=max(y1,y2))
                        cout<<"BORDER\n";
                    else
                        cout<<"MISS\n";
                    goto end;
                }
            }
        cout<<"HIT\n";
        end:;
    }
}

:::