Fotografen
InterviewTime limit2sMemory limit1024 MB
Given N photos with rotations, find the fewest operations that rotate k adjacent photos clockwise at once to make all upright, or -1 if impossible.
- Level
Medium5 of 10
- Topics
- Greedy, Prefix sum, Array
- Solved
- No attempts yet
Problem
A photographer took many nice photos with a digital camera and connects it to a computer to transfer them. The camera was held at different angles for each shot, so some photos are rotated. The four possible rotations are called up, right, down, and left, where up means the side that points up in the picture. A photo is correct when it is rotated up. The computer shows the photos in a list and has a function that rotates one photo 90 degrees clockwise. The rotation order is shown below.

How a photo is rotated
The photographer finds rotating photos one by one boring, so turns it into a game. The photographer picks a positive integer . The only way to rotate photos is to select exactly adjacent photos from the list and rotate all of them at once. Formally, there are photos . The photographer picks an index (), and photos are rotated 90 degrees clockwise. This is one operation.
The goal is to make every photo upright with as few operations as possible. Write a program that computes the minimum number of operations needed.
Input
The first line contains two integers and (), the total number of photos and the number of photos that must be rotated together.
The second line contains characters that give the starting rotation of the photos: U for up, H for right, N for down, and V for left.
Output
Print the minimum number of operations needed. If it is impossible to make all photos upright, print .
Hint
One possible optimal solution: rotate positions 3-4 three times to get UVVU, then rotate positions 2-3 once to get UUUU. This uses four operations in total.