YS - Sort Points by Argument

Author: Jeffrey Zhang

Table of Contents

SolutionImplementation

Solution

The idea for this problem is fairly straightforward. Let us define the "argument" of a point as the angle it forms with the origin. Given nn points {P1,...,Pn}\{P_1,...,P_n\}, we can find the argument of the point Pi=(xi,yi)P_i = (x_i,y_i) by calling tan1yixi\tan^{-1}{\frac{y_i}{x_i}}. To sort the points in the counterclockwise order, we just sort the points based on their argument from smallest to largest.

The problem conviently required us to have the sorted points start from the 3rd quadrant and end at the 2nd quadrant, which matches with the characteristics of the builtin tan1\tan^{-1} function, where the 3rd and 4th quadrant points have negative angle values and 1st and 2nd quadrant points have positive angle values.

Implementation

Time Complexity: O(NlogNM(N))\mathcal{O}(N \log N \cdot M(N)), where M(N)M(N) is the computation complexity for tan1N\tan^{-1}{N}

C++

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct Point {
ll x;
ll y;
};
int main() {

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!