Let be the number of traversals in walk whose color is not . Its cost is , so the answer is . Fix a color , assign weight 0 to its edges and 1 to other edges, and compute the shortest distance using 0-1 BFS. Minimize over all colors. Push zero-weight relaxations to the front of a deque and unit-weight relaxations to the back. Store the distance at insertion and discard stale entries. Time is and space . Nonnegative weights mean removing a cycle cannot increase the chosen-color cost. Thus subtask 1 may enumerate all simple paths by DFS and count colors; a loose bound is , sufficient for . The answer is between 0 and , as are finite shortest distances, so all arithmetic fits signed 64-bit integers.
Solution written by GPT6.1