Defragment
InterviewTime limit1sMemory limit128 MB
Given files spread over N disk clusters, find the minimum number of single-cluster moves to place them contiguously in order, with file i starting after file i-1.
- Level
Medium6 of 10
- Topics
- Greedy, Array, Implementation, Hash map
- Solved
- No attempts yet
Problem
You are developing the file system for a new operating system. All disk space is divided into equally sized clusters, numbered from to . Each file occupies one or more clusters located at arbitrary positions on the disk. Every cluster not occupied by a file is considered free.
A file can be read fastest when all of its clusters lie in consecutive clusters in their natural order. Because the disk rotates at a constant speed, clusters near the beginning are read faster than clusters near the end, so the files are numbered from to in order of decreasing access frequency. In the optimal layout, file occupies clusters , file occupies clusters , and so on, where is the number of clusters that file occupies.
To reach the optimal layout you perform cluster-moving operations. One cluster-moving operation reads the contents of one occupied cluster and writes them to a free cluster; afterwards the source cluster becomes free and the destination cluster becomes occupied.
Compute the minimum number of cluster-moving operations required to place all files in the optimal layout.
Input
The first line contains two integers and separated by a space (). Each of the next lines describes one file. The description of the -th file starts with the integer , the number of clusters in file (), followed by integers giving the cluster numbers occupied by that file in natural order.
All cluster numbers in the input are distinct, and there is always at least one free cluster.
Output
Print a single integer: the minimum number of cluster-moving operations needed to place all files in the optimal layout. If the files are already in the optimal layout, print .