Buffer Manager
Time limit1sMemory limit128 MB
Given buffer states (free, digit worthiness, or locked) in a string, find the starting position of the K-length window without locked buffers whose digit sum is smallest.
- Level
Medium4 of 10
- Topics
- Sliding window, Prefix sum, Implementation, String
- Solved
- No attempts yet
Problem
A DBMS (Database Management System) team has built an efficient Lock Manager and now needs a Buffer Manager.
Data blocks read from the hard drive are stored in main memory in a fixed number of pre-allocated buffers. Each buffer holds exactly one data block and is in one of three states:
- free — it holds no useful data; its worthiness is .
- occupied — it holds data with an integer worthiness from to .
- locked — it is in use by some part of the DBMS, so it can be neither reused nor flushed, and its worthiness is undefined.
When the DBMS reads a data block it must pick a buffer to store it. A free buffer is preferred; if none is free, an occupied non-locked buffer must be flushed. Maximum performance is achieved when several consecutive data blocks are read into consecutive memory buffers, so the manager always allocates one contiguous run of buffers.
Buffers are numbered from to (). Given a request to read data blocks (), the Buffer Manager must choose consecutive non-locked buffers numbered whose total worthiness (the cost of flushing them) is as small as possible. If several starting positions give the same minimal total, choose the smallest . If no run of consecutive non-locked buffers exists — which also happens when — the request is impossible.
Write a program that processes one such request.
Input
The first line contains two integers and separated by a space.
The buffer states follow, one character per buffer:
0— the buffer is free.1–9— the buffer is occupied and has that worthiness.*— the buffer is locked.
These characters are written without spaces, grouped per line. Every line after the first contains exactly characters, except possibly the last.
Output
Print a single integer : the starting buffer number of the chosen run of consecutive non-locked buffers with the minimal total worthiness. If several starting positions tie, print the smallest .
Print if it is impossible to find consecutive non-locked buffers.