In the FAT file system the file allocation table has one entry per block: the number of the next block of the file, -1 at the end of a file, or 0 if the block is free. A directory entry only remembers the first block, and the chain gives the rest.
What to build
Follow the chains of files in a FAT and count the free blocks.
Requirements
- Entry
fat[b]is the block afterbin its file,-1ifbis the last block, and0ifbis free. Block 0 is reserved for the boot sector: its entry is always 0 and it is never in a file and never counted as free. - For each start block, print
s: b1 b2 ... (k blocks)with the blocks in order, beginning with the start block, ors: emptywhen the start block is free. - After all queries print
free blocks: F, the number of entries 1 ton − 1that are 0.
Input
The first line has n (2 ≤ n ≤ 30), the number of blocks. The second line has the n FAT entries. The third line has q (1 ≤ q ≤ 10) and the fourth line has q start blocks (1 to n − 1).
Output
One line per query, then free blocks: F.
Constraints
The table is valid: every chain ends in -1 and there are no loops.
Example
Input:
10
0 0 5 -1 0 8 0 0 3 0
1
2
Output:
2: 2 5 8 3 (4 blocks)
free blocks: 5
Why it works
A chain is a linked list stored in a table. The table is small enough to keep in memory, so following it costs no disk reads; only the data blocks are read. Free blocks are the zeros, which makes allocating a block a simple search of the table.
Examples
10 0 0 5 -1 0 8 0 0 3 0 1 2
2: 2 5 8 3 (4 blocks) free blocks: 5
6 0 -1 4 0 -1 0 3 1 2 3
1: 1 (1 blocks) 2: 2 4 (2 blocks) 3: empty free blocks: 2
Hints
Hint 1
Start at the given block and follow fat[b] until you reach -1, printing each block and counting.
Hint 2
If fat[start] is 0 the block is free: print empty for that query.
Hint 3
Count the free blocks by looking at entries 1 to n-1 only; block 0 is reserved.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int main(void) {
int n, fat[30], q, s;
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &fat[i]);
scanf("%d", &q);
for (int i = 0; i < q; i++) {
scanf("%d", &s);
if (fat[s] == 0) {
printf("%d: empty\n", s);
continue;
}
int count = 0;
printf("%d:", s);
for (int b = s; b != -1; b = fat[b]) {
printf(" %d", b);
count++;
}
printf(" (%d blocks)\n", count);
}
int free_blocks = 0;
for (int b = 1; b < n; b++)
if (fat[b] == 0) free_blocks++;
printf("free blocks: %d\n", free_blocks);
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step