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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
#include <bits/stdc++.h>
#define MP make_pair
#define PB push_back
#define st first
#define nd second
#define rd third
#define FOR(i, a, b) for(int i =(a); i <=(b); ++i)
#define RE(i, n) FOR(i, 1, n)
#define FORD(i, a, b) for(int i = (a); i >= (b); --i)
#define REP(i, n) for(int i = 0;i <(n); ++i)
#define VAR(v, i) __typeof(i) v=(i)
#define FORE(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) ((int)(x).size())
#define __builtin_ctz __builtin_ctzll
#define __builtin_clz __builtin_clzll
#define __builtin_popcount __builtin_popcountll
using namespace std;
template<typename TH> void _dbg(const char* sdbg, TH h) { cerr<<sdbg<<"="<<h<<"\n"; }
template<typename TH, typename... TA> void _dbg(const char* sdbg, TH h, TA... t) {
  while(*sdbg != ',') { cerr<<*sdbg++; } cerr<<"="<<h<<","; _dbg(sdbg+1, t...);
}
#ifdef LOCAL
#define debug(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
#define debugv(x) {{cerr <<#x <<" = "; FORE(itt, (x)) cerr <<*itt <<", "; cerr <<"\n"; }}
#else
#define debug(...) (__VA_ARGS__)
#define debugv(x)
#define cerr if(0)cout
#endif
#define next ____next
#define prev ____prev
#define left ____left
#define hash ____hash
typedef long long ll;
typedef long double LD;
typedef pair<int, int> PII;
typedef pair<ll, ll> PLL;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<ll> VLL;
typedef vector<pair<int, int> > VPII;
typedef vector<pair<ll, ll> > VPLL;

template<class C> void mini(C&a4, C b4){a4=min(a4, b4); }
template<class C> void maxi(C&a4, C b4){a4=max(a4, b4); }
template<class T1, class T2>
ostream& operator<< (ostream &out, pair<T1, T2> pair) { return out << "(" << pair.first << ", " << pair.second << ")";}
template<class A, class B, class C> struct Triple { A first; B second; C third;
  bool operator<(const Triple& t) const { if (st != t.st) return st < t.st; if (nd != t.nd) return nd < t.nd; return rd < t.rd; } };
template<class T> void ResizeVec(T&, vector<int>) {}
template<class T> void ResizeVec(vector<T>& vec, vector<int> sz) {
  vec.resize(sz[0]); sz.erase(sz.begin()); if (sz.empty()) { return; }
  for (T& v : vec) { ResizeVec(v, sz); }
}
typedef Triple<int, int, int> TIII;
template<class A, class B, class C>
ostream& operator<< (ostream &out, Triple<A, B, C> t) { return out << "(" << t.st << ", " << t.nd << ", " << t.rd << ")"; }
template<class T> ostream& operator<<(ostream& out, vector<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }
template<class T> ostream& operator<<(ostream& out, set<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }
template<class L, class R> ostream& operator<<(ostream& out, map<L, R> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; }

struct Unit {
  int r, c;
  Unit() {};
  Unit(int r_, int c_) : r(r_), c(c_) {}
};
struct Farmer : public Unit {
  int gold;
  Farmer(int r_, int c_, int g_) : gold(g_) {
    r = r_;
    c = c_;
  }
};

struct Tank : public Unit {
  Tank(int r_, int c_) {
    r = r_;
    c = c_;
  }
};
enum TakenType {
  kFree, kFarmer, kTank
};
const int kRecruitCost = 100;
const int kMaxTakenGold = 10;
const int kMaxDamagedStones = 10;
const int kBaseI = 0, kBaseJ = 0;
int sum_completed_turns;
int dr[] = {1, -1, 0, 0};
int dc[] = {0, 0, 1, -1};
const int kDirs = 4;
const int kInf = 1e6;
struct Sol {
  
  int completed_turns;
  VVI board;
  int n;
  int bil;
  vector<Farmer> farmers;
  vector<Tank> tanks;
  vector<vector<TakenType>> taken;
  vector<int> recruiting_times;
  int done_moves;
  int prv_moves;
  void UpdState() {
    for (auto& farmer : farmers) {
      assert(board[farmer.r][farmer.c] >= 0);
      int to_take = min(board[farmer.r][farmer.c], kMaxTakenGold);
      board[farmer.r][farmer.c] -= to_take;
      farmer.gold += to_take;
    }
    for (auto& tank : tanks) {
      if (board[tank.r][tank.c] > 0) { continue; }
      int to_destroy = min(-board[tank.r][tank.c], kMaxDamagedStones);
      board[tank.r][tank.c] += to_destroy;
    }
  }
  void RecruitFarmer() {
    cout<<"R FARMER\n";
    recruiting_times.PB(completed_turns);
    assert(bil >= kRecruitCost);
    assert(taken[kBaseI][kBaseJ] == kFree);
    bil -= kRecruitCost;
    farmers.PB({kBaseI, kBaseJ, 0});
    //debug(farmers.back().r);
    taken[kBaseI][kBaseJ] = kFarmer;
  }
  void RecruitTank() {
    cout<<"R TANK\n";
    assert(bil >= kRecruitCost);
    assert(taken[kBaseI][kBaseJ] == kFree);
    bil -= kRecruitCost;
    tanks.PB({kBaseI, kBaseJ});
    taken[kBaseI][kBaseJ] = kTank;
  }
  void MoveFarmer(Farmer& f, int r2, int c2) {
    MoveUnit(f, r2, c2);
    if (f.gold && r2 == kBaseI && c2 == kBaseI) {
      bil += f.gold;
      f.gold = 0;
    }
  }
  void MoveTank(Tank& t, int r2, int c2) {
    MoveUnit(t, r2, c2);
  }
  bool Valid(int r, int c) {
    return r >= 0 && r < n && c >= 0 && c < n;
  }
  void MoveUnit(Unit& unit, int r2, int c2) {
    done_moves++;
    cout<<"M "<<unit.r<<" "<<unit.c<<" "<<r2<<" "<<c2<<endl;
    assert(Valid(r2, c2) && abs(unit.r - r2) + abs(unit.c - c2) == 1);
    assert(taken[r2][c2] == kFree);
    swap(taken[unit.r][unit.c], taken[r2][c2]);
    unit.r = r2;
    unit.c = c2;
  }
  bool stuck;
  bool IsBoardClear() {
    REP (i, n) {
      REP (j, n) {
        if (board[i][j] > 0) { return false; }
      }
    }
    if (stuck) { return true; }
    REP (i, n) {
      REP (j, n) {
        if (board[i][j] < 0) { return false; }
      }
    }
    return true;
  }
  bool AreFarmersEmpty() {
    for (auto& f : farmers) {
      if (f.gold) { return false; }
    }
    return true;
  }
  int SumAbs() {
    int res = 0;
    REP (i, n) {
      REP (j, n) {
        res += abs(board[i][j]);
      }
    }
    return res;
  }
  int prv_abs;
  void EndTurn() {
    int cur_abs = SumAbs();
    if (done_moves == prv_moves && cur_abs == prv_abs) {
      stuck = true;
//       int any_gold = 0;
//       REP (i, n) {
//         REP (j, n) {
//           if (board[i][j] > 0) { any_gold = true; }
//         }
//       }
//       if (!any_gold) {
//         stuck = true;
//       }
    }
    prv_abs = cur_abs;
    prv_moves = done_moves;
//     REP (i, n) {
//       REP (j, n) {
//         if (taken[i][j] == kFarmer) {
//           for (auto f : farmers) {
//             if (f.r == i && f.c == j) {
//               if (f.gold) {
//                 cerr<<"F";
//               } else {
//                 cerr<<"E";
//               }
//             }
//           }
//         } else if (taken[i][j] == kTank) {
//           for (auto t : tanks) {
//             if (t.r == i && t.c == j) {
//               cerr<<"T";
//             }
//           }
//         } else {
//           cerr<<board[i][j];
//         }
//       }
//       cerr<<endl;
//     }
//     cerr<<endl;
    completed_turns++;
    UpdState();
    cout<<"=\n";
  }
  void Test() {
    cin>>n;
    done_moves = 0;
    prv_abs = 0;
    stuck = 0;
    int bfses = 0;
    completed_turns = 0;
    board = VVI(n, VI(n));
    taken = vector<vector<TakenType>>(n, vector<TakenType>(n, kFree));
    bool any_stones = false;
    int wanted_tanks = 0;
    int cnt_stones_cells = 0;
    REP (i, n) {
      REP (j, n) {
        cin>>board[i][j];
        if (board[i][j] < 0) {
          cnt_stones_cells++;
          any_stones = true;
        }
      }
    }
    int ratio_tanks = 20;
    wanted_tanks = (cnt_stones_cells + ratio_tanks - 1) / ratio_tanks; 
    bil = 2 * kRecruitCost;
    int fir_clear_board = -1;
    while (1) {
      if (completed_turns > 100000) {
        throw 1;
      }
      int gold_cells = 0;
      REP (i, n) {
        REP (j, n) {
          if (board[i][j] > 0) {
            gold_cells++;
          }
        }
      }
      if (IsBoardClear()) {
        if (fir_clear_board == -1) {
          fir_clear_board = completed_turns;
          debug("GOING BACK HOME", completed_turns);
        }
//           REP (r, n) {
//             REP (c, n) {
//               if (taken[r][c] == kFarmer) {
//                 for (auto f : farmers) {
//                   if (f.r == r && f.c == c) {
//                     if (f.gold == 0) {
//                       cerr<<"O";
//                     } else {
//                       cerr<<"X";
//                     }
//                   }
//                 }
//               } else {
//                 cerr<<".";
//               }
//             }
//             cerr<<endl;
//           }
//           cerr<<endl;
        //debug(completed_turns);
        vector<int> who_moved(SZ(farmers));
        REP (ii, SZ(farmers)) {
          auto& f = farmers[ii];
          if (f.gold && f.r == 0) {
            if (taken[1][f.c] == kFree && board[1][f.c] == 0) {
              MoveFarmer(f, 1, f.c);
            }
            who_moved[ii] = 1;
          }
        }
        REP (ii, SZ(farmers)) {
          if (who_moved[ii]) { continue; }
          auto& f = farmers[ii];
        //for (auto& f : farmers) {
          if (f.gold == 0) {
            if (Valid(f.r, f.c + 1) && taken[f.r][f.c + 1] == kFree && board[f.r][f.c + 1] == 0) {
              MoveFarmer(f, f.r, f.c + 1);
            } else if (Valid(f.r + 1, f.c) && taken[f.r + 1][f.c] == kFree && board[f.r + 1][f.c] == 0) {
              MoveFarmer(f, f.r + 1, f.c);
            }
          } else {
            if (Valid(f.r, f.c - 1) && taken[f.r][f.c - 1] == kFree && board[f.r][f.c - 1] == 0) {
              MoveFarmer(f, f.r, f.c - 1);
            } else if (Valid(f.r - 1, f.c) && taken[f.r - 1][f.c] == kFree && (f.r - 1 != 0 || f.c == 0) && board[f.r - 1][f.c] == 0) {
              MoveFarmer(f, f.r - 1, f.c);
            } 
          }
        }
        for (auto& f : tanks) {
          if (Valid(f.r, f.c + 1) && taken[f.r][f.c + 1] == kFree) {
            MoveTank(f, f.r, f.c + 1);
          } else if (Valid(f.r + 1, f.c) && taken[f.r + 1][f.c] == kFree) {
            MoveTank(f, f.r + 1, f.c);
          }
        }
        
        
      } else {
        
        
        
        vector<vector<int>> wanted(n, VI(n));
        int want_more_farmers = (SZ(farmers) <= 24);
        int want_more_tanks = SZ(tanks) < wanted_tanks;
        if (bil >= kRecruitCost && taken[kBaseI][kBaseJ] == kFree && (want_more_farmers || want_more_tanks)) {
          if (want_more_tanks && (!want_more_farmers || SZ(tanks) <= SZ(farmers))) {
            RecruitTank();
          } else {
            RecruitFarmer();
          }
        }
        int cur_threshold = 512;
        function<LD(int, int, int)> ProfitFarmer = [&](int r, int c, int d) {
          if (board[r][c] <= 0 || d == kInf) { return (LD)0; }
          int tim = d + (board[r][c] + kMaxTakenGold - 1) / kMaxTakenGold;
          //return (LD)1. * board[r][c] / tim;
          if (want_more_farmers) {
            return (LD)1. * board[r][c] / tim;
          } else {
            if (gold_cells <= 2) {
              return (LD)1;
            } else {
              return (LD)1. / d;
            }
          }
        };
        function<LD(int, int, int)>ProfitTank = [&](int r, int c, int d) {
          if (board[r][c] >= 0 || d == kInf) { return (LD)0; }
          int tim = d + (-board[r][c] + kMaxDamagedStones - 1) / kMaxDamagedStones;
          return (LD)1. / tim;
        };
          
        function<pair<VVI, vector<VPII>>(Unit&, bool)> Bfs = [&](Unit& f, bool is_farmer) {
          bfses++;
          VVI dis(n, VI(n, kInf));
          vector<VPII> par(n, VPII(n, {-1, -1}));
          int sr = f.r, sc = f.c;
          dis[sr][sc] = 0;
          VPII que{{sr, sc}};
          for (int ii = 0; ii < SZ(que); ii++) {
            int cr, cc;
            tie(cr, cc) = que[ii];
            REP (dir, kDirs) {
              int nr, nc;
              nr = cr + dr[dir];
              nc = cc + dc[dir];
              if (!Valid(nr, nc)) { continue; }
              if (wanted[nr][nc]) { continue; }
              if (taken[nr][nc] != kFree) { continue; }
              if (board[nr][nc] < 0 && is_farmer) { continue; }
              if (dis[nr][nc] == kInf) {
                dis[nr][nc] = dis[cr][cc] + 1;
                par[nr][nc] = {cr, cc};
                if (board[nr][nc] >= 0) {
                  que.PB({nr, nc});
                }
              }
            }
          }
          return pair<VVI, vector<VPII>>(dis, par);
        };
        function<VPII(vector<VPII>&, int, int)> GetPathBegExcl = [&](vector<VPII>& par, int r, int c) {
          VPII path;
          while (r != -1) {
            path.PB({r, c});
            tie(r, c) = par[r][c];
          }
          path.pop_back();
          reverse(ALL(path));
          return path;
        };
        vector<int> who_moved(SZ(farmers));
        if (want_more_farmers || want_more_tanks) {
          cur_threshold = 200;
          if (SZ(farmers) <= 4) {
            cur_threshold = 100;
          }
          //bool any_going_home = false;
          //vector<VVI> dises;
          int best_dis = kInf;
          int who_best = -1;
          VPII best_path;
          REP (fi, SZ(farmers)) {
            Farmer& f = farmers[fi];
            auto dupa = Bfs(f, 1);
            VVI dises;
            vector<VPII> par;
            tie(dises, par) = dupa;
            if (f.gold < cur_threshold) { continue; }
            if (dises[kBaseI][kBaseJ] < best_dis) {
              who_best = fi;
              best_dis = dises[kBaseI][kBaseJ];
              best_path = GetPathBegExcl(par, kBaseI, kBaseJ);
            }
          }
          if (who_best != -1) {
            wanted[kBaseI][kBaseJ] = 1;
            MoveFarmer(farmers[who_best], best_path[0].st, best_path[0].nd);
            who_moved[who_best] = 1;
            //debug(who_best, farmers[who_best].r, farmers[who_best].c);
          }
        }
        REP (ti, SZ(tanks)) {
          VVI dises;
          Tank& t = tanks[ti];
          if (board[t.r][t.c] < 0) { continue; }
          vector<VPII> par;
          tie(dises, par) = Bfs(t, 0);
          int best_r, best_c;
          LD best_prof = 0;
          REP (r, n) {
            REP (c, n) {
              if (r == t.r && c == t.c) { continue; }
              LD prof = ProfitTank(r, c, dises[r][c]);
              if (prof > best_prof) {
                best_r = r;
                best_c = c;
                best_prof = prof;
              }
            }
          }
          if (best_prof) {
            VPII path = GetPathBegExcl(par, best_r, best_c);
            wanted[best_r][best_c] = 1;
//               for (auto p : path) {
//                 wanted[p.st][p.nd] = 1;
//               }
            MoveTank(t, path[0].st, path[0].nd);
            //who_moved[who_best] = 1;
          } else {
            if (rand() % 10 == 0) {
              vector<int> dirs(4);
              iota(ALL(dirs), 0);
              random_shuffle(ALL(dirs));
              //random_shuffle(
              REP (dir_ind, kDirs) {
                int dir = dirs[dir_ind];
                int nr = t.r + dr[dir];
                int nc = t.c + dc[dir];
                if (Valid(nr, nc) && taken[nr][nc] == kFree && board[nr][nc] == 0 && nr != 0) {
                  MoveTank(t, nr, nc);
                  break;
                }
              }
            }
          }
        }
        REP (fi, SZ(farmers)) {
          if (who_moved[fi]) { continue; }
          VVI dises;
          Farmer& f = farmers[fi];
          if (board[f.r][f.c]) { continue; }
          vector<VPII> par;
          tie(dises, par) = Bfs(f, 1);
          int best_r, best_c;
          LD best_prof = 0;
          REP (r, n) {
            REP (c, n) {
              if (r == f.r && c == f.c) { continue; }
              LD prof = ProfitFarmer(r, c, dises[r][c]);
              if (prof > best_prof) {
                best_r = r;
                best_c = c;
                best_prof = prof;
              }
            }
          }
          if (best_prof) {
            //debug(fi, f.r, f.c, best_r, best_c);
            VPII path = GetPathBegExcl(par, best_r, best_c);
            wanted[best_r][best_c] = 1;
//               for (auto p : path) {
//                 wanted[p.st][p.nd] = 1;
//               }
            MoveFarmer(f, path[0].st, path[0].nd);
            //who_moved[who_best] = 1;
          } else {
            if (rand() % 10 == 0) {
              vector<int> dirs(4);
              iota(ALL(dirs), 0);
              random_shuffle(ALL(dirs));
              //random_shuffle(
              REP (dir_ind, kDirs) {
                int dir = dirs[dir_ind];
                int nr = f.r + dr[dir];
                int nc = f.c + dc[dir];
                if (Valid(nr, nc) && taken[nr][nc] == kFree && board[nr][nc] == 0 && nr != 0) {
                  MoveFarmer(f, nr, nc);
                  break;
                }
              }
            }
          }
        }
      }
      EndTurn();
      if (IsBoardClear() && AreFarmersEmpty()) {
        cout<<"===\n";
        completed_turns++;
        sum_completed_turns += completed_turns;
        debug(SZ(farmers), bfses, completed_turns, completed_turns - fir_clear_board);
        //debug(recruiting_times);
        return;
      }
    }
  }
};


int32_t main() {

  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(10);
  cerr << fixed << setprecision(10);
  cin.tie(0);
  //double beg_clock = 1.0 * clock() / CLOCKS_PER_SEC;
  
//   Farmer f(2, 3, 5);
//   Farmer heh({21, 37, -2});
//   debug(f.r, heh.r);
  
  int T, k;
  cin>>T>>k;;
  RE (i, T) {
    Sol sol;
    sol.Test();
  }
  debug(sum_completed_turns, 1. * sum_completed_turns / T, k);
  if (sum_completed_turns <= k * T) {
    cerr<<"UDALO SIE!!"<<endl;
  } else {
    cerr<<"Nie udalo sie :<"<<endl;
  }
  return 0;
}