No Time to Paint
Time limit5sMemory limit512 MB
Given a target string of 26 ordered colors and Q queries, each leaving one interval unpainted, find the minimum number of brush strokes to paint the rest, where a stroke paints a contiguous range one color and no lighter color may cover a darker one.
- Level
Hard8 of 10
- Topics
- Prefix sum, Stack, Greedy, Array
- Solved
- No attempts yet
Problem
Bessie has recently received a painting set, and she wants to paint the long fence at one end of her pasture. The fence consists of consecutive 1-meter segments (). Bessie has 26 different colors available, which she labels with the letters 'A' through 'Z' in increasing order of darkness ('A' is a very light color, and 'Z' is very dark). She can therefore describe the desired color she wants to paint each fence segment as a length- string where each character is a letter.
Initially, all fence segments are uncolored. Bessie can color any contiguous range of segments with a single color in a single brush stroke as long as she never paints a lighter color over a darker color (she can only paint darker colors over lighter colors).
For example, an initially uncolored segment of length four can be colored as follows:
.... -> BBB. -> BBLL -> BQQL
Running short on time, Bessie thinks she may need to leave some consecutive range of fence segments unpainted. Currently, she is considering candidate ranges (), each described by two integers with giving the indices of endpoints of the range of segments to be left unpainted.
For each candidate range, what is the minimum number of strokes needed to paint every fence segment outside those in the range with its desired color while leaving all fence segments inside the range uncolored? Bessie does not actually do any painting during this process, so the answers for each candidate range are independent.
Input
The first line contains and .
The next line contains a string of length representing the desired color for each fence segment.
The next lines each contain two space-separated integers and representing a candidate range to possibly leave unpainted.
Output
For each of the candidates, output the answer on a new line.