Translate addresses

Translate logical addresses to physical ones with a page table.

Input

The first line has the page size s (a power of 2, from 16 to 4096) and the number of pages k (1 ≤ k ≤ 32). The second line has the page table: k frame numbers, where -1 means the page is not in memory. The third line has q (1 ≤ q ≤ 50), and the fourth line has q logical addresses (0 to 1,000,000).

Output

One line per address:

  • invalid if its page number is k or more,
  • page fault if its page is not in memory,
  • otherwise the physical address.

Examples

Example 1 · Input
1024 4
5 2 -1 7
5
0 1500 2100 3100 4100
Expected output
5120
2524
page fault
7196
invalid
Example 2 · Input
16 3
0 -1 1
4
15 16 33 48
Expected output
15
page fault
17
invalid

Hints

Hint 1

page = address / size and offset = address % size.

Hint 2

A page number of k or more does not exist: invalid.

Hint 3

Otherwise frame = table[page]; -1 means a page fault, else print frame * size + offset.

Solution

Show one correct solution (try it yourself first)
#include <stdio.h>

int main(void) {
    int s, k, table[32], q;
    scanf("%d %d", &s, &k);
    for (int i = 0; i < k; i++) scanf("%d", &table[i]);
    scanf("%d", &q);
    for (int i = 0; i < q; i++) {
        int address;
        scanf("%d", &address);
        int page = address / s, offset = address % s;
        if (page >= k) printf("invalid\n");
        else if (table[page] < 0) printf("page fault\n");
        else printf("%d\n", table[page] * s + offset);
    }
    return 0;
}

Lesson: Paging →