Gary in OS class

4

8 votes
Brute-force search, Hard, Dynamic Programming, Greedy algorithm
Problem

Gary recently started taking OS classes in college. His teacher wants him to write a program that can manage storage effectively. Given M bytes of contiguous memory, his program should divide the given M bytes into blocks each of size K this will result in MK blocks each of size K and a wasted memory of size M%K. Now his program should TRY to store N given files (It's not necessary to store all N jfiles) where ith file demands Ai contiguous bytes. Now there are a few rules that imply on the stored files:
1. A file should belong completely to only one block i.e. all Ai bytes of the file should be in one block.
2. Two files shouldn't overlap each other.
3. A block can contain any number of files until it's not completely filled or the space left in it isn't big enough to store a file.
Let's focus on the third point, once the files are stored there still might be some space left in the blocks, Let the summation of these space be called Internal Fragmentation (denoted by F). Gary's aim is to minimise the loss function given by K2+F2. Can you help Gary in writing the best possible solution for the above problem?

This is an approximate problem, your aim is to a write a solution which minimises the value of the above-mentioned loss function. There will be a relative scoring and you will not get 100 points until your solution is the best one. Breaking any of the above mentioned rules will lead to a wrong answer. 50 more test cases will be added once the contest ends.

Input:
The first line contains two space separated integers N and M.
Next N lines contain integer Ai denoting the space required by ith File.

Output:
First line should contain an integer K denoting size of blocks.
In the next MK lines, ith line should first contain an integer Si denoting the number of files stored in ith block followed by Si space separated integers where each integer denotes the number of file to stored.

Constraints:
1N105
1M106
1Ai105
1SiN

Test Generation:
Ai is generated uniformly at random.
For First 10 tests: 1Ai10
For Next 10 tests: 1Ai102
For Next 10 tests: 10Ai103
For Next 10 tests: 102Ai104
For Next 10 tests: 103Ai105

Sample Input
4 10
2
5
2
6
Sample Output
5
2 1 3
1 2
Time Limit: 5
Memory Limit: 256
Source Limit:
Explanation

Here we divide 10 bytes into 2 blocks each of size K=5 bytes, in the first block we store file 1 and file 3 and in block 2 we store file 2. Total internal fragmentation (F) = 1. Your score = 52+12 = 5.099.

Contributers:
Editor Image

?