Defragmentation
Time limit1sMemory limit128 MB
Given K files scattered across N disk clusters, find the minimum number of cluster moves to pack them consecutively in file order.
- Level
Medium7 of 10
- Topics
- Graph, Simulation, Union-find
- Solved
- No attempts yet
Problem
A secure operating system uses a special file system. The whole disk is divided into clusters of equal size, numbered to . Each file occupies one or more clusters, and those clusters may lie anywhere on the disk. Every cluster not occupied by a file is a free cluster. A file is read fastest when all of its clusters lie in consecutive disk clusters in their natural order.
Because the disk rotates at a constant speed, clusters near the beginning of the disk are read faster than clusters near the end. The files are therefore numbered to in order of decreasing access frequency. Let be the number of clusters in file . In the optimal layout, file occupies clusters , file occupies clusters , and so on.
To reach this layout you perform cluster-moving operations. One cluster-moving operation reads the contents of one occupied cluster into memory and writes them to some free cluster; the source cluster then becomes free and the destination cluster becomes occupied.
Arrange the files into the optimal layout using the minimum possible number of cluster-moving operations.
Input
The input consists of several disk descriptions. The first line of a description contains two integers and separated by a space (). Then lines follow; the -th of them describes file . It begins with the integer , the number of clusters in file (), followed by integers giving the cluster numbers occupied by that file in their natural order. Each cluster number is between and inclusive.
All cluster numbers within one description are distinct, and there is always at least one free cluster. The input ends with a line containing two zeros in place of and .
Output
For each disk description, print exactly one line. If at least one move is required, print We need M move operations., where is the minimum number of cluster-moving operations needed to reach the optimal layout. If the files are already in the optimal layout, print No optimization needed. instead.