#55414: 17ms解


phigrosgame@gmail.com (Game Phigros)


#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
using namespace std;

static const char *B;
static long bp;

static char *O;
static long ol;

static inline int rd() {
    while (*(B + bp) < '0' || *(B + bp) > '9') bp++;
    int x = 0;
    char c;
    while ((c = *(B + bp)) >= '0' && c <= '9') { x = x * 10 + (c - '0'); bp++; }
    return x;
}

static inline void wr(int x, char ec) {
    if (!x) { O[ol++] = '0'; O[ol++] = ec; return; }
    char t[12]; int n = 0;
    while (x > 0) { t[n++] = '0' + x % 10; x /= 10; }
    while (n > 0) O[ol++] = t[--n];
    O[ol++] = ec;
}

static inline void sort4(int a[4]) {
    int t;
    if (a[0] > a[1]) { t=a[0]; a[0]=a[1]; a[1]=t; }
    if (a[2] > a[3]) { t=a[2]; a[2]=a[3]; a[3]=t; }
    if (a[0] > a[2]) { t=a[0]; a[0]=a[2]; a[2]=t; }
    if (a[1] > a[3]) { t=a[1]; a[1]=a[3]; a[3]=t; }
    if (a[1] > a[2]) { t=a[1]; a[1]=a[2]; a[2]=t; }
}

static inline void *fast_alloc(size_t bytes) {
    void *p = mmap(nullptr, bytes, PROT_READ | PROT_WRITE,
                   MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE, -1, 0);
    return p;
}

int main() {
    struct stat st;
    fstat(STDIN_FILENO, &st);
    long bl = st.st_size;
    B = (const char*)mmap(nullptr, bl, PROT_READ,
                           MAP_PRIVATE | MAP_POPULATE, STDIN_FILENO, 0);
    bp = 0;

    int R = rd(), C = rd(), Q = rd();
    long long N = (long long)R * C;

    O = (char*)fast_alloc((size_t)Q * 32 + 64);

    int *S  = (int*)fast_alloc(sizeof(int) * N);
    int *pk = (int*)fast_alloc(sizeof(int) * (N + 1));

    for (int r = 0; r < R; r++) {
        int base = r * C;
        int rshift = r << 10;
        for (int c = 0; c < C; c++) {
            int id = rd();
            S[base + c] = id;
            pk[id] = rshift | c;
        }
    }

    int a[4];
    for (int q = 0; q < Q; q++) {
        int id = rd();
        int p = pk[id];
        int r = p >> 10, c = p & 1023;

        a[0] = S[(r == 0 ? R - 1 : r - 1) * C + c];
        a[1] = S[(r == R - 1 ? 0 : r + 1) * C + c];
        a[2] = S[r * C + (c == 0 ? C - 1 : c - 1)];
        a[3] = S[r * C + (c == C - 1 ? 0 : c + 1)];
        sort4(a);

        wr(a[0], ' '); wr(a[1], ' '); wr(a[2], ' '); wr(a[3], '\n');
    }

    write(STDOUT_FILENO, O, ol);
    return 0;
}