/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 540.0 KiB
#2 Accepted 1ms 540.0 KiB
#3 Accepted 1ms 540.0 KiB
#4 Accepted 2ms 368.0 KiB
#5 Accepted 1ms 540.0 KiB
#6 Accepted 1ms 556.0 KiB
#7 Accepted 2ms 376.0 KiB
#8 Accepted 1ms 540.0 KiB
#9 Accepted 1ms 540.0 KiB
#10 Accepted 1ms 336.0 KiB
#11 Accepted 1ms 540.0 KiB
#12 Accepted 1ms 516.0 KiB
#13 Accepted 1ms 540.0 KiB
#14 Accepted 2ms 332.0 KiB
#15 Accepted 1ms 512.0 KiB
#16 Accepted 2ms 552.0 KiB
#17 Accepted 1ms 544.0 KiB
#18 Accepted 2ms 364.0 KiB
#19 Accepted 2ms 340.0 KiB
#20 Accepted 2ms 564.0 KiB
#21 Accepted 1ms 540.0 KiB
#22 Accepted 2ms 560.0 KiB
#23 Accepted 2ms 584.0 KiB
#24 Accepted 2ms 584.0 KiB
#25 Accepted 1ms 540.0 KiB
#26 Accepted 2ms 540.0 KiB
#27 Accepted 1ms 332.0 KiB
#28 Accepted 1ms 540.0 KiB
#29 Accepted 2ms 328.0 KiB

Code

#include <iostream>
#include <vector>
using namespace std;

struct Point {
    long long x, y;
};

// Function to check if a point is on the edge of a polygon segment
bool onEdge(Point p, Point a, Point b) {
    long long crossProduct = (b.y - a.y) * (p.x - a.x) - (b.x - a.x) * (p.y - a.y);
    if (crossProduct != 0)
        return false;
    
    long long dotProduct = (p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y);
    if (dotProduct < 0)
        return false;
    
    long long squaredLengthBA = (b.x - a.x) * (b.x - a.x) + (b.y - a.y) * (b.y - a.y);
    return dotProduct <= squaredLengthBA;
}

// Function to determine if a point is inside the polygon using the Ray-Casting algorithm
bool isInsidePolygon(vector<Point>& polygon, Point p) {
    int n = polygon.size();
    int intersections = 0;

    for (int i = 0; i < n; i++) {
        Point a = polygon[i];
        Point b = polygon[(i + 1) % n];

        // Check if the point is on the edge of the polygon
        if (onEdge(p, a, b))
            return false; // Point is not strictly inside if it's on the edge

        // Check if a ray starting from the point intersects with the edge
        if ((p.y > a.y) != (p.y > b.y)) {
            double xIntersection = a.x + (double)(b.x - a.x) * (p.y - a.y) / (b.y - a.y);
            if (p.x < xIntersection)
                intersections++;
        }
    }

    // The point is strictly inside if there are an odd number of intersections
    return intersections % 2 == 1;
}

int main() {
    int n;
    cin >> n;

    vector<Point> polygon(n);
    for (int i = 0; i < n; i++) {
        cin >> polygon[i].x >> polygon[i].y;
    }

    Point p;
    cin >> p.x >> p.y;

    if (isInsidePolygon(polygon, p)) {
        cout << "YES" << endl;
    } else {
        cout << "NO" << endl;
    }

    return 0;
}

Information

Submit By
Type
Submission
Problem
P1145 Nobita's Love for Shizuka
Language
C++17 (G++ 13.2.0)
Submit At
2024-12-10 10:50:03
Judged At
2024-12-10 10:50:03
Judged By
Score
100
Total Time
2ms
Peak Memory
584.0 KiB