How many ways are there to color uncolored edges in a circle - algorithm

given n points on a circle and all edges (C(2,n)) are drawn. Some of these edges are already colored in blue or red. You should find out how many ways are possible to color rested edges in order to have final picture with conditions below:
all edges are colored.
all triangles have 0 or 2 edges in red.
here are some examples:
example 1
input: n = 3 and 0 number of edges are already colored.
output = 4 : because we can color all edges in blue or only one one of them in blue and rest of them in red.
example 2
input n = 4 and 4 number of edges are already colored
1 2 blue
2 3 blue
3 4 red
4 1 red
output = 1 : because the only way to color rested edges is like below:
1 3 blue
2 4 red
constraints:
3 <= n <= 100,000
time limit : 1 second
memory limit: 256 MB
actually I have no idea about ideal data structure for such question, and I need your help for some clues

Here's a linear-time algorithm.
First, observe that every cycle of a valid coloring contains an even number of red edges (I'll leave this as an exercise). Given the colors of a spanning tree, there exists exactly one valid completion. Uniqueness is easy to prove because the color of each edge not in the tree is determined by the parity of the colors of the tree edges with which it forms a cycle. I'll leave validity as another exercise (pressed for time, sorry).
The algorithm is, use depth-first search to find a spanning forest of the given edges, storing the parity of the edge colors between each node and the root of its tree. Given this data, we can verify the given color of every edge not in the forest. If any is wrong, then there are 0 colorings. Otherwise, there are 2^(number of trees minus one) colorings.

Related

algorithm to find closest object

I need to map blue objects to red ones by distance. The center of each object is known. The yellow and green objects, if they are shown, are hints. They help to decide which red object is more important.
For example, in the situation shown in image below:
The bottom blue object should be mapped to the bottom most right red object since both green and yellow objects are very close to that red object.
The right blue object should be mapped to top-right red object since it's closer to it.
I have a naive solution, but I'm not quite sure what to do instead of "????" below
Do you have any suggestions?
My naive solution in sort of pseudo-code:
for each BLUE:
find group P=(YELLOW_BLUE, GREEN_BLUE and RED_BLUE) when each object in P is the closest to BLUE
vector<RED> redCandidates
for each O in P:
if O is YELLOW OR O is GREEN
find closest RED to O
insert RED to redCandidates
if size of redCandidates is 0 -> return RED_BLUE
else if size of redCandidates is 1 -> return redCandidates[0] since hint has more weight to the decision
else if size of redCandidates is > 1 -> ????
UPDATE1
After looking into Minimum Cost Flow problem suggested by #ldog, I decided to use Hungarian Algorithm. I created bipartite graph where each blue node is connected to each red node and the weights on the edges are the distance between blue and red.
Now, before I solve the graph, I need to apply rewards on the edges where yellow/green are close to red. I don't quite understand how to do that.
Let's say distance between blue 1 and the red 4 is D_1_4 = 10 and the distance between the yellow hint 11 and the red 4 is D_4_11 = 3. So, because D_1_4 > D_4_11, should I just add reward to the edge 1_4? Or, should I add the reward to each edge that enters node 4, meaning edges 1_4, 2_4 and 3_4?
It seems your question is not fully formed and you are looking for a decent formulation of the things that you expressed in words.
Here are some suggestions:
Use intersection over union for dealing with how to assign similarity for overlapping areas.
There are many ways you could try to make what you expressed in words quantified, and therefore able to be optimized. One reasonable way to quantify what you expressed in words is as a minimization problem I will discuss below.
The minimization should assign one blue box to exactly one red box (given what you told me.) The green and yellow boxes are hints and are not included in this constraint, they are simply used to modify which red box is preferential over others. To formalize what you described in words, we have the set of red boxes R and the set of blue boxes B. There are m red boxes and n blue boxes with m >= n. Each pairing of blue box i with red box j has a preference w_{ij} (this preference is pre-calculated accounting for the hint boxes as well as spatial proximity.)
We wish to compute:
max \sum_{i<j} w_{ij}x_{ij}
such that
\sum_{k} x_{ik} = 1, \sum_{l} x_{lj} = 1, x_{ik} \in {0,1}
The variable x_{ij} is 1 if and only if blue box i is assigned to red box j, it is 0 otherwise.
This problem (is Totally Unimodular) and can be solved in polynomial time. In fact, it can be solved as an instance of the common Minimum Cost Flow problem. To do this, define a node in a graph for each blue box i, and a node in a graph for each red box j. Connect each blue node to each red node (directed blue->red) with an edge with weight -w_{ij} and capacity 1. Connect each blue node to the source (directed source -> blue) with an edge of capacity 1 and weight 0. Connect each red node to the sink (directed red->sink) with an edge of capacity 1 and weight 0. Give the source a supply of n and the sink a demand of n. Compute the Minimum Cost Flow on this graph (see for example lemon) and the resulting flow yields the maximum solution (alternatively minimum flow.)
Having described this in detail, I see this is already a common approach [1] to solve exactly problems like yours. Here is an implementation.
YMMV depending on how good you make your weights to be. You may want to try a machine learning approach to determine optimal weights using a ground truth dataset and an iterative refinement. The refinement can be computed for a fixed set of blue and red ground truth boxes by refining the weights w_{ij} until all other possible assignments other than the ground truth have a lower score of the optimization than the ground truth. This can be done iterative using any max-margin learning framework or technique, combined with the method I described above (and apparently is described in [1].)
[1] Zhang, Li, Nevatia: Global data association for multi-object tracking using network flows, CVPR (2008).

Two dimensional array scan algorithm

I have being given with a question to scan 2 dimensional array, the array represent a garden, u can step on the garden grass only if the grass is cut down and not too high. a cut down grass represented by number 1. high grass represented with a number bigger then 1, the bigger the number - the higher the grass, heights are unique. in this garden you can have ant colonies which is represented by 0. you can't step on ant colony, no matter what.
Your goal is to cut down all the grass and make it level 1, but u must cat the smallest grass first before you cut any bigger grass. u start from any corner of the garden u choose, as long as u don't stand on an ant colony.
once u cut a grass, it will become number 1, which means, u can now step on it, remember, u can't step on grass bigger then number 1.
Edit:
- heights are unique
The algorithm should return the number of steps made (else -1) , obviously the less steps the better, and you can't go out of the board.
Example:
this matrix
[1,1,1,0]
[1,0,2,1]
[1,0,3,1]
output: 3, because u start from the bottom right cornet, then, u go up, and then left, (chop the grass) and then down (chop grass again).
suggested solution:
is using some kind of a flood fill algorithm (recursion in all directions), and in any case use calculated data structure - like min heap, to hold the current smallest grass height so far, without a pre-clculated min heap we can't never know if we can cut the grass. we take the minimum number from the heap, and start searching for it in the matrix. every cell we encounter, we will go in all directions to search for the number we want.
This solution is obviously the worst, but it solve the problem. I was just wandering if someone can have a better one, I can imagine some dynamic programming solution maybe, not sure. Hell =D
An algorithm that finds the shortest path (with the minimum number of steps):
Collect all cells with height > 1 and sort them by height in increasing order. (They are all unique).
Add the starting cell to the beginning of the sorted collection of cells.
Iterate through the collection and find the shortest path between the current cell and the next cell in the collection, assuming that all cells with higher heights are the ant colonies (cannot be visited). This can be done with BFS. Example:
1 2 4
1 3 0
1 1 1
On the first iteration, we need to find the shortest path between bottom-right corner and cell with height = 2. We should run BFS in the 'virtual garden' where all cells with height > 2 are impossible to go through:
1 2 0
1 0 0
1 1 1
Note, that you need not change higher cells to zero value, just to change the condition in BFS.
Join all found shortest paths.

SPOJ WATER : Developing a BFS algorithm

I am attempting to solve the following question from SPOJ :
On a rectangular mesh comprising nm fields, nm cuboids were put, one
cuboid on each field. A base of each cuboid covers one field and its
surface equals to one square inch. Cuboids on adjacent fields adhere
one to another so close that there are no gaps between them. A heavy
rain pelted on a construction so that in some areas puddles of water
appeared.
Task
Write a program which:
reads from the standard input a size of the chessboard and heights of cuboids put on the fields
computes maximal water volume, which may gather in puddles after the rain
writes results in the standard output.
Input
The number of test cases t is in the first line of input, then t test
cases follow separated by an empty line. In the first line of each
test case two positive integers 1 <= n <= 100, 1 <= m <= 100 are
written. They are the size of the mesh. In each of the following n
lines there are m integers from the interval [1..10000]; i-th number
in j-th line denotes a height of a cuboid given in inches put on the
field in the i-th column and j-th raw of the chessboard.
Output
Your program should write for each tes case one integer equal to the
maximal volume of water (given in cubic inches), which may gather in
puddles on the construction.
Example
Sample input:
1
3 6
3 3 4 4 4 2
3 1 3 2 1 4
7 3 1 6 4 1
Sample output:
5
I am using a BFS to add how much water will flow from the border elements into the puddle(if theres any path found). But I am unable to handle cases where a puddle maybe like two consecutive cuboids. Can anyone help me with that case?
Here is my answer for the problem. For speaking convenience, I assume the index start from (1,1) to (M,N)
As you can imagine as the flow of water, the water can only travel from the higher cuboid to the lower cuboid ( there is no revert direction i.e. the water from lower cuboid will hit the wall of higher cuboid and stop there).
So we build the graph G = (V,E) such that V are M x N vertices i.e. the cuboid on the matrix. The edge are connected (1-way ONLY) that connected cuboid i(th) to cuboid j(th) when
height(i) >= height(j) and (i and j are physically CONNECTED)
So the problem are just a simple BFS.
By the way, I found another one solve this problem as well. Please take a look
http://www.spojsolutions.com/212-water-among-cubes/

Empty intersection counting

I am implementing a game of go on a board size of 7 x 7, w = white stones, b = black stones. I want to count the end result. Remember this is a made up go game, we only count empty cells that are surrounded by black or white stones.
0 1 2 3 4 5 6
0 b
1 b w
2b b w w
3 w w
4 w w
5 w w w
6
I want to count all the intersection surrounded by w and b, that means I want to count cells 2,3 3,2 3,3 3,4 4,3 4,4 for white stones and 0,0 0,1 1,0 1,1 for black stones. All the algorithms I came up with are too complicated.
I will implement the final solution using GNU assembler. I just started learning assembly language so I don't want it to be complicated. The algorithm can use loops and arrays, but no recursion or function calls.
I wanted to see if there is a simple algorithm in linear algebra to solve this problem, or I would appreciate it if you can describe a simple algorithm without the use of recursion and function calls.
A flood fill type algorithm might be applicable:
Find the first unassigned cell.
If the cell is empty, flood fill from it, stopping at edge cells or occupied cells.
For the first occupied cell encountered, record the colour of the occupier.
If an occupied cell encountered is a different colour, record that more than one colour is involved.
After filling, if there was only one colour encountered, mark the whole area as belonging to that colour. The number of empty cells in the area is added to the count.
Repeat from step 1 until all cells are assigned.
A flood fill is a fairly standard algorithm something like:
Push the start cell on a stack.
While the stack is not empty:
Pop a cell from it.
If the cell has not been processed yet (i.e. unassigned in this case):
Process it (i.e. look at its colour in this case).
Push all its neighbours on the stack.
Note that for these algorithms, it can make it easier if the board is surrounded by a layer of invisible "edge" cells. Edge cells and occupied cells have no neighbours for the purpose of your algorithm.
See http://en.wikipedia.org/wiki/Flood_fill
I would try an algorithm that travels along the edges of shapes formed by empty spaces like this:
Start at a piece which is adjacent to an empty space.
By testing all the adjacent spaces, travel along the outside edge of the shape formed by the empty spaces.
If you encounter the edge of the board, you are allowed to continue travelling along the edge of the board.
If you encounter both black and white pieces along the border of the shape, then the shape does not belong to any player.
Otherwise, the shape just outlined belongs to the player who owns all the border pieces.
You can then use the shapes to determine the number of spaces owned by each player.
Something more to think about since this question is tagged 'homework': What is the result in this situation, and how can you account for it?
0 1 2 3 4 5 6
0
1 w w w w w w
2 w
3 w b b b
4 w b b
5 w b b b
6 w

Is this problem NP-hard?

I'm trying to come up with a reasonable algorithm for this problem:
Let's say you have a bunch of balls. Each ball has at least one color, but can also be multicolored. Each ball also has a number on it. There are also a bunch of boxes which are each only one color. The goal is to maximize the sum of the numbers on the balls in the boxes, and the only rules are:
in order to place a ball in a box, it
has to at least have the box's color
on it
you can only put one ball in each
box.
For example, you can put a blue and green ball into a blue box or a green box, but not into a red box.
I've come up with a few optimizations that help a lot in terms of running time. For example, you can sort the balls in descending order of point value. Then as you go from highest number to lowest, if the ball only has one color, and there are no other higher-point balls that contain that color, you can put it in that box (and thus remove that box and that ball from the remaining combinations).
I'm just curious is there's some kind of dynamic algorithm for this type of problem, or if it's just the traveling salesman problem in disguise. Would it help if I knew there were at most X colors? Any help is greatly appreciated. Thanks!
Edit - here's a simple example:
Balls:
1 red ball - 5 points
1 blue ball - 3 points
1 green/red ball - 2 points
1 green/blue ball - 4 points
1 red/blue ball - 1 point
Boxes:
1 red
1 blue
1 green
Optimal Solution:
red ball in red box
blue ball in blue box
green/blue ball in green box
Total value: 12 points (5 + 3 + 4)
This is a special case of the maximum weight matching problem on a weighted bipartite graph. Construct a graph whose left vertices correspond to balls, whose right vertices correspond to boxes and with the edge joining a ball and a box having weight V where V is the number on the ball if the ball can be placed in the box, and 0 otherwise. Add extra boxes or balls joined to the other side with edges of weight zero until you have the same number of vertices on each side. The assignment you're looking for is determined by the set of edges of nonzero weight in the maximum (total) weight matching in the resulting graph.
The assignment algorithm can be solved in O(n^3) time, where n is here the maximum of the number of balls or boxes, using the Hungarian algorithm. (BTW, I should make the disclaimer that I only mention the Hungarian algorithm because it is the theoretical result I happen to be familiar with and it presumably answers the question in the title of whether the original problem is NP-hard. I have no idea whether it is the best algorithm to use in practice.)
Have you tried a greedy alg?
Sort by points/value and place in box if possible.
If there are any exceptions im missing id like to see them.

Resources