2

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:

  1. all edges are colored.
  2. 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

Community
  • 1
  • 1
Mahsirat
  • 79
  • 7

1 Answers1

3

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.

David Eisenstat
  • 64,237
  • 7
  • 60
  • 120
  • Thanks for your answer. But I could not understand your algorithm very well. Could you please solve my second example by this algorithm as an example. @ David Eisenstat – Mahsirat Apr 21 '19 at 16:49
  • @Mahsirat the four edges form a simple cycle. There are several possible spanning forests, each comprised of one tree containing three of the edges. The fundamental cycle of the fourth is the right color, so there are 2^(1-1) = 1 colorings. – David Eisenstat Apr 22 '19 at 00:17