Given counts of red, yellow, and blue unicorns, arrange them in a ring so no two neighbors share a hair color, or report IMPOSSIBLE, printing the lexicographically smallest valid string.
Medium5GreedyImplementationStringMathNo attempts yetTime limit5sMemory limit512 MBYou own N pet unicorns. Each mane holds one or two kinds of hair among red hairs, yellow hairs, and blue hairs, and the color of a mane depends on exactly which kinds it holds.
You have R, O, Y, G, B, and V unicorns with red, orange, yellow, green, blue, and violet manes.
You have just built a circular stable with N stalls arranged in a ring, so every stall borders two other stalls. You want to put exactly one unicorn in each stall. Unicorns need to feel rare, so a unicorn cannot stand next to another unicorn whose mane holds at least one of the same hair colors. A unicorn with an orange mane cannot stand next to a unicorn with a violet mane, because both manes hold red hairs. A unicorn with a green mane cannot stand next to a unicorn with a yellow mane, because both manes hold yellow hairs.
Decide whether all of the unicorns can be placed, and produce an arrangement when they can.
The first line holds the number of test cases T. Each of the next T lines holds one test case: seven integers N, R, O, Y, G, B, and V separated by spaces.
Limits
For each test case, print one line Case #x: y, where x is the test case number starting from 1. If the unicorns cannot all be placed, y is IMPOSSIBLE. Otherwise y is a string of N characters giving the unicorns in the stalls, starting at a stall of your choice and reading clockwise around the ring. Write R for a unicorn with a red mane, O for orange, Y for yellow, G for green, B for blue, and V for violet.
Several strings can describe a valid arrangement, including the strings you get by starting at a different stall. Collect all of them and print only the lexicographically smallest one. Characters compare in ASCII order, so B < G < O < R < V < Y.
The stalls form a ring, so the first character and the last character of the printed string are neighbors as well.