1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
#include <cstdio>
#include <cstring>
#include <cassert>
//#include <unistd.h>//usleep
#include <array>
#include <bitset>
#include <algorithm>

#define DBG(...) fprintf(stderr, __VA_ARGS__)

typedef int I;
typedef unsigned U;
static const I MAXN = 20;
static const I GATH = 10;
static const I COST = 100;
static const I INIT_GOLD = 200;

static const I ROWL = MAXN + 1;
static const I BASE = ROWL;
static const I LAST = BASE + ROWL * MAXN;
static const I LEFT = -1;
static const I RIGHT = 1;
static const I TOP = -ROWL;
static const I BOTTOM = ROWL;
static const I BLEN = ROWL * (MAXN + 2);

static inline I index(I x, I y) {
        return ROWL + ROWL * y + x;
}

static U seed = 1;

static inline U randd() {
        seed = seed * 214013u + 2531011;
        return seed >> 16;
}

template <I N>
struct Choice {
        I val[N];
        U wei[N];
        I num;

        Choice() : num(0) {}
        void add(I value, U weight = 1u) {
                if (weight) {
                        val[num] = value;
                        wei[num] = weight;
                        ++num;
                }
        }
        I get(I def = 0) {
                if (num == 0)
                        return def;
                if (num == 1)
                        return val[0];
                U wsum = 0;
                for (I i=0; i<num; ++i)
                        wsum += wei[i];
                U r = randd() % wsum;
                for (I i=0;; ++i)
                        if (r < wei[i])
                                return val[i];
                        else
                                r -= wei[i];
        }
};

typedef Choice<5> RandDir;

static void moved(I a, I b) {
        I r1 = a / ROWL - 1;
        I r2 = b / ROWL - 1;
        I c1 = a % ROWL;
        I c2 = b % ROWL;
        printf("M %d %d %d %d\n", r1, c1, r2, c2);
}

typedef std::bitset<BLEN> Bits;
typedef std::array<I, BLEN> Array;

struct Farmer {
        I pos;
        I gold;
};

struct Tank {
        I pos;
};

typedef std::array<Farmer, BLEN> FArray;
typedef std::array<Tank, BLEN> TArray;

struct State {
        I len;
        I remaining;
        I move;
        I gold;
        I nfarmers;
        I ntanks;
        Array board;
        Bits inside;
        Bits occupied;
        FArray farmers;
        TArray tanks;

        I fwithgold;
        I fwithrock;
        Bits farmerstobase;
        Bits retired;
        Array waytobase;
        Array waytogold;
        Array waytorock;
        Array nearbase;
        Array farbase;

        void print() const;
        void readnew();
        void run();
        void round();
        void mkmove();
        void buy();
        void fillhm();

        U fweight(I i, I j, I g) const {
                if (!inside[j] || board[j] < 0)
                        return 0;
                if (i != j && occupied[j])
                        return 0;
                bool gotobase = farmerstobase[i];
                if (gotobase && j == BASE)
                        return 1000;
                I bias;
                if (gotobase)
                        bias = (waytobase[j] - waytobase[i]) * 40 + 40;
                else if (retired[i]) {
                        if (g > 0)
                                bias = (nearbase[j] - nearbase[i]) * 40 + 40;
                        else
                                bias = (farbase[j] - farbase[i]) * 40 + 40;
                } else
                        bias = (waytogold[j] - waytogold[i]) * 40 + 40;
                assert(bias >= 0);
                if (j == BASE && g >= COST)
                        return bias + 40;
                if (j == BASE && g == 0)
                        return bias + 1;
                if (board[j] == 0)
                        return bias + 3;
                else
                        return bias + 10;
        }

        U tweight(I i, I j) const {
                if (!inside[j])
                        return 0;
                if (i != j && occupied[j])
                        return 0;
                if (j == BASE)
                        return 1;
                I bias;
                if (retired[i])
                        bias = (farbase[j] - farbase[i]) * 40 + 40;
                else
                        bias = (waytorock[j] - waytorock[i]) * 40 + 40;
                assert(bias >= 0);
                if (board[j] > 0)
                        return bias + 2;
                if (board[j] == 0)
                        return bias + 3;
                if (board[j] >= -10)
                        return bias + 20;
                return 10;
        }
};

#define neighbors(i) {(i) + TOP, (i) + LEFT, (i) + RIGHT, (i) + BOTTOM}

void State::round() {
        fillhm();
        mkmove();
        buy();
}

void State::mkmove() {
        for (I n=0; n<nfarmers; ++n) {
                I i = farmers[n].pos;
                I g = farmers[n].gold;
                RandDir rd;
                rd.add(i, fweight(i, i, g));
                for (I nb : neighbors(i))
                        rd.add(nb, fweight(i, nb, g));
                I j = rd.get();
                I gather = board[j] > GATH ? GATH : board[j];
                board[j] -= gather;
                farmers[n].gold += gather;
                if (i != j) {
                        farmers[n].pos = j;
                        occupied[i] = false;
                        occupied[j] = true;
                        if (j == BASE) {
                                gold += farmers[n].gold;
                                remaining -= farmers[n].gold;
                                farmers[n].gold = 0;
                        }
                        moved(i, j);
                }
        }
        for (I n=0; n<ntanks; ++n) {
                I i = tanks[n].pos;
                RandDir rd;
                rd.add(i, tweight(i, i));
                for (I nb : neighbors(i))
                        rd.add(nb, tweight(i, nb));
                I j = rd.get();
                if (board[j] < 0) {
                        I gather = board[j] < -GATH ? -GATH : board[j];
                        board[j] -= gather;
                }
                if (i != j) {
                        tanks[n].pos = j;
                        occupied[i] = false;
                        occupied[j] = true;
                        moved(i, j);
                }
        }
}

void State::buy() {
        if (gold < COST || occupied[BASE])
                return;
        if ((nfarmers + ntanks)*4 > len*len)
                return;

        bool needf = fwithgold > nfarmers;
        bool needt = fwithrock > ntanks;
        I r = BASE + RIGHT;
        I b = BASE + BOTTOM;
        if (needf) {
                RandDir rd;
                rd.add(r, fweight(BASE, r, 0));
                rd.add(b, fweight(BASE, b, 0));
                I i = rd.get();
                if (i) {
                        I gather = board[i] > GATH ? GATH : board[i];
                        occupied[i] = true;
                        farmers[nfarmers].pos = i;
                        farmers[nfarmers].gold = gather;
                        board[i] -= gather;
                        ++nfarmers;
                        gold -= COST;
                        printf("R FARMER\n");
                        moved(BASE, i);
                }
        }
        if (needt && gold >= COST && (nfarmers > 0 || gold >= 2*COST)) {
                RandDir rd;
                rd.add(r, tweight(BASE, r));
                rd.add(b, tweight(BASE, b));
                I i = rd.get();
                if (i) {
                        occupied[i] = true;
                        tanks[ntanks].pos = i;
                        if (board[i] < 0) {
                                I gather = board[i] < -GATH ? -GATH : board[i];
                                board[i] -= gather;
                        }
                        ++ntanks;
                        gold -= COST;
                        printf("R TANK\n");
                        moved(BASE, i);
                }
        }
}

struct PQElem {
        I pos;
        I val;
};

bool pqlt(const PQElem& a, const PQElem& b) {
        return a.val < b.val;
}
struct PQ {
        U hlen;
        std::array<PQElem, BLEN*4> heap;
        PQ() : hlen(0) {}
        bool empty() const { return !hlen; }
        void push(const PQElem& e) {
                assert(hlen < heap.size());
                heap[hlen++] = e;
                std::push_heap(heap.begin(), heap.begin() + hlen, pqlt);
        }
        PQElem pop() {
                std::pop_heap(heap.begin(), heap.begin() + hlen, pqlt);
                return heap[--hlen];
        }
};

void State::fillhm() {
        const I IMAX = 65535;
        {
                fwithgold = 0;
                fwithrock = 0;
                for (I i=BASE; i<LAST; ++i) {
                        if (board[i] > 0)
                                ++fwithgold;
                        else if (board[i] < 0)
                                ++fwithrock;
                }
        }
        {
                // waytobase
                waytobase.fill(0);
                Bits visited;
                PQ pq;
                pq.push({BASE, IMAX});
                while (!pq.empty()) {
                        PQElem e = pq.pop();
                        if (visited[e.pos])
                                continue;
                        visited[e.pos] = true;
                        waytobase[e.pos] = e.val;
                        for (I nb : neighbors(e.pos))
                                if (!visited[nb] && inside[nb] && board[nb] >= 0)
                                        pq.push({nb, e.val - 1});
                }
        }
        {
                // waytogold
                waytogold.fill(0);
                Bits visited;
                PQ pq;
                for (I i=BASE; i<LAST; ++i)
                        if (board[i] > 0)
                                pq.push({i, IMAX});
                while (!pq.empty()) {
                        PQElem e = pq.pop();
                        if (visited[e.pos])
                                continue;
                        visited[e.pos] = true;
                        waytogold[e.pos] = e.val;
                        for (I nb : neighbors(e.pos))
                                if (!visited[nb] && inside[nb] && board[nb] >= 0)
                                        pq.push({nb, e.val - 1});
                }
        }
        {
                // waytorock
                waytorock.fill(0);
                Bits rocks;
                for (I i=BASE; i<LAST; ++i) {
                        if (board[i] < 0) {
                                bool near = false;
                                for (I nb : neighbors(i))
                                        if (waytobase[nb] > 0)
                                                near = true;
                                if (near)
                                        rocks[i] = true;
                        }
                }
                Bits visited;
                PQ pq;
                for (I i=BASE; i<LAST; ++i)
                        if (rocks[i])
                                pq.push({i, IMAX});
                while (!pq.empty()) {
                        PQElem e = pq.pop();
                        if (visited[e.pos])
                                continue;
                        visited[e.pos] = true;
                        waytorock[e.pos] = e.val;
                        for (I nb : neighbors(e.pos))
                                if (!visited[nb] && inside[nb])
                                        pq.push({nb, e.val - 1});
                }
        }
        {
                // farmerstobase
                farmerstobase.reset();
                FArray tobase;
                I flen = 0;
                for (I n=0; n<nfarmers; ++n) {
                        if (farmers[n].gold > 0) {
                                I i = farmers[n].pos;
                                I g = farmers[n].gold;
                                if (fwithgold == 0
                                                || (nfarmers < 3 && g + gold >= COST)
                                                || (nfarmers < 10 && g >= 512)
                                                || (board[i] == 0 && g >= 1024)) {

                                        I dist = waytobase[BASE] - waytobase[i];
                                        tobase[flen].pos = i;
                                        tobase[flen].gold = std::max(g, COST*4) - dist*2*GATH;
                                        ++flen;
                                }
                        }
                }
                I maxtobase = 2;
                if (flen > maxtobase)
                        std::partial_sort(tobase.begin(), tobase.begin() + maxtobase, tobase.begin() + flen,
                                [](const Farmer& a, const Farmer& b) { return a.gold > b.gold; });
                for (I n=0; n<std::min(maxtobase, flen); ++n)
                        farmerstobase[tobase[n].pos] = true;
        }
        {
                // retired
                for (I n=fwithgold*4; n<nfarmers; ++n)
                        retired[farmers[n].pos] = true;
                for (I n=fwithrock; n<ntanks; ++n)
                        retired[tanks[n].pos] = true;
        }
}

void State::print() const {
#define RED "\e[31m"
#define GREEN "\e[32m"
#define BK_BLUE "\e[44m"
#define BK_MAGENTA "\e[105m"
#define BK_YELLOW "\e[43m"
#define ENDC "\e[0m"
        DBG("--- move: %d; gold: %d; remaining %d; farmers: %d; tanks: %d ---\n", move, gold, remaining, nfarmers, ntanks);
        for (I y=0; y<len; ++y) {
                for (I x=0; x<len; ++x) {
                        I i = index(x, y);
                        I v = board[i];
                        bool o = occupied[i];
                        bool istank = false;
                        bool isfarm = false;
                        bool fhasm = false;
                        if (o) {
                                for (I n=0; n<nfarmers; ++n) {
                                        if (farmers[n].pos == i) {
                                                isfarm = true;
                                                if (farmers[n].gold > 0)
                                                        fhasm = true;
                                        }
                                }
                                for (I n=0; n<ntanks; ++n)
                                        if (tanks[n].pos == i)
                                                istank = true;
                        }
                        const char* fg = v > 0 ? GREEN : v < 0 ? RED : "";
                        const char* bg = istank ? BK_MAGENTA : fhasm ? BK_YELLOW : isfarm ? BK_BLUE : "";
                        DBG("%s%s%4d%s ", fg, bg, v, ENDC);
                }
                DBG("\n");
        }
        DBG("\n\n");
}

void State::readnew() {
        move = 0;
        remaining = 0;
        nfarmers = 0;
        ntanks = 0;
        gold = INIT_GOLD;

        inside.reset();
        occupied.reset();
        retired.reset();

        scanf("%d\n", &len);
        for (I y=0; y<len; ++y) {
                for (I x=0; x<len; ++x) {
                        I i = index(x, y);
                        I val;
                        scanf("%d", &val);
                        board[i] = val;
                        inside[i] = true;
                        if (val > 0)
                                remaining += val;
                }
                scanf("\n");
        }

        I hlen = len/2;
        for (I y=0; y<len; ++y) {
                for (I x=0; x<len; ++x) {
                        I i = index(x, y);
                        I l = std::max(y, x);
                        nearbase[i] = l < hlen ? hlen : len - l;
                        farbase[i] = l < hlen ? l : hlen;
                }
        }
}

void State::run() {
        //print();
        while (remaining) {
                round();
                ++move;
                printf("=\n");
                //print();
                //usleep(1000000/10);//
        }
        printf("===\n");
        //print();
}

static State state;

int main() {
        I t, k;
        scanf("%d %d\n", &t, &k);
        for (I i=0; i<t; ++i) {
                state.readnew();
                state.run();
        }
        return 0;
}