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
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
#include <cstdio>
#include <set>
#include <iostream>
#include <assert.h>
#include <algorithm>
#include <string>
#include <vector>
#include <string.h>
#include <stdio.h>
#include <unordered_map>

// TODO: Maybe comment this out before submit.
//#define DBG_CHECKS
//#define DBG_FULL
#define DEB 0
// #define DBG_CHECKS
#define USE_SUBPROBLEM_CACHE 1
#define USE_NS_CACHE 0

#if DEB == 1
#include <sys/types.h>
#include <unistd.h>
void sleepSec(float t) {
	usleep(t * 1E6);
}
#endif


// TODO: UWAGA NA TO PRZED WYSLANIEM
//#include "message.h"
//#include "palindromy.h"

#define deb(x) cout << #x << " = " << x << endl;

using namespace std;

// Dwa z najczesciej uzywanych typow o dlugich nazwach
// - ich skrocenie jest bardzo istotne
typedef vector<int> VI;
typedef long long LL;

// W programach bardzo rzadko mozna znalezc w pelni zapisana instrukcje petli.
// Zamiast niej wykorzystywane sa trzy nastepujace makra:
// FOR - petla zwiekszajaca zmienna x od b do e wlacznie
#define FOR(x, b, e) for(int x = b; x <= (e); ++x)
// FORD - petla zmniejszajaca zmienna x od b do e wlacznie
#define FORD(x, b, e) for(int x = b; x >= (e); --x)
// REP - petla zwiekszajaca zmienna x od 0 do n. Jest ona bardzo czesto
// wykorzystywana do konstruowania i przegladania struktur danych
#define REP(x, n) for(int x = 0; x < (n); ++x)
// Makro VAR(v,n) deklaruje nowa zmienna o nazwie v oraz typie i wartosci
// zmiennej n. Jest ono czesto wykorzystywane podczas operowania na
// iteratorach struktur danych z biblioteki STL, ktorych nazwy typow sa bardzo dlugie
#define VAR(v, n) __typeof(n) v = (n)
// ALL(c) reprezentuje pare iteratorow wskazujacych odpowiednio na pierwszy
// i za ostatni element w strukturach danych STL. Makro to jest bardzo
// przydatne chociazby w przypadku korzystania z funkcji sort, ktora jako
// parametry przyjmuje pare iteratorow reprezentujacych przedzial
// elementow do posortowania
#define ALL(c) (c).begin(), (c).end()
// Ponizsze makro sluzy do wyznaczania rozmiaru struktur danych STL.
// Uzywa sie go w programach, zamiast pisac po prostu x.size() ze wzgledu na to,
// iz wyrazenie x.size() jest typu unsigned int i w przypadku porownywania
// z typem int w procesie kompilacji generowane jest ostrzezenie
#define SIZE(x) ((int)(x).size())
// Bardzo pozyteczne makro sluzace do iterowania po wszystkich elementach
// w strukturach danych STL
#define FOREACH(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)
// Skrot - zamiast pisac push_back podczas wstawiania elementow na koniec
// struktury danych, takiej jak vector, wystarczy napisac PB
#define PB push_back
// Podobnie - zamiast first bedziemy pisali po prostu ST
#define ST first
// a zamiast second - ND
#define ND second

// tl tr br bl
int arrow_chr[4][4] = {
		{3, 0xE2, 0x86, 0x96},
		{3, 0xE2, 0x86, 0x97},
		{3, 0xE2, 0x86, 0x98},
		{3, 0xE2, 0x86, 0x99},
};
int sqr_chr[] = {4,0xF0,0x9F,0x9E,0x8E};
int box_chr[] = {3, 0xE2,0x8C,0xB7};

int SWNEOfs[4][2] = { {0,-1}, {-1,0}, {0,1}, {1, 0}};

string pc8(const int *s) {
	char buf[10];
	REP(i, s[0])
		sprintf(buf+i, "%c", s[i+1]);
	return buf;
}

const char *MAP_LVL0[] =
{
		" - ",
		"| |",
		"   ",
};
const int LVL0_SZ = 3;

const char *MAP_LVLN[] =
{
		" H   H ",
		"HcH HcH",
		" h - h ",
		"|     |",
		" H   H ",
		"hcH Hch",
		" H   H ",
};
const int LVLN_SZ = 7;

struct Pt {
	char x, y;

	Pt(): x(0), y(0) {}
	Pt(char x, char y): x(x), y(y) {}

	Pt operator+(const Pt &s) const { return Pt(x+s.x, y+s.y); }
	Pt operator-(const Pt &s) const { return Pt(x-s.x, y-s.y); }
	Pt operator*(const int &n) const { return Pt(x*n, y*n); }
	bool operator==(const Pt &s) const { return x == s.x && y == s.y; }
	bool operator!=(const Pt &s) const { return !(*this == s); }
	Pt bounce(bool horiz) {
		if (horiz) y = -y; else x = -x;
		return *this;
	}
	LL hash() {
		const LL LPRIME = 1000000007;
		LL h = 37*LPRIME;
		h = h*LPRIME+x;
		h = h*LPRIME+y;
		return h*LPRIME;
	}
};
ostream &operator<<(ostream &o, const Pt &p) {
	return o << "Pt("<<(int)p.x<<", "<<(int)p.y<<")";
}

struct CharHolder {
	int refs;
	vector<vector<char> > m;
	LL _hash;

	LL hash() {
		const LL LPRIME = 43594442599UL;
		if (_hash != -1) return _hash;
		_hash = 0;
		REP(x, SIZE(m)) REP(y, SIZE(m[0]))
			_hash = _hash * LPRIME + m[x][y];
		return _hash*LPRIME;
	}

	CharHolder(): refs(0), _hash(-1) {
	}
};

struct Map {
	CharHolder *chld;

	char w, h; // x \in [0,w-1]; y \in [0,h-1]; (0,0) bottom left on screen
	Map():chld(NULL) {
		defCopy();
	}
	Map(const Map &mp) {
		h = mp.h;
		w = mp.w;
		chld = mp.chld;
		if (chld != NULL)
			chld->refs += 1;
	}
	Map &operator=(const Map &mp) {
		h = mp.h;
		w = mp.w;
		chld = mp.chld;
		if (chld != NULL)
			chld->refs += 1;
		return *this;
	}
	~Map() {
		freeChld();
	}

	void freeChld() {
		if (chld != NULL) {
			chld->refs -= 1;
			if (chld->refs == 0)
				delete chld;
			chld = NULL;
		}
	}

	void defCopy() {
		CharHolder *ch = new CharHolder();
		ch->refs = 1;
		if (chld != NULL) {
			ch->m = chld->m;
			freeChld();
		}
		ch->_hash = -1;
		chld = ch;
	}

	bool inMap(Pt p) const {
		if (p.x < 0 || p.x >= w) return false;
		if (p.y < 0 || p.y >= h) return false;
		return true;
	}
	bool inBorder(Pt p, bool &horizBord) {
		if (p.x == 0 || p.x == w-1) {
			horizBord = false;
			return true;
		}
		if (p.y == 0 || p.y == h-1) {
			horizBord = true;
			return true;
		}
		return false;
	}
	bool inBorder(Pt p) { bool u; return inBorder(p, u); }

	char cell(const Pt &p) const {
		if (DEB && !inMap(p)) {
			if (DEB) cerr << "ERROR: Read cell " << p << " outside map!" << endl;
		}

		return chld->m[p.x][p.y];
	}
	char cell(int x, int y) const { return cell(Pt(x, y)); }
	char &cellW(const Pt &p) {
		if (!inMap(p)) {
			if (DEB) cerr << "ERROR: Read cell " << p << " outside map!" << endl;
		}

		chld->_hash = -1;
		return chld->m[p.x][p.y];
	}
	char &cellW(int x, int y) { return cellW(Pt(x, y)); }
	void resize(char w, char h) {
		this->w=w;
		this->h=h;

		defCopy();
		chld->_hash = -1;
		chld->m.clear(); chld->m.resize(w, vector<char>(h, ' '));
	}

	// TODO probably integrate with higher mechanism
	void loadMap(const char *lines[], int sz) {
		resize(sz+2, sz+2);
		REP(r, sz) {
			REP(c, sz) {
				cellW(c+1, sz-r) = lines[r][c];
			}
		}
		REP(x, w) REP(y, h) {
			Pt p(x, y);
			if (inBorder(p)) cellW(p) = '#';
		}
	}

	LL hash() {
		const LL LPRIME = 19168104274513UL;
		LL hsVal = 47*LPRIME;
		hsVal = hsVal*LPRIME+w;
		hsVal = hsVal*LPRIME+h;
		hsVal = hsVal*LPRIME+chld->hash();
		return hsVal*LPRIME;
	}
};

ostream &operator<<(ostream &o, Map &m) {
	o << "Map(w=" << (int)m.w << ", h=" << (int)m.h << "):" << endl;
	FORD(y, m.h-1, 0) {
		FOR(x, 0, m.w-1) {
			Pt cur(x, y);
			o << m.cell(x, y);
		}
		o << endl;
	}
	return o;
}

struct MapTransform {
private:
	Map m;
public:
	vector<Pt> fixPts;
	MapTransform(){}
	MapTransform(Map &m) {
		setMap(m);
	}
	void setMap(Map &m) {
		this->m = m;
		this->m.defCopy();
	}
	Map getMap() {
		Map nm = m;
		nm.defCopy();
		return nm;
	}
	int mapW() { return m.w; }
	int mapH() { return m.h; }
	void cropTo(const vector<Pt> &pts) {
		int minX=1E9, maxX=-1E9;
		int minY=minX, maxY=maxX;
		FOREACH(it, pts) {
			minX = min(minX, (int)it->x);
			minY = min(minY, (int)it->y);
			maxX = max(maxX, (int)it->x);
			maxY = max(maxY, (int)it->y);
		}
		auto &mv = m.chld->m;
		_trimTo(mv, minX, maxX);
		m.w = SIZE(mv);
		REP(x, m.w) {
			_trimTo(mv[x], minY, maxY);
			m.h = SIZE(mv[x]);
		}
		FOREACH(it, fixPts) {
			it->x -= minX;
			it->y -= minY;
		}
	}
	void cropTo(Pt p, Pt q) {
		vector<Pt> v;
		v.PB(p);
		v.PB(q);
		cropTo(v);
	}

	void extendX(int x, int newW) {
		auto &mv = m.chld->m;
		_extendVec(mv, x, newW);
		m.w = SIZE(mv);
		int incr = newW-1;
		FOREACH(it, fixPts)
			if (it->x > x) it->x += incr;
	}

	void extendY(int y, int newW) {
		auto &mv = m.chld->m;
		REP(x, m.w)
			_extendVec(mv[x], y, newW);
		m.h = SIZE(mv[0]);
		int incr = newW-1;
		FOREACH(it, fixPts)
			if (it->y > y) it->y += incr;
	}

	void rotate(int k) {
		REP(i, k) {
			Map mr;
			mr.resize(m.h, m.w);
			REP(x, m.w) REP(y, m.h) {
				Pt bef(x, y), aft(y, m.w-1-x);
				char c = m.cell(bef);
				if (c == '-') c = '|';
				else if (c == '|') c = '-';
				mr.cellW(aft) = c;
			}
			m = mr;
		}
		if (!fixPts.empty() && DEB)
			cerr << "ERROR! fixPts not available for rotate()" << endl;
	}

	void paste(Pt p, Map &ms) {
		REP(x, ms.w) REP(y, ms.h) {
				Pt c(x, y);
				m.cellW(c+p) = ms.cell(c);
		}
	}

	template<typename T>
	void _extendVec(vector<T> &v, int x, int newW){
		vector<T> ncentr(newW-1, v[x]);
		v.insert(v.begin()+x, ALL(ncentr));
	}

	template<typename T>
	void _trimTo(vector<T> &v, int l, int h) {
		v.erase(v.begin()+h+1, v.end());
		v.erase(v.begin(), v.begin()+l);
	}
};

struct HilbertSqr {
	Pt p; // bot.-left cor.
	Pt tr; // top-right cor.
	Pt c; // hil. center
	char rotation; // nr of clockwise turns 0 - hil. entrance on bottom
	bool horizEntry; // entered from top/bot.
};

struct MapState {
	Map m;
	Pt p; // pos of the ball
	Pt v; // vel of the ball
	Pt t; // map target loc
#if USE_NS_CACHE == 1
	bool isHilHit; // TODO  Possibly unneeded
#endif

	void loadState(const char *lines[], int sz) {
		p = Pt(1, 0);
		v = Pt(1, 1);
		t = Pt(0, 1);
		m.loadMap(lines, sz);
	}
	string pickArrow() {
		// tl tr br bl
		if (v == Pt(-1, 1)) return pc8(arrow_chr[0]);
		if (v == Pt(1, 1)) return pc8(arrow_chr[1]);
		if (v == Pt(1, -1)) return pc8(arrow_chr[2]);
		if (v == Pt(-1, -1)) return pc8(arrow_chr[3]);
		assert(false); return "";
	}

	LL hash() {
		const LL LPRIME = 592344878353UL;
		LL h = 31*LPRIME;
		h = h*LPRIME+p.hash();
		h = h*LPRIME+v.hash();
		h = h*LPRIME+t.hash();
		h = h*LPRIME+m.hash();
		return h*LPRIME;
	}
};

ostream &operator<<(ostream &o, MapState &s) {
	FORD(y, s.m.h-1, 0) {
		FOR(x, 0, s.m.w-1) {
			Pt cur(x, y);
			if (cur == s.p) o << s.pickArrow();
			else if(cur == s.t) o << '+';
//			else if(s.m.cell(x, y) == ' ') o << pc8(box_chr);
			else o << s.m.cell(x, y);
		}
		o << endl;
	}

	return o;
}


struct StateResult {
	StateResult():steps(0), dx(0), dy(0) {}
	StateResult(LL st, LL dx, LL dy):steps(st), dx(dx), dy(dy) {}
	LL steps;
	LL dx, dy;
	StateResult operator+(const StateResult &s) const {
		return StateResult(steps+s.steps, dx+s.dx, dy+s.dy);
	}
	StateResult operator+(const Pt &p) const {
		return StateResult(steps+1, dx+p.x, dy+p.y);
	}
};

ostream &operator<<(ostream &o, const StateResult &s) {
	o << "StateResult(" << s.steps << ", " << s.dx << ", " << s.dy << ")";
	return o;
}

struct AnswerGather {
	vector<LL> queries, x, y;
	void check() {
		if(DEB)
		REP(i, SIZE(queries)-1) {
			if (queries[i] > queries[i+1] && DEB)
				cerr << "ERROR: Input contains a decreasing query" << endl;
		}
	}
	bool hasNext() {
		return SIZE(x) < SIZE(queries);
	}

	LL next() {
		return queries[SIZE(x)];
	}

	void answer(LL ax, LL ay) {
		x.PB(ax); y.PB(ay);
	}
};


struct HilbertBall {
	MapTransform hilNLvl;
	MapTransform hil0Lvl;
	std::unordered_map<LL, StateResult> stateCache;
	std::unordered_map<LL, MapState> subprCache;
#if USE_NS_CACHE == 1
	std::unordered_map<LL, MapState> nextStateCache;
#endif
	LL solveCalls, cashHits;

	HilbertBall() {
		hilNLvl = _loadHilLvl(MAP_LVLN, LVLN_SZ);
		hil0Lvl = _loadHilLvl(MAP_LVL0, LVL0_SZ);
		solveCalls = cashHits = 0;
	}

	MapTransform _loadHilLvl(const char *lines[], int sz) {
		MapTransform mt;
		MapState ms;
		ms.loadState(lines, sz);
		mt.setMap(ms.m);
		mt.cropTo(Pt(1,1), Pt(sz, sz));
		return mt;
	}

	bool inHilbert(Map &m, Pt p, HilbertSqr &hs) {
		if (tolower(m.cell(p)) == 'h') {
			hs.c = _findCentr(m, p);
			hs.rotation = _findRot(m, hs.c);
			hs.p = hs.c - Pt(1, 1);
			hs.tr = hs.c + Pt(1, 1);
			hs.horizEntry = (p.x == hs.c.x);
			return true;
		}
		return false;
	}

	bool inHilbert(MapState &s, HilbertSqr &hs) {
		return inHilbert(s.m, s.p, hs);
	}

	char _findRot(Map &m, Pt c) {
		REP(r, 4) {
			Pt ofs(SWNEOfs[r][0], SWNEOfs[r][1]);
			if (m.cell(c+ofs) == 'h')
				return r;
		}
		if (DEB) cerr << "ERROR: _findRot: 'h' not found!" << endl;
		return 0;
	}

	Pt _findCentr(Map &m, Pt p) {
		REP(r, 4) {
			Pt c(SWNEOfs[r][0], SWNEOfs[r][1]);
			c = c+p;
			if(m.cell(c)=='c') {
				return c;
			}
		}
		if (DEB) cerr << "ERROR: _findCentr: Center not found!" << endl;
		return Pt();
	}

	// s - base state - must be inHilbert
	MapState hilSubproblem(MapState &s, bool lvl0Case=false,
			bool useGeneralSubs=false) {

		LL h;
		if(USE_SUBPROBLEM_CACHE) {
			solveCalls += 1;
			const LL LPRIME = 3206828235229UL;
			h = s.hash()*LPRIME + lvl0Case;
			h *= LPRIME;
			auto it = subprCache.find(h);
			if (it != subprCache.end()) {
				cashHits += 1;
				return it->ND;
			}

		}


		HilbertSqr hs;
		if (!inHilbert(s, hs)) {
			if(DEB)
				cerr << "ERROR: hilSubproblem called for not inHilbert" << endl;
		}

		Pt vBeforeEntry = Pt(s.v).bounce(hs.horizEntry);
		Pt nStart = s.p-vBeforeEntry, nTrg = s.v + s.p;

		MapTransform mt(s.m);
		mt.fixPts.PB(nStart); // 0
		mt.fixPts.PB(nTrg); // 1

		if (useGeneralSubs)
			_generalHilbSubst(mt, s.m, lvl0Case);
		else
			_twoCaseHilbSubst(hs, mt, s, nStart, lvl0Case);

		MapState ns;
		ns.m = mt.getMap();
		ns.p = mt.fixPts[0];
		ns.v = vBeforeEntry;
		ns.t = mt.fixPts[1];

		if(USE_SUBPROBLEM_CACHE) {
			subprCache[h] = ns;
		}

		return ns;
	}

	MapState hilSubstitute(MapState &s, bool lvl0Case=false) {
		MapTransform mt(s.m);
		mt.fixPts.PB(s.p); // 0
		mt.fixPts.PB(s.t); // 1

		_generalHilbSubst(mt, s.m, lvl0Case);

		MapState ns;
		ns.m = mt.getMap();
		ns.p = mt.fixPts[0];
		ns.v = s.v;
		ns.t = mt.fixPts[1];
		return ns;
	}

	void _twoCaseHilbSubst(HilbertSqr &hs, MapTransform &mt, MapState &s,
			Pt nStart, bool lvl0Case) {
		mt.fixPts.PB(hs.c); // 2
		mt.fixPts.PB(hs.p); // 3
		mt.fixPts.PB(hs.tr); // 4

		if (s.m.cell(nStart) == '#') {
			// Just one hilbert.
			mt.cropTo(mt.fixPts);
			_insertHilb(mt, 2, 3, hs.rotation, 0, lvl0Case);
		}
		else {
			HilbertSqr hs2;
			Pt othHilbP = s.p + (s.p-hs.c)*2;
			if (!inHilbert(s.m, othHilbP, hs2) && DEB)
				cerr << "ERROR: Ohter hilbert not found!" << endl;
			mt.fixPts.PB(hs2.p); // 5
			mt.fixPts.PB(hs2.tr); // 6
			mt.fixPts.PB(hs2.c); // 7

			mt.cropTo(mt.fixPts);

			_insertHilb(mt, 2, 3, hs.rotation, 0, lvl0Case);
			// If same x, do only y. Do only x otherwise.
			int extOpt = (hs2.c.x == hs.c.x) ? 2 : 1;
			_insertHilb(mt, 7, 5, hs2.rotation, extOpt, lvl0Case);
		}
	}

	// extOpt == 0 - both ways, extOpt == 1 only X, extOpt == 2 only Y
	// extOpt == -1 - no extending
	void _insertHilb(MapTransform &mt, int cFpNr, int pasteFpNr, int rot,
			int extOpt, bool lvl0Case) {
		MapTransform *lvl = (lvl0Case ? &hil0Lvl : &hilNLvl);
		Pt cc;
		if (extOpt >= 0) {
			if (extOpt != 2) {
				cc = mt.fixPts[cFpNr];
				mt.extendX(cc.x, lvl->mapW()-2);
			}
			if (extOpt != 1) {
				cc = mt.fixPts[cFpNr];
				mt.extendY(cc.y, lvl->mapH()-2);
			}
		}

		Pt pp = mt.fixPts[pasteFpNr];

		MapTransform pasteEl = *lvl;
		pasteEl.rotate(rot);
		Map mp = pasteEl.getMap();
		mt.paste(pp, mp);
	}

	void _generalHilbSubst(MapTransform &mt, Map &m, bool lvl0Case) {
		VI xs, ys;
		VI corPos, rot;

		REP(x, m.w) REP(y, m.h) {
			Pt cp(x, y);
			HilbertSqr sprop;
			if (m.cell(cp) == 'h' && inHilbert(m, cp, sprop)) {
				corPos.PB(SIZE(mt.fixPts));
				rot.PB(sprop.rotation);
				mt.fixPts.PB(sprop.p);
				mt.fixPts.PB(sprop.tr);
				xs.PB(sprop.c.x);
				ys.PB(sprop.c.y);
			}
		}

		// Save the border!
		mt.fixPts.PB(Pt(0,0));
		mt.fixPts.PB(Pt(m.w-1, m.h-1));
		mt.cropTo(mt.fixPts);

		sort(ALL(xs)); xs.erase(unique(ALL(xs)), xs.end());
		sort(ALL(ys)); ys.erase(unique(ALL(ys)), ys.end());
		reverse(ALL(xs));
		reverse(ALL(ys));

		MapTransform *lvl = (lvl0Case ? &hil0Lvl : &hilNLvl);
		FOREACH(it, xs) mt.extendX(*it, lvl->mapW()-2);
		FOREACH(it, ys) mt.extendY(*it, lvl->mapH()-2);

		REP(i, SIZE(corPos)) {
			_insertHilb(mt, 0, corPos[i], rot[i], -1, lvl0Case);
		}
	}

	MapState nextState(MapState &s, bool &hilHit) {
#if USE_NS_CACHE == 1
		LL h;
//			cout << "Cache query for " << endl << s << endl;
		h = s.hash();
		auto it = nextStateCache.find(h);
		if (it != nextStateCache.end()) {
			hilHit = it->ND.isHilHit;
//				cout << "CH: " << it->ND << " ih:" << it->ND.isHilHit << " H:" << h << endl;
			return it->ND;
		}
#endif

		MapState ns = s;
		Pt np = s.p + s.v;
		ns.p = np;
		bool horiz;
		if (ns.m.cell(np) == '#' && ns.m.inBorder(np, horiz))
			ns.v.bounce(horiz);
		if(ns.m.cell(np) == '|') ns.v.bounce(false);
		if(ns.m.cell(np) == '-') ns.v.bounce(true);
		//HilbertSqr hs;
		//if ((hilHit = inHilbert(ns, hs)))
		hilHit = (tolower(ns.m.cell(ns.p)) == 'h');
		if (hilHit) {
			Pt horBncP = ns.p+Pt(ns.v).bounce(true);
			if (ns.m.inMap(horBncP) && tolower(ns.m.cell(horBncP)) == 'h')
				ns.v.bounce(false);
			else
				ns.v.bounce(true);
		}

#if USE_NS_CACHE == 1
			ns.isHilHit = hilHit;
//			cout << "PC: " << ns << " ih:" << ns.isHilHit << " H:" << h << endl;
			nextStateCache[h] = ns;
#endif
		return ns;
	}


	StateResult solveState(MapState &s, int hilLvl, bool ldeb=false) {
		StateResult r;

		solveCalls += 1;

		const LL LPRIME = 107814156778397UL;
		LL h = s.hash()*LPRIME + hilLvl;
		auto it = stateCache.find(h);
		if (it != stateCache.end()) {
			cashHits += 1;
			return it->ND;
		}

		if(ldeb) cout << "solveState call (lvl=" << hilLvl << "): " << endl << s << endl;

		MapState cs = s;
		while (cs.p != cs.t) {
			bool hilHit;
			Pt p0 = cs.p;

			cs = nextState(cs, hilHit);
			if(ldeb) cout << "Step: " << endl << cs << endl;

			if (hilHit) {
				MapState substate = hilSubproblem(cs, hilLvl==1);
				if(ldeb) cout << "solveState generated subproblem (lvl="
						<<hilLvl<<"):" << endl << substate << endl;
				StateResult subr = solveState(substate, hilLvl-1);
				r = r + subr;
				cs = nextState(cs, hilHit);
			}
			else
				r = r + (cs.p - p0);

			if(ldeb) cout << "Result after step: " << r << endl;
		}
		if(ldeb) cout << "Final result: " << r << endl;

		stateCache[h] = r;

		return r;
	}

	StateResult resAfterSteps(LL steps, MapState &s, int hilLvl, bool ldeb=false) {
		StateResult r;

		if(ldeb) cout << "resAfterSteps call lvl="<<hilLvl << " steps=" << steps
				<< ": " << endl << s << endl;

		MapState cs = s;
		while (cs.p != cs.t) {
			bool hilHit;
			Pt p0 = cs.p;

			cs = nextState(cs, hilHit);
			if(ldeb) cout << "Step: " << r << endl;

			if (hilHit) {
				MapState substate = hilSubproblem(cs, hilLvl==1);
				if(ldeb) cout << "resAfterSteps generated subproblem (lvl="
						<<hilLvl<<"):" << endl << substate << endl;
				StateResult cumr = r + solveState(substate, hilLvl-1, ldeb);
				if(ldeb) cout << "Subproblem return with cumr=" << cumr << endl;
				if (cumr.steps > steps) {
					if(ldeb) cout << "Will solve subproblem, and then add " << r << endl;
					return resAfterSteps(steps - r.steps, substate,
							hilLvl-1, ldeb) + r;
				}
				else if (cumr.steps == steps) {
					return cumr;
				}
				else {
					r = cumr;
					cs = nextState(cs, hilHit);
				}
			}
			else
				r = r + (cs.p - p0);

			if(ldeb) cout << "Result after step: " << r << endl << cs << endl;

			if (r.steps == steps) {
				return r;
			}
		}

		if (DEB) cerr << "ERROR: We should never get to end of resAfterSteps"
				<< endl;
		return r;
	}

	void posAfterSteps(int lvl, LL steps, LL &x, LL &y, bool ldeb=false) {
		MapState ms;
		if (lvl == 0)
			ms.loadState(MAP_LVL0, LVL0_SZ);
		else
			ms.loadState(MAP_LVLN, LVLN_SZ);

		StateResult r = resAfterSteps(steps, ms, lvl, ldeb);

		if(DEB && r.steps != steps) cerr << "ERROR: bad steps" << endl;

		x = ms.p.x; x += r.dx;
		y = ms.p.y; y += r.dy;
	}

	void batchResAfterSteps(StateResult r, AnswerGather &ag,
			MapState &s, int hilLvl, bool ldeb=false) {

		if(ldeb) cout << "batchResAfterSteps call lvl="<<hilLvl << ": " << endl << s << endl;

		MapState cs = s;
		while (cs.p != cs.t) {
			bool hilHit;
			Pt p0 = cs.p;

			cs = nextState(cs, hilHit);
			if(ldeb) cout << "Step: " << r << endl;

			if (hilHit) {
				MapState substate = hilSubproblem(cs, hilLvl==1);
				if(ldeb) cout << "batchResAfterSteps generated subproblem (lvl="
						<<hilLvl<<"):" << endl << substate << endl;

				StateResult cumr = r + solveState(substate, hilLvl-1, ldeb);
				if(ldeb) cout << "Subproblem return with cumr=" << cumr << endl;

				if (cumr.steps > ag.next()) {
					if(ldeb) cout << "Will solve subproblem " << endl;
					batchResAfterSteps(r, ag, substate, hilLvl-1, ldeb);
				}
				if (!ag.hasNext()) return;


				while (cumr.steps == ag.next()) {
					ag.answer(cumr.dx, cumr.dy);
					if (!ag.hasNext()) return;
				}

				r = cumr;
				cs = nextState(cs, hilHit);
			}
			else
				r = r + (cs.p - p0);

			if(ldeb) cout << "Result after step: " << r << endl << cs << endl;

			while (r.steps == ag.next()) {
				ag.answer(r.dx, r.dy);
				if (!ag.hasNext()) return;
			}
		}
	}

	void batchPosAfterSteps(int lvl, AnswerGather &ag, bool ldeb=false) {
		MapState ms;
		if (lvl == 0)
			ms.loadState(MAP_LVL0, LVL0_SZ);
		else
			ms.loadState(MAP_LVLN, LVLN_SZ);

		batchResAfterSteps(StateResult(), ag, ms, lvl, ldeb);

		REP(i, SIZE(ag.x)) {
			ag.x[i] += ms.p.x;
			ag.y[i] += ms.p.y;
		}
	}

	void printStats() {
		deb(solveCalls);
		double hitPerc = 100;
		hitPerc *= cashHits;
		hitPerc /= solveCalls;
		deb(hitPerc);
		deb(SIZE(stateCache))
		deb(SIZE(subprCache))
	}
};


void playHilbertOnLvl(int lvl, int stepLimit=-1) {
	MapState ms;
	if (lvl > 0)
		ms.loadState(MAP_LVLN, LVLN_SZ);
	else
		ms.loadState(MAP_LVL0, LVL0_SZ);

	HilbertBall hb;
	while(1) {
		lvl--;
		ms = hb.hilSubstitute(ms, lvl==0);
		if (lvl == 0) break;
	}

	cout << ms << endl;

	int steps = 0;
	while (true) {
		cin.get();
		bool hilHit;
		ms = hb.nextState(ms, hilHit);
		steps += 1;
		cout << "After " << steps << " steps p=" << ms.p << endl;
		cout << ms << endl;
		if (stepLimit == steps)
			return;
		if (ms.p == Pt(0,1)) {
			cout << "Ended after " << steps << " steps" << endl;
			break;
		}
	}
}

void playHilbertShowSubprob() {
	MapState ms; ms.loadState(MAP_LVLN, LVLN_SZ);

	cout << ms << endl;
	HilbertBall hb;

	REP(i, 50) {
		cin.get();
		bool hilHit;
		cout << "This is the next step:" << endl;
		ms = hb.nextState(ms, hilHit);
		cout << ms << endl;
		if (hilHit) {
			cin.get();
			cout << "Hilbert was hit. This is the subproblem:" << endl;
			MapState sms = hb.hilSubproblem(ms, true, true);
			cout << sms << endl;

			while(sms.t != sms.p) {
				cin.get();
				bool hit;
				sms = hb.nextState(sms, hit);
				cout << sms << endl<<endl;
			}
			cout << "Subproblem solved." << endl;
		}
	}

}

int main(int argc, char *argv[]) {
#define deb(x) cout << #x << " = " << x << endl;
	if (argc == 2 && strcmp(argv[1], "debug") == 0 ) {
		//        printf("== [RUNNING IN DEBUG MODE]==\n\n");
		char test_file_path[] = "/home/horban/workspace/Zadanka/in.txt";
		freopen(test_file_path, "r", stdin);
	}

    // TODO: UWAGA NA TO PRZED WYSLANIEM
	std::ios_base::sync_with_stdio(0);

	HilbertBall hb;

	int n, z;
	cin >> n >> z;
	AnswerGather ag;
	REP(tnr, z) {
		LL steps; cin >> steps;
		ag.queries.PB(steps);
	}
	ag.check();
	hb.batchPosAfterSteps(n-1, ag, false);

	REP(tnr, z) {
		cout << ag.x[tnr] << ' ' << ag.y[tnr] << endl;
	}

	if (DEB) hb.printStats();

    return 0;
}