题解:P14752 Hit or not?

· · 题解

题解:P14752 Hit or not?

题目传送门

题目分析

给定一个凸多边形(顶点按逆时针顺序给出),以及一个位于 x 轴上点 O(x_0, 0)。从 O 点向 y 轴正方向(正前方)发射子弹,求子弹首先击中的是哪条边。

思路

由于子弹沿直线 x = x_0 向上飞行,我们可以将问题简化为:

  1. 找到所有与竖直线 x = x_0 相交的边。
  2. 计算每个交点的 y 坐标。
  3. 选择最小的正 y 坐标对应的边(因为子弹从 y=0 出发,首先碰到的是最低的交点)。

对于每条边 P_iP_{i+1}(i 从 0 到 n-1,P_n = P_0):

代码

#include <bits/stdc++.h>
#define Jason227 return
#define Code 0
using namespace std;

int n, ans1 = -1, ans2 = -1, j, x1, y11, x2, y2, y;
long long x0;
double mi = 1e18;

int main(){
    cin >> n;
    vector<pair<long long, long long>> p(n);
    for(int i = 0; i < n; i++){
        cin >> p[i].first >> p[i].second;
    }
    cin >> x0;
    for(int i = 0; i < n; i++){
        j = (i + 1) % n;
        x1 = p[i].first, y11 = p[i].second;
        x2 = p[j].first, y2 = p[j].second;
        if((x1 <= x0 && x2 >= x0) || (x1 >= x0 && x2 <= x0)){
            y = y11 + double(y2 - y11) * (x0 - x1) / (x2 - x1);
            if(y > 0 && y < mi){
                mi = y;
                ans1 = i + 1;
                ans2 = j + 1;
            }
        }
    }
    cout << ans1 << " " << ans2 << '\n';
    Jason227 Code;
}

复杂度分析

AC 记录