To read byte x of a file, the file system first finds which block holds it, then follows pointers from the inode: a direct pointer, or an indirect block, or two or three levels of them.
What to build
For each byte offset, say how the inode reaches the block that holds it.
Requirements
- The block number is
offset / B(whole-number division), andk = B / Pis the number of pointers in an indirect block. The inode hasDdirect pointers, then one single, one double and one triple indirect pointer. - Blocks
0toD − 1aredirect i(the pointer number). The nextkblocks aresingle i(positioniin the indirect block). The nextk²aredouble i j(positioniin the outer block,jin the inner one). The nextk³aretriple i j l. Beyond that printtoo big. - Numbering inside a level starts at 0 for the first block of that level.
Input
The first line has B, P and D (P divides B; 4 ≤ P ≤ 8, 64 ≤ B ≤ 4096, 0 ≤ D ≤ 15). The second line has q (1 ≤ q ≤ 20), and the third line has q byte offsets (0 to 10^12).
Output
One line per offset, such as direct 3, single 17, double 2 5, triple 0 1 7 or too big.
Constraints
Use 64-bit integers.
Example
Input:
4096 4 12
4
0 49151 49152 53247
Output:
direct 0
direct 11
single 0
single 0
Why it works
Each level takes away the blocks of the levels before it, and what is left is split by k: the quotient picks the outer pointer and the remainder the inner one. A small file never leaves the direct pointers, so reading it costs no extra disk reads; a large file pays one more read for each level.
Examples
4096 4 12 4 0 49151 49152 53247
direct 0 direct 11 single 0 single 0
64 8 2 3 0 127 128
direct 0 direct 1 single 0
Hints
Hint 1
block = offset / B, and k = B / P. If block is below D it is a direct pointer with that index.
Hint 2
Otherwise subtract D from block. If the result is below k, it is the single indirect, at that index. Subtract k and try double (index / k and index % k), then triple.
Hint 3
Use long long for the offset and for k * k * k. If nothing matches, print too big.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int main(void) {
long long b, p, d, q, offset;
scanf("%lld %lld %lld", &b, &p, &d);
scanf("%lld", &q);
long long k = b / p;
for (long long i = 0; i < q; i++) {
scanf("%lld", &offset);
long long blk = offset / b;
if (blk < d) {
printf("direct %lld\n", blk);
continue;
}
blk -= d;
if (blk < k) {
printf("single %lld\n", blk);
continue;
}
blk -= k;
if (blk < k * k) {
printf("double %lld %lld\n", blk / k, blk % k);
continue;
}
blk -= k * k;
if (blk < k * k * k) {
printf("triple %lld %lld %lld\n", blk / (k * k), (blk / k) % k, blk % k);
continue;
}
printf("too big\n");
}
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step