Given some points in plane (upto 500 points), no 3 collinear. We have to determine the number of triangles whose vertices are from the given points and that contain exactly N points inside them. How to efficiently solve this problem? The naive O(n^4) algorithm is too slow. Any better approach?
Number of triangles with N points inside
1.2k views Asked by Artur AtThere are 2 answers
Amar Malik
On
Actually I happened to encounter similar problem recently but the only difference was that there were around 300 pts and I solved it using bitset (C++ STL). For every pair of points, say (x[i],y[i]) and (x[j],y[j]), I formed a bitset<302>B[i][j] and B[i][j][k] stores 1 if k-th point is above line segment from point i to point j else I would store 0.
Now in a brute force manner I get three points so as to form a triangle, lets say (x[i],y[i]), (x[j],y[j]) and (x[k],y[k]), then a point,say z-th point ,would be inside triangle if B[i][j][z]==B[i][j][k] && B[j][k][z]==B[j][k][i] && B[k][i][z]==B[k][i][j] because a point inside triangle would show similar sign w.r.t. a side of triangle as the third point of triangle(one which is not on this side). So i get three bitset variables P=B[i][j], Q=B[j][k] and R=B[k][i] and there taking there bitwise AND then applying count() function to give me the active number of bits and hence the number of points within the triangle. But make sure you change variable P such that it gives B[i][j][k]=1 if not then take bitwise not (~) of this variable.
Though the above solution is problem specific, i hope it helps. This is the problem link: http://usaco.org/current/index.php?page=viewproblem&cpid=660
Related Questions in MATH
- How to restrict vpasolve() to only integer solutions (MATLAB)
- Need clarification on VHDL expressions involving std_logic_vector, unsigned and literals, unsure about compiler interpretation
- What is the algorithm behind math.gcd and why it is faster Euclidean algorithm?
- How to throw a charged particle in a electric vector field?
- Issues with a rotation gizmo and sign flips when converting back to euler angles
- Solving the area of a 2 dimensional shape
- WorldToScreen function
- Algorithm to find neighbours of point by distance with no repeats
- Detecting Circles and Ellipses from Point Arrays in Java
- three parameter log normal distribution
- Bound for product of matrices
- Javascript animation taking incorrect amount of time to reach desired location
- Converting Math.js-like Expressions to Runnable Python Code
- Looking for a standard mathematical function that returns 0 if x = 0 and a constant k when x <> 0
- Partitions in co-lexicographic order (PARI/GP algorithm without recursion)
Related Questions in GEOMETRY
- WorldToScreen function
- Intersection of Cartesian Box and Polygon in 3D
- find point in inside polygon ..with mysql
- How do I find the line segments formed by the meeting of two sides of two polygons?
- How to create a pareto distribution prediction function?
- How to estimate the memory size of a binary voxelized geometry?
- Spacing out overlapping rectangles: how to translate pseudocode?
- Sympy manipulation of wedge products
- how to create a sector and check if some point is in it's area?
- Get third control point quadratic Bezier curve for parabola with given fucus and directrix, Lua
- CGSRegionRef: How is an arbitrary region represented as union of rects?
- Distribution of n number of equi-distant point in polygon
- Selecting suitable triangles to intersect with a line
- How to distribute n number of points into a svg polygon javascript
- How to offset a shaply polygon without chnaging corner shape
Related Questions in COMPUTATIONAL-GEOMETRY
- Sweep shape along 3D path in Python
- 'plotAtlas' function in Morpho package
- Encounter problem at different speed/start point algorithm design
- Selecting suitable triangles to intersect with a line
- Merging Geodataframe Polygons to Meet Population Threshold in Python
- Rotating a 3D body in python results in holes in the body
- SageMath: Create a triangle with specific angles in Hyperbolic space, eg., Upper Halfspace Plane
- reducing a massive tetrahedron mesh using gmsh or other way
- Implementing Jarvis Binary Search in Chan's algorithm
- How to find centroid snapped to grid via Shapely?
- Find the largest rectangle that doesn't intersect any given polygon
- Generate P random N-dimensional points from list of ALL possible pairwise distances
- Fast way to find closest line segment for a large set of planar points [Python]
- how to check if all the faces face outward
- Counting the number of polygons containing origin in 2D
Related Questions in COMBINATORICS
- How to calculate efficient binominal coefficient or sum of these coeficients mod value?
- Minimum cases of n choose k with respect of n choose q
- Filter elements in the list A, based on the list B, such that for a in A there exists at least one element b in B, where a = (a&b)
- Is my logic correct? A bit string of n with more 0s than 1s
- Giving each student a set of questions so that any two would have minimal number of common questions
- All combinations 1 to n_1, 2 to n_2, ..., n to n_n in R as vectors in a list?
- Number of the binary strings that have the given number of occurrences
- Seeking Efficient Enumeration Strategies for Graph Partitioning
- How do I select a combination of two variables from a dataframe when each variable value can only be selected once?
- R: Creating all possible between group combinations without within group combinations
- Is it possible in SQL to generate all pairs of participants from a list of events and participants? If so, how?
- How to attach each row of a dataframe against all the other rows in a pairwise manner
- Finding paths covering all edges in complete digraphs
- Optimization Strategy for Data Retrieval from APIs with Row Limits
- Put n persons in x 2-Beds-Room and y 3-Beds-Room based on preferences
Related Questions in TRIANGLE-COUNT
- C For Loop Floyd's Triangle but different?
- How to generate a triangle free graph in Networkx (with randomseed)?
- Python: count specific subshapes in shape with intersecting lines
- Count Triangles in Scala - Spark
- How to find a "triangle of friends" in a graph?
- Number of possible triangles from an integer array in O(NlogN)
- An algorithmic task with triangles
- How I can copy triangle shape numbers in Python
- Unity-3D how can i see polygon count in mobile phone?
- Trying to create a function to see if a triangle is valid, getting an error message on my function
- Finding total number of triangles using networkx
- My Java-Triangle Code doesn't print the full Triangle
- Triangle , C++ construction, problem with calculating angles
- problem with triangle angle in programm language C++
- How do I let my program print a complete right angle triangle for certain values?
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
You could try thinking of the triangle as the intersection of three half-spaces. To find the number of points inside a triangle A, B, C first consider the set of points on one side of the infinite line in direction AB. Let these sets L(AB) and R(AB) for points of the left and right. Similarly you the same with other two edges and build sets L(AC) and R(AC) and sets L(BC) and R(BC).
So the number of points in ABC will be the number of points in the intersection of L(AB), L(AC) and L(BC). (You might want to consider R(AB) instead depending on the orientation of the triangle).
Now if we want to consider the full set of 500 points. First take all pairs of points AB and construct the sets L(AB) and R(AB). This will take O(n^3) operations.
Next we test all triangles and find the intersections of the three sets. If we use some hash table structure for the sets then to find the intersection points is like a hashtable lookups. If L(AB) has l elements, L(AC) has m elements and L(BC) n elements. Say l > m > n. For each point in L(BC) we need to do a lookup in L(AC) and L(BC) so thats a maximum of 2n hashtable lookups.
It might be faster to consider a geometric lookup table. Divide your whole domain into a coarse grid say a 10 by 10 grid. We can then put each point into a set G(i,j). We can then split the sets L(AB) into each grid cell. Say call these sets L(AB,i,j) and R(AB,i,j). In testing for intersections first workout which grid cells lie in the intersection. This dramatically reduces the search space and as each set L(AB,i,j) contain fewer members there will be fewer hashtable lookups.