Suppose some figure on the squared paper. Sides of the figure go straight on the lines of squared paper. Figure may have any (not even convex) shape. How to find the maximum number of dominoes (1x2 rectangular) that can be placed in that figure. It is not allowed to put domino over another one. It is allowed to put domino only in such way, when its sides fall exactly on the lines of squared paper.
Looks like the maximum cardinality matching problem in a bipartite graph. The squares are the vertices and the dominoes are the edges that belong to the matching.
To see that the graph is bipartite, imagine the squares are checkerboard-painted. Black ones only neighbour white ones and vice versa.
You can classify squares by the number of neighbor free squares as type 0, 1, 2, 3 or 4.
I believe that should work:
find a type 1 square, place there a domino in the only possible way and repeat
else, find a free corner formed by two contiguous type 2 and type 3 squares, place there a domino and go to 1
else, place a domino in any type 2 square and go to 1
you are done
Related
I want to find an algorithm to tackle this problem but I have no idea what this problem is even called so I can't google it.
Problem:
There is a triangle, and inside the triangle there are n dots. For example, as below.
Now assume 3 sides of triangle are rubber bands and dots are nails on the wall. We tuck each rubber bands into some dot(s). But each rubber bands must be convex towards the center of triangle.
Also, there should be no intersection of any 2 rubber bands apart from the 3 vertices of original triangle.
Also, there should not be any remaining dot inside the polygon formed by 3 rubber bands.
How many valid arrangement of rubberbands, such that all given conditions are satisfied, are there?
Here, in this picture, the leftmost picture is the original state, 2nd picture is a valid composition, 3rd is invalid since blue and red rubber bands intersect, 4th is invalid since there is a nail remaining inside red-blue-green polygon
My approach: After some thoughts: I guessed that if we pick an arbitrary location inside the triangle which is not one of the given dots(nails), and then we make a Y shape starting from that location towards 3 vertices of outer triangle, that is guaranteed to make a unique valid arrangement of rubber bands, if we imagine that each pair of 2 neighboring edges of Y shape is a rubberband and then we release those bands. They will sort themselves out to form a valid arrangement with elasticity.
So from each 3 vertices of triangle, I draw a line towards all n dot(nails). And then for each polygon partitions that are created by those lines and/or 3 sides of triangle(approx n^3 polygon partitions in total), I can make exactly 1 valid composition by picking any point in the polygon and making Y shape.
For example, if I pull rubber bands to form a y-shape as in the left picture, I can then make a valid composition by releasing those rubber bands, as in the right picture.
However, the problem is that 2 or more polygons may yield same valid composition, so we will count more than the correct answer.
For example, if there are only 2 dots(nails), we could make a bunch of polygon partitions by connecting lines(colored brown) starting from each 3 vertices of triangle to 2 dots(nails). so there are 17 partitions. each 17 partitions would yield a valid composition but the answer would be 6. (3 cases where 2 dots go under same rubber band, 3 cases where 1 dot goes under a band and the other dot goes under the other band.)
So I drew several small examples and tried to figure out a pattern to make an algorithm to de-duplicate it and I kind of see a pattern but can't really formulate it into a pseudo code. Any help is appreciated.
Given a set of n points (a_1, b_1), (a_2, b_2), ..., (a_n, b_n). Need to find the minimum x such that three axis parallel squares each of length x together covers all of the points.
I can find the rectangle with smallest area enclosing all the points. Can this rectangle be used somehow? Or any hint on how to approach this problem?
I think, it is enough to consider two cases:
When each square touches some edge of smallest-area rectangle.
When two squares are located at opposite corners of smallest-area rectangle while third one lies inside (does not touch any edge of smallest-area rectangle).
In first case we could fix corner of one square at one of 4 rectangle's corners, then fix corners of other two squares somewhere at two opposite (to chosen corner) edges of the rectangle (n possible positions for each one), then for each point determine optimal square where it belongs and minimum x.
In second case try two opposite pairs of rectangle corners for "outer" squares, then fix one of corners of the "inner" square at all n*n positions determined by all x and y point coordinates, then for each point determine optimal square where it belongs and minimum x.
Time complexity would be O(n3).
The answer of #EvgenyKluev seems to go in the right direction, but there's a couple of subtleties that I'd like to address.
Since I didn't see a restriction for x being integer, you might want to go with binary search on x to guide your algorithm, and find suitable terminating conditions when the range still available for x is small enough (you would do binary search for integer x as well, but there you don't need a terminating condition).
The placement of a square in one corner of the rectangle (something that you will have to do, somewhat straightforward to prove) limits your search space for the placement of the other two squares: let A be the set of points covered by the corner-aligned first square, and let S be the set of all points. Take S-A and find the enclosing rectangle of that set of points. Placing the remaining two squares at opposite corners of the enclosing rectangle of S-A will always be a solution (only one pair of opposite corners might fit), if one exists.
Thus, one algorithm could - very high level - go like this
binary search for x on [0,N]:
find R(S), the enclosing rectangle of S
for each corner C of R(S):
align one square at C, let the points covered by that square be A
find R(S-A)
do two squares aligned at opposite corners of R(S-A) cover S-A?
As for the binary search, I can't really say how fast that will converge to a range that allows only one alignment of squares, at which point you can directly calculate the value x - I expect that with arbitrary precision, you can make that arbitrarily bad. Each iteration takes O(n log n) for sorting the points in both cardinal directions.
I have a general question on an algorithm that I would like to use to construct an irregular polygon.
I have the following scenario:
I have a start and end position for a ship, thus I know the distance between the two position (say 40km). Using this info, I would like to calculate the remaining vertices of a polygon that includes this as one side, while the other sides should be equal in length and sum up to say 200km (as a matter of fact, any user supplied length). I therefore know the perimeter of the resulting polygon and the 2 vertices that make up one of the sides.
In short, how do I get the other 4 vertices so that each side besides the initially calculated is the same size (and the perimeter of the hexagon adds up to 200 + initial side)?
Thanks in advance!
I'm working with a really slow renderer, and I need to approximate polygons so that they look almost the same when confined to a screen area containing very few pixels. That is, I'd need an algorithm to go through a polygon and subtract/move a bunch of vertices until the end polygon has a good combination of shape preservation and economy of vertice usage.
I don't know if there's a formal name for these kind of problems, but if anyone knows what it is it would help me get started with my research.
My untested plan is to remove the vertices that change the polygon area the least, and protect the vertices that touch the bounding box from removal, until the difference in area from the original polygon to the proposed approximate one exceeds a tolerance I specify.
This would all be done only once, not in real time.
Any other ideas?
Thanks!
You're thinking about the problem in a slightly off way. If your goal is to reduce the number of vertices with a minimum of distortion, you should be defining your distortion in terms of those same vertices, which define the shape. There's a very simple solution here, which I believe would solve your problem:
Calculate distance between adjacent vertices
Choose a tolerance between vertices, below which the vertices are resolved into a single vertex
Replace all pairs of vertices with distances lower than your cutoff with a single vertex halfway between the two.
Repeat until no vertices are removed.
Since your area is ultimately decided by the vertex placement, this method preserves shape and minimizes shape distortion. The one drawback is that distance between vertices might be slightly less intuitive than polygon area, but the two are proportional. If you really wish, you could run through the change in area that would result from vertex removal, but that's a lot more work for questionable benefit imo.
As mentioned by Angus, if you want a direct solution for the change in area, it's not actually super difficult. Was originally going to leave this as an exercise to the reader, but it's totally possible to solve this exactly, though you need to include vertices on either side.
Assume you're looking at a window of vertices [A, B, C, D] that are connected in that order. In this example we're determining the "cost" of combining B and C.
Calculate the angle offset from collinearity from A toward C. Basically you just want to see how far from collinear the two points are. This is |sin(|arctan(B - A)| - |arctan(C - A)|)| Where pipes are absolute value, and differences are the sensical notion of difference.
Calculate the total distance over which the angle change will effectively be applied, this is just the euclidean distance from A to B times the euclidean distance from B to C.
Multiply the terms from 2 and 3 to get your first term
To get your second term, repeat steps 2 - 4 replacing A with D, B with C, and C with B (just going in the opposite direction)
Calculate the geometric mean of the two terms obtained.
The number that results in step 6 presents the full-picture minus a couple constants.
I tried my own plan first: Protect the vertices touching the bounding box, then remove the rest in the order that changes the resultant area the least, until you can't find a vertice to remove that keeps the new polygon area within X% of the original one. This is the result with X = 5%:
When the user zooms out really far these shapes fit the bill well enough for me. I haven't tried any of the other suggestions. The savings are quite astonishing, sometimes from 80-100 vertices down to 4 or 5.
I am trying to extract semantics from graphical xy plots where the points are plotted and some or all have a label. The label is plotted "near the point" so that a human can normally understand which label goes with which point. For example in this plot it is clear which label(number) belongs to which point(*) and an algorithm based on Euclidian distance would work. (The labels and points have no semantic ordering - e.g. a scatterplot)
*1
*2
*3
*4
In congested plots the authoring software/human may place the label in different directions to avoid overlap. For example in
1**2
**4
3
A human reader can normally work out which label is associated with which label.
One solution I'd accept would be to create a Euclidean distance matrix and shuffle the rows to get the minimum of a function (e.g. the summed squares of the distances on the diagonal or other heuristic). In the second example (with the points labelled a,b,c,d clockwise from the NW corner) we have a distance matrix (to 1 d.p.)
a b c d
1ab2 1 1.0 2.0 2.2 1.4
dc4 2 2.0 1.0 1.4 2.2
3 3 2.0 2.2 1.4 1.0
4 2.2 1.4 1.0 2.0
and we need to label a1 b2 c4 d3. Swapping rows 3 and 4 gives the minimum sum of the diagonal. Here's a more complex example where simply picking the nearest may fail
*1*2*5
**4
3 *6
If this is solved then I shall need to go to cases where the number of labels may be smaller or larger than the number of points.
If the algorithm is standard than I would appreciate a pointer to Open Source Java (e.g. JAMA or Apache maths)
NOTE: This SO answer Associating nearby points with a path doesn't quite work as an answer because the path through the points is given.
You have a complete bipartite graph that one part is numbers and other one is points. Weight's of edge in this graph is euclidean distance between numbers and points. And you're task is finding matching with minimal weight.
This is known problem and has a well known algorithm named as Hungarian Algorithm:
From Wiki:
We are given a nonnegative n×n matrix, where the element in the i-th
row and j-th column represents the cost of assigning the j-th point to
the i-th number. We have to find an assignment of the point to the
numbers that has minimum cost. If the goal is to find the assignment
that yields the maximum cost, the problem can be altered to fit the
setting by replacing each cost with the maximum cost subtracted by the
cost.
The algorithm is easier to describe if we formulate the problem using
a bipartite graph. We have a complete bipartite graph G=(S, T; E) with
n number vertices (S) and n point vertices (T), and each edge has a
nonnegative cost c(i,j). We want to find a perfect matching with
minimum cost. The Hungarian method is a combinatorial optimization
algorithm which solves the assignment problem in polynomial time and
which anticipated later primal-dual methods. f
For detailed algorithm and code you can take a look at topcoder article
and this pdf maybe to use
there is a media file to describe it.
(This video explains why the Hungarian algorithm works)
algorithm :
step 1:- prepare a cost matrix.if the cost matrix is not a square
matrix then add a dummy row(column) with zero cost element.
step 2:- subtract the minimum element in each row from all the
elements of the respective rows.
step 3:- further modify the resulting matrix by subtracting the
minimum elememnt of each column from all the elements of the
respective columns.thus obtain the modified matrix.
step 4:- then,draw minimum no of horizontal and vertical lines to
cover all zeros in the resulting matrix.let the minimum no of lines be
N.now there are 2 possible cases.
case 1 - if N=n,where n is the order of matrix,then an optimal
assignment can be made.so make the assignment to get the required
solution.
case 2 - if N less than n then proceed to step 5
step 5: determine the smallest uncovered element in the
matrix(element not covered by N lines).subtract this minimum element
from all uncovered elements and add the same elements at the
intersection of horizontal and vertical lines.thus the second modified
matrix is obtained.
step 6:- repeat step(3) and (4) untill we get the case (1) of step 4.
step 7:- (to make zero assignments) examine the rows successively
untill a row-wise exactly single zero is found.circle(o) this zero to
make the assignment.then mark a cross(x) over all zeros if lying in
the column of the circled zero,showing that they can't be considered
for future assignment.continue in this manner untill all the zeros
have been examined. repeat the same procedure for column also.
step 8:- repeat the step 6 succeccively until one of the following
situation arises- (i)if no unmarked zeros is left,then the process
ends or (ii) if there lies more than one of the unmarked zero in any
column or row then,circle one of the unmarked zeros arbitrarily and
mark a cross in the cell of remaining zeros in its row or
column.repeat the process untill no unmarked zero is left in the
matrix.
step 9:- thus exactly one marked circled zero in each row and each
column of the matrix is obtained. the assignment corresponding to
these marked circle zeros will give the optimal assignment.
For details see wiki and http://www.ams.jhu.edu/~castello/362/Handouts/hungarian.pdf
If I have understood your question, each of the examples you show has a unique best solution that minimizes the sum of the squares of the distances between points and labels. There is an exponential number of mappings between points and labels, but perhaps you can try the following:
In polynomial time, compute the distance from each label to each point. In a general graph you would have to solve the all-pairs shortest-path problem. Here, as Mikola points out, you can just do it with a doubly nested and use the coordinate geometry: pick either the Euclidean distance or the Manhattan distance.
In polynomial time, find the minimum-cost bipartite matching between points and labels. The solution to this problem will give you a matching between points and labels that minimizes the total distance.
All algorithms (shortest paths, Euclidean distance, min-cost bipartite matching) are standard and can be found on Wikipedia.
What is slightly nonstandard is if you find more than one bipartite matching with minimum cost. If that happens, you can try them all and see if one matching minimizes the sum of distances squared. If there are still ties, I recommend you treat horizontal distance as slightly shorter than vertical distance, and run the algorithm again. If you still have ties, there may not be a unique solution, or you may want to treat "label to the right" as slightly "closer" than label to the left.
But when there is a unique solution, all-pairs shortest paths followed by miniumum-cost bipartite matching should find it.
I haven't seen a common algorithm for this case. Therefore I would solve this problem pragmantically:
Assuming that a label belonging to a point is always the nearest (maybe with others), you could orient on a region growing algorithm (see animated gif). Iterate through every point (red) for each growing step (circle around number label). The growing step is determined by the minimal distance between a point and a label.
Use temporary lists for points and labels. Each time you find a definite pair, remove the corresponding point and label. Just skip the label if there is more than one nearest point (here: label 2). By solving other point-label combinations (here: label 3), they should be mapped in another iteration.
After iterations without any progress due to overall ambiguous situations, you can define a selection method to solve them (e.g. prefer top over bottom, left over right).