There always is something to choose from! And now, instead of "Noughts and Crosses", Inna choose a very unusual upgrade of this game. The rules of the game are given below:There is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: "X" or "O". Then the player chooses two positive integers a and b (a·b = 12), after that he makes a table of size a × b from the cards he put on the table as follows: the first b cards form the first row of the table, the second b cards form the second row of the table and so on, the last b cards form the last (number a) row of the table. The player wins if some column of the table contain characters "X" on all cards. Otherwise, the player loses.Inna has already put 12 cards on the table in a row. But unfortunately, she doesn't know what numbers a and b to choose. Help her win the game: print to her all the possible ways of numbers a, b that she can choose and win.

The first line of the input contains integer t (1 ≤ t ≤ 100). This value shows the number of sets of test data in the input. Next follows the description of each of the t tests on a separate line. The description of each test is a string consisting of 12 characters, each character is either "X", or "O". The i-th character of the string shows the character that is written on the i-th card from the start.

For each test, print the answer to the test on a single line. The first number in the line must represent the number of distinct ways to choose the pair a, b. Next, print on this line the pairs in the format axb. Print the pairs in the order of increasing first parameter (a). Separate the pairs in the line by whitespaces.

4
OXXXOXOOXOOX
OXOXOXOXOXOX
XXXXXXXXXXXX
OOOOOOOOOOOO

module A;

private {
    import std.stdio: writeln, readln;
    import std.conv: to;
    import std.array: appender, join;
    import std.range: stride, repeat, iota;
    import std.algorithm : all, filter;
    import std.string: format;
}

string[] getAnswer(string cards) {
    auto result = appender!(string[]);
    auto count_cards = cards.length;

    foreach(i; filter!(a => count_cards % a == 0)(iota(1, count_cards+1))) {
        foreach(j; 0..count_cards / i) {
            if(i * j > 12) continue;
            if(all!"a == 'X'"(stride(cards[j..$], count_cards / i))) {
                result.put("%dx%d".format(i, count_cards / i));
                break;
            }
        }
    }

    return result.data();
}

void main() {
    byte count_test = (readln()[0..$-1]).to!byte;

    auto tests = appender!(string[])();
    foreach(i; 0..count_test) {
        tests.put(readln()[0..$-1]);
    }

    foreach(cards ; tests.data()) {
        string[] answer = getAnswer(cards);
        writeln(answer.length, " ", answer.join(" "));
    }
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from $$$a$$$ to make it a good array. Recall that the prefix of the array $$$a=[a_1, a_2, \dots, a_n]$$$ is a subarray consisting several first elements: the prefix of the array $$$a$$$ of length $$$k$$$ is the array $$$[a_1, a_2, \dots, a_k]$$$ ($$$0 \le k \le n$$$).The array $$$b$$$ of length $$$m$$$ is called good, if you can obtain a non-decreasing array $$$c$$$ ($$$c_1 \le c_2 \le \dots \le c_{m}$$$) from it, repeating the following operation $$$m$$$ times (initially, $$$c$$$ is empty):  select either the first or the last element of $$$b$$$, remove it from $$$b$$$, and append it to the end of the array $$$c$$$. For example, if we do $$$4$$$ operations: take $$$b_1$$$, then $$$b_{m}$$$, then $$$b_{m-1}$$$ and at last $$$b_2$$$, then $$$b$$$ becomes $$$[b_3, b_4, \dots, b_{m-3}]$$$ and $$$c =[b_1, b_{m}, b_{m-1}, b_2]$$$.Consider the following example: $$$b = [1, 2, 3, 4, 4, 2, 1]$$$. This array is good because we can obtain non-decreasing array $$$c$$$ from it by the following sequence of operations:  take the first element of $$$b$$$, so $$$b = [2, 3, 4, 4, 2, 1]$$$, $$$c = [1]$$$;  take the last element of $$$b$$$, so $$$b = [2, 3, 4, 4, 2]$$$, $$$c = [1, 1]$$$;  take the last element of $$$b$$$, so $$$b = [2, 3, 4, 4]$$$, $$$c = [1, 1, 2]$$$;  take the first element of $$$b$$$, so $$$b = [3, 4, 4]$$$, $$$c = [1, 1, 2, 2]$$$;  take the first element of $$$b$$$, so $$$b = [4, 4]$$$, $$$c = [1, 1, 2, 2, 3]$$$;  take the last element of $$$b$$$, so $$$b = [4]$$$, $$$c = [1, 1, 2, 2, 3, 4]$$$;  take the only element of $$$b$$$, so $$$b = []$$$, $$$c = [1, 1, 2, 2, 3, 4, 4]$$$ — $$$c$$$ is non-decreasing. Note that the array consisting of one element is good.Print the length of the shortest prefix of $$$a$$$ to delete (erase), to make $$$a$$$ to be a good array. Note that the required length can be $$$0$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer: the length of the shortest prefix of elements you need to erase from $$$a$$$ to make it a good array.

NoteIn the first test case of the example, the array $$$a$$$ is already good, so we don't need to erase any prefix.In the second test case of the example, the initial array $$$a$$$ is not good. Let's erase first $$$4$$$ elements of $$$a$$$, the result is $$$[4, 5, 2]$$$. The resulting array is good. You can prove that if you erase fewer number of first elements, the result will not be good.

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		while (a.length > 1 && a[$ - 2] >= a[$ - 1])
		{
			a.popBack ();
		}
		while (a.length > 1 && a[$ - 2] <= a[$ - 1])
		{
			a.popBack ();
		}
		a.popBack ();
		writeln (a.length);
	}
}


You have array of $$$n$$$ numbers $$$a_{1}, a_{2}, \ldots, a_{n}$$$. Rearrange these numbers to satisfy $$$|a_{1} - a_{2}| \le |a_{2} - a_{3}| \le \ldots \le |a_{n-1} - a_{n}|$$$, where $$$|x|$$$ denotes absolute value of $$$x$$$. It's always possible to find such rearrangement.Note that all numbers in $$$a$$$ are not necessarily different. In other words, some numbers of $$$a$$$ may be same.You have to answer independent $$$t$$$ test cases.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^{4}$$$) — the number of test cases. The first line of each test case contains single integer $$$n$$$ ($$$3 \le n \le 10^{5}$$$) — the length of array $$$a$$$. It is guaranteed that the sum of values of $$$n$$$ over all test cases in the input does not exceed $$$10^{5}$$$. The second line of each test case contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$-10^{9} \le a_{i} \le 10^{9}$$$).

For each test case, print the rearranged version of array $$$a$$$ which satisfies given condition. If there are multiple valid rearrangements, print any of them.

NoteIn the first test case, after given rearrangement, $$$|a_{1} - a_{2}| = 0 \le |a_{2} - a_{3}| = 1 \le |a_{3} - a_{4}| = 2 \le |a_{4} - a_{5}| = 2 \le |a_{5} - a_{6}| = 10$$$. There are other possible answers like "5 4 5 6 -2 8".In the second test case, after given rearrangement, $$$|a_{1} - a_{2}| = 1 \le |a_{2} - a_{3}| = 2 \le |a_{3} - a_{4}| = 4$$$. There are other possible answers like "2 4 8 1".

import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric;

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto N = readln.chomp.to!int;
        auto as = readln.split.to!(int[]);
        sort(as);
        int[] bs;
        int i = (as.length.to!int-1)/2, j = (as.length.to!int-1)/2+1;
        for (;;) {
            if (i < 0) break;
            bs ~= as[i];
            if (j >= N) break;
            bs ~= as[j];
            --i;
            ++j;
        }
        writeln(bs.to!(string[]).join(" "));
    }
}

//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;

final class InputReader {
  private:
  ubyte[] p, buffer;
  bool eof;
  bool rawRead () {
    if (eof) {
      return false;
    }
    p = stdin.rawRead (buffer);
    if (p.empty) {
      eof = true;
      return false;
    }
    return true;
  }
  ubyte nextByte(bool check) () {
    static if (check) {
      if (p.empty) {
        if (!rawRead ()) {
          return 0;
        }
      }
    }
    auto r = p.front;
    p.popFront ();
    return r;
  }
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
  }
  bool seekByte (in ubyte lo) {
    while (true) {
      p = p.find! (c => c >= lo);
      if (!p.empty) {
        return false;
      }
      if (!rawRead ()) {
        return true;
      }
    }
  }
  template next(T) if (isSigned!T) {
    T next ()  {
      if (seekByte (45)) {
        return 0;
      }
      T res;
      ubyte b = nextByte!false ();
      if (b == 45) {
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    T next () {
      if (seekByte (48)) {
        return 0;
      }
      T res = nextByte!false () - 48;
      while (true) {
        ubyte b = nextByte!true ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  T[] nextA(T) (in int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    const n = r.next!uint;
    auto a = r.nextA!int(n);
    sort(a);
    auto b = new int[n];
    int i = (n - 1) / 2, j = i + 1;
    b[0] = a[i];
    foreach (k; 1 .. n) {
      debug stderr.writefln ("[%d, %d)", i, j);
      if ((k & 1)) {
        b[k] = a[j++];
      } else {
        b[k] = a[--i];
      }
    }
    writefln!("%(%s %)")(b);
  }
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto t = RD!int;
	auto ans = new long[][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		a.sort();
		auto pos = n / 2;
		ans[ti] ~= a[pos];
		int l = pos-1;
		int r = pos+1;
		while (true)
		{
			if (l < 0) break;
			ans[ti] ~= a[l];
			if (r == n) break;
			ans[ti] ~= a[r];
			--l; ++r;
		}
	}

	foreach (e; ans)
		e.map!(to!string).join(" ").writeln;
	stdout.flush;
	debug readln;
}


There are $$$n$$$ people participating in some contest, they start participating in $$$x$$$ minutes intervals. That means the first participant starts at time $$$0$$$, the second participant starts at time $$$x$$$, the third — at time $$$2 \cdot x$$$, and so on.Duration of contest is $$$t$$$ minutes for each participant, so the first participant finishes the contest at time $$$t$$$, the second — at time $$$t + x$$$, and so on. When a participant finishes the contest, their dissatisfaction equals to the number of participants that started the contest (or starting it now), but haven't yet finished it.Determine the sum of dissatisfaction of all participants.

The first line contains a single integer $$$k$$$ ($$$1 \le k \le 1000$$$) — the number of test cases. Each of the next $$$k$$$ lines contains three integers $$$n$$$, $$$x$$$, $$$t$$$ ($$$1 \le n, x, t \le 2 \cdot 10^9$$$) — the number of participants, the start interval and the contest duration.

Print $$$k$$$ lines, in the $$$i$$$-th line print the total dissatisfaction of participants in the $$$i$$$-th test case.

NoteIn the first example the first participant starts at $$$0$$$ and finishes at time $$$5$$$. By that time the second and the third participants start, so the dissatisfaction of the first participant is $$$2$$$. The second participant starts at time $$$2$$$ and finishes at time $$$7$$$. By that time the third the fourth participants start, so the dissatisfaction of the second participant is $$$2$$$. The third participant starts at $$$4$$$ and finishes at $$$9$$$. By that time the fourth participant starts, so the dissatisfaction of the third participant is $$$1$$$.The fourth participant starts at $$$6$$$ and finishes at $$$11$$$. By time $$$11$$$ everyone finishes the contest, so the dissatisfaction of the fourth participant is $$$0$$$.In the second example the first participant starts at $$$0$$$ and finishes at time $$$2$$$. By that time the second participants starts, and the third starts at exactly time $$$2$$$. So the dissatisfaction of the first participant is $$$2$$$. The second participant starts at time $$$1$$$ and finishes at time $$$3$$$. At that time the third participant is solving the contest.

// Vicfred
// https://codeforces.com/contest/1539/problem/A
// math
import std.algorithm;
import std.stdio;

void main() {
    int k;
    readf("%s\n", &k);

while(k--) {
    long n, x, t;
    readf("%s %s %s\n", &n, &x, &t);
    long ans = t/x*max(0, n-t/x) + min(n - 1, t/x - 1)*min(n, t/x)/2;
    ans.writeln;
}
}

import std.stdio, std.algorithm, std.conv, std.string, std.array, std.random;

void main()
{
  int k;
  readf!" %d "(k);
  while (k--) {
    long n, x, t;
    readf!" %d %d %d "(n, x, t);
    long tmp = t / x;
    long result = 0;

    if (n >= tmp + 1) {
      result += tmp * (n - tmp - 1);
      result += (tmp + 1) * (tmp) / 2;
    } else {
      result = n * (n - 1) / 2;
    }
    writeln(result);
  }
}

// Vicfred
// https://codeforces.com/contest/1539/problem/A
//
import std.stdio;

void main() {
    int k;
    readf("%s\n", &k);

while(k--) {
    long n, x, t;
    readf("%s %s %s\n", &n, &x, &t);
    long ans = t/x*(n-t/x) + (t/x - 1)*(t/x)/2;
    ans.writeln;
}
}


During the research on properties of the greatest common divisor (GCD) of a set of numbers, Ildar, a famous mathematician, introduced a brand new concept of the weakened common divisor (WCD) of a list of pairs of integers.For a given list of pairs of integers $$$(a_1, b_1)$$$, $$$(a_2, b_2)$$$, ..., $$$(a_n, b_n)$$$ their WCD is arbitrary integer greater than $$$1$$$, such that it divides at least one element in each pair. WCD may not exist for some lists.For example, if the list looks like $$$[(12, 15), (25, 18), (10, 24)]$$$, then their WCD can be equal to $$$2$$$, $$$3$$$, $$$5$$$ or $$$6$$$ (each of these numbers is strictly greater than $$$1$$$ and divides at least one number in each pair).You're currently pursuing your PhD degree under Ildar's mentorship, and that's why this problem was delegated to you. Your task is to calculate WCD efficiently.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 150\,000$$$) — the number of pairs. Each of the next $$$n$$$ lines contains two integer values $$$a_i$$$, $$$b_i$$$ ($$$2 \le a_i, b_i \le 2 \cdot 10^9$$$).

Print a single integer — the WCD of the set of pairs.  If there are multiple possible answers, output any; if there is no answer, print $$$-1$$$.

NoteIn the first example the answer is $$$6$$$ since it divides $$$18$$$ from the first pair, $$$24$$$ from the second and $$$12$$$ from the third ones. Note that other valid answers will also be accepted.In the second example there are no integers greater than $$$1$$$ satisfying the conditions.In the third example one of the possible answers is $$$5$$$. Note that, for example, $$$15$$$ is also allowed, but it's not necessary to maximize the output.

import std.algorithm;
import std.container;
import std.conv;
import std.range;
import std.stdio;
import std.string;
import std.format;

long gcd(long a, long b) {
  if (b == 0) return a;
  else return gcd(b, a%b);
}

int n;

void main() {
  string s = readln.strip;
  n = parse!int(s);

  long[] a,b;
  a.length = n;
  b.length = n;

  long x = 0;
  foreach (i; 0 .. n) {
    readln.strip.formattedRead(" %s %s", a[i], b[i]);
    x = gcd(a[i]*b[i],x);
  }

  foreach(i; 0 .. n) {
    long y = gcd(x,a[i]);
    if (y != 1) {
      x = y;
    } else {
      x = gcd(x,b[i]);
    }
  }

  if (x == 1)
    writeln(-1);
  else
    writeln(x);
}

import core.bitop;
import std.algorithm;
import std.array;
import std.bitmanip;
import std.container;
import std.conv;
import std.functional;
import std.math;
import std.numeric;
import std.range;
import std.stdio;
import std.string;
import std.typecons;
import std.range.interfaces;

void main()
{
    int n;
    readf("%s", &n);
    readln;

    int[] calcFor2Elms(int a, int b) {
        int[] calc(int x) {
            int[] ans;
            auto sq = sqrt(x.to!real).floor();
            auto v = x, k = 2;
            while (v > 1) {
                if (v % k == 0) {
                    ans ~= k;
                    while (v % k == 0) v /= k;
                }
                ++k;
                if (k > sq) break;
            }
            if (v > 1) ans ~= v;
            return ans;
        }
        return multiwayUnion([calc(a), calc(b)]).array;
    }

    int a, b;
    readf("%s %s", &a, &b);
    readln;
    auto elms = calcFor2Elms(a, b);

    debug { elms.writeln; }

    foreach (_; 1 .. n) {
        int x, y;
        readf("%s %s", &x, &y);
        readln;

        int[] cur;
        foreach (e; elms) {
            if (x % e == 0 || y % e == 0) cur ~= e;
        }

        elms = cur;

        debug { elms.writeln; }
    }

    writeln(elms.empty() ? -1 : elms.front);
}

import core.bitop;
import std.algorithm;
import std.array;
import std.bitmanip;
import std.container;
import std.conv;
import std.functional;
import std.math;
import std.numeric;
import std.range;
import std.stdio;
import std.string;
import std.typecons;
import std.range.interfaces;

void main()
{
    int n;
    readf("%s", &n);
    readln;

    int[] calcFor2Elms(int a, int b) {
        int[] calc(int x) {
            int[] ans;
            auto sq = sqrt(x.to!real).floor();
            auto v = x, k = 2;
            while (v > 1 && k <= sq) {
                if (v % k == 0) {
                    ans ~= k;
                    while (v % k == 0) v /= k;
                }
                ++k;
            }
            if (v > 1) ans ~= v;
            return ans;
        }
        return multiwayUnion([calc(a), calc(b)]).array;
    }

    int a, b;
    readf("%s %s", &a, &b);
    readln;
    auto elms = calcFor2Elms(a, b);

    debug { elms.writeln; }

    foreach (_; 1 .. n) {
        int x, y;
        readf("%s %s", &x, &y);
        readln;

        int[] cur;
        foreach (e; elms) {
            if (x % e == 0 || y % e == 0) cur ~= e;
        }

        elms = cur;

        debug { elms.writeln; }
    }

    writeln(elms.empty() ? -1 : elms.front);
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

bool isPrime (int v)
{
	if (v < 2)
	{
		return false;
	}
	for (int d = 2; d * d <= v; d++)
	{
		if (v % d == 0)
		{
			return false;
		}
	}
	return true;
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [n];
		auto b = new int [n];
		foreach (i; 0..n)
		{
			readf (" %s %s", &a[i], &b[i]);
		}

		bool [int] cand;
		for (int d = 1; d * d <= a[0]; d += 1)
		{
			if (a[0] % d == 0)
			{
				cand[d] = true;
				cand[a[0] / d] = true;
			}
		}
		for (int d = 1; d * d <= b[0]; d += 1)
		{
			if (b[0] % d == 0)
			{
				cand[d] = true;
				cand[b[0] / d] = true;
			}
		}

		int [] divs;
		foreach (k, v; cand)
		{
			if (isPrime (k))
			{
				divs ~= k;
			}
		}

		int res = -1;
		foreach (d; divs)
		{
			bool ok = true;
			foreach (i; 0..n)
			{
				if (a[i] % d != 0 && b[i] % d != 0)
				{
					ok = false;
				}
			}
			if (ok)
			{
				res = d;
				break;
			}
		}

		writeln (res);
	}
}

import std.stdio, std.string, std.conv, std.algorithm;

void main(){

  int n; rd(n);
  long a, b; rd(a, b);
  long[] cand;
  for(int i=2; i*i<=a; i++){
    if(a%i==0){
      cand~=i;
      while(a%i==0) a/=i;
    }
  }
  if(a>1) cand~=a;
  for(int i=2; i*i<=b; i++){
    if(b%i==0){
      cand~=i;
      while(b%i==0) b/=i;
    }
  }
  if(b>1) cand~=b;
  foreach(i; 0..(n-1)){
    long s, t; rd(s, t);
    long[] nex;
    foreach(x; cand){
      if(s%x==0 || t%x==0) nex~=x;
    }
    cand.swap(nex);
  }

  if(cand.length>0){
    writeln(cand[0]);
  }else{
    writeln(-1);
  }
}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.numeric, std.regex, std.typecons;
import core.bitop;

class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; }
int readInt() { return readToken.to!int; }
long readLong() { return readToken.to!long; }
real readReal() { return readToken.to!real; }

bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } }
bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } }

int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; }
int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); }
int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); }

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto A = new long[N];
      auto B = new long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong();
        B[i] = readLong();
      }

      long g = 0;
      foreach (i; 0 .. N) {
        const l = A[i] / gcd(A[i], B[i]) * B[i];
        g = gcd(g, l);
      }
      if (g == 1) {
        writeln(-1);
      } else {
        long ans;
        foreach (a; [A[0], B[0]]) {
          const m = gcd(g, a);
          for (long p = 2; p * p <= m; ++p) {
            if (m % p == 0) {
              ans = p;
              goto found;
            }
          }
          if (m > 1) {
            ans = m;
            goto found;
          }
        }
        assert(false);
       found:
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

import std.stdio, std.string, std.conv, std.algorithm;

void main(){

  int n; rd(n);
  long a, b; rd(a, b);
  long[] cand;
  for(int i=2; i*i<=a; i++){
    if(a%i==0){
      cand~=i;
      while(a%i) a/=i;
    }
  }
  if(a>1) cand~=a;
  for(int i=2; i*i<=b; i++){
    if(b%i==0){
      cand~=i;
      while(b%i) b/=i;
    }
  }
  if(b>1) cand~=b;
  foreach(i; 0..(n-1)){
    long s, t; rd(s, t);
    long[] nex;
    foreach(x; cand){
      if(s%x==0 || t%x==0) nex~=x;
    }
    cand.swap(nex);
  }

  if(cand.length>0){
    writeln(cand[0]);
  }else{
    writeln(-1);
  }
}

void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.bitmanip, std.complex, std.container, std.math, std.numeric, std.regex, std.typecons;
import core.bitop;

class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { if (stdin.eof) { throw new EOFException; } tokens = readln.split; } auto token = tokens.front; tokens.popFront; return token; }
int readInt() { return readToken.to!int; }
long readLong() { return readToken.to!long; }
real readReal() { return readToken.to!real; }

bool chmin(T)(ref T t, in T f) { if (t > f) { t = f; return true; } else { return false; } }
bool chmax(T)(ref T t, in T f) { if (t < f) { t = f; return true; } else { return false; } }

int binarySearch(alias pred, T)(in T[] as) { int lo = -1, hi = cast(int)(as.length); for (; lo + 1 < hi; ) { const mid = (lo + hi) >> 1; (unaryFun!pred(as[mid]) ? hi : lo) = mid; } return hi; }
int lowerBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a >= val)); }
int upperBound(T)(in T[] as, T val) { return as.binarySearch!(a => (a > val)); }

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto A = new long[N];
      auto B = new long[N];
      foreach (i; 0 .. N) {
        A[i] = readLong();
        B[i] = readLong();
      }

      long g = 0;
      foreach (i; 0 .. N) {
        const l = A[i] / gcd(A[i], B[i]) * B[i];
        g = gcd(g, l);
      }
      writeln((g == 1) ? -1 : g);
    }
  } catch (EOFException e) {
  }
}


Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences of days 0, 010, 01010 are zebras, while sequences 1, 0110, 0101 are not.Oleg tells you the story of days he lived in chronological order in form of string consisting of 0 and 1. Now you are interested if it is possible to divide Oleg's life history into several subsequences, each of which is a zebra, and the way it can be done. Each day must belong to exactly one of the subsequences. For each of the subsequences, days forming it must be ordered chronologically. Note that subsequence does not have to be a group of consecutive days.

In the only line of input data there is a non-empty string s consisting of characters 0 and 1, which describes the history of Oleg's life. Its length (denoted as |s|) does not exceed 200 000 characters.

If there is a way to divide history into zebra subsequences, in the first line of output you should print an integer k (1 ≤ k ≤ |s|), the resulting number of subsequences. In the i-th of following k lines first print the integer li (1 ≤ li ≤ |s|), which is the length of the i-th subsequence, and then li indices of days forming the subsequence. Indices must follow in ascending order. Days are numbered starting from 1. Each index from 1 to n must belong to exactly one subsequence. If there is no way to divide day history into zebra subsequences, print -1. Subsequences may be printed in any order. If there are several solutions, you may print any of them. You do not have to minimize nor maximize the value of k.

import
		std.math,
		std.conv,
		std.file,
		std.range,
		std.array,
		std.stdio,
		std.string,
		std.bitmanip,
		std.algorithm;

void main()
{
	uint[][200_000] res;

	uint p, cnt;

	foreach(i, c; readln.strip)
	{
		if(c == '1')
		{
			if(p--)
			{
				res[p] ~= i + 1;
			}
			else
			{
				break;
			}
		}
		else
		{
			res[++p - 1] ~= i + 1;

			if(cnt < p)
			{
				cnt = p;
			}
		}
	}

	if(p != cnt)
	{
		writeln(-1);
	}
	else
	{
		writeln(cnt);

		foreach(r; res[0..cnt])
		{
			writefln(`%u %(%u %)`, r.length, r);
		}
	}
}

import
		std.math,
		std.conv,
		std.file,
		std.range,
		std.array,
		std.stdio,
		std.string,
		std.bitmanip,
		std.algorithm;

void main()
{
	auto arr = readln.strip.map!(a => a == '1').enumerate.array;

	uint[][] res;

	loop: while(true)
	{
		uint[] cur;

		while(arr.length)
		{
			auto u = cur.length & 1;

			if(arr.front.value != u)
			{
				if(!u)
				{
					cur = null;
				}

				break;
			}

			cur ~= arr.front.index + 1;
			arr.popFront;
		}

		if(cur.length)
		{
			res ~= cur;
		}
		else
		{
			break;
		}
	}

	if(!arr.length)
	{
		writeln(res.length);

		foreach(s; res)
		{
			writefln(`%u %(%u %)`, s.length, s);
		}
	}
	else
	{
		writeln(-1);
	}
}

import
		std.math,
		std.conv,
		std.file,
		std.range,
		std.array,
		std.stdio,
		std.string,
		std.bitmanip,
		std.algorithm;

void main()
{
	auto arr = readln.strip.map!(a => a == '1').enumerate.array;

	uint[][] res;

	loop: while(true)
	{
		uint[] cur;

		while(arr.length)
		{
			if(arr.front.value != (cur.length & 1))
			{
				break;
			}

			cur ~= arr.front.index + 1;
			arr.popFront;
		}

		if(cur.length)
		{
			if(!(cur.length & 1))
			{
				res = null;
				break;
			}
			else
			{
				res ~= cur;
			}
		}
		else
		{
			break;
		}
	}

	if(!arr.length && res.length)
	{
		writeln(res.length);

		foreach(s; res)
		{
			writefln(`%u %(%u %)`, s.length, s);
		}
	}
	else
	{
		writeln(-1);
	}
}

import
		std.math,
		std.conv,
		std.file,
		std.array,
		std.stdio,
		std.string,
		std.bitmanip,
		std.algorithm;

void main()
{
	auto arr = readln.strip;
	auto mark = new bool[arr.length];

	uint[][] res;

	loop: while(true)
	{
		uint[] cur;

		foreach(i, c; arr)
		{
			if(mark[i] || c != (cur.length & 1 ? '1' : '0')) continue;

			cur ~= i + 1;
			mark[i] = true;
		}

		if(cur.length)
		{
			if(!(cur.length & 1))
			{
				res = null;
			}
			else
			{
				res ~= cur;
			}
		}
		else
		{
			break;
		}
	}

	if(mark.all && res.length)
	{
		writeln(res.length);

		foreach(s; res)
		{
			writefln(`%u %(%u %)`, s.length, s);
		}
	}
	else
	{
		writeln(-1);
	}
}

import
		std.math,
		std.conv,
		std.file,
		std.array,
		std.stdio,
		std.string,
		std.bitmanip,
		std.algorithm;

void main()
{
	auto arr = readln.strip;
	auto mark = new bool[arr.length];

	uint[][] res;

	loop: while(true)
	{
		uint[] cur;

		foreach(i, c; arr)
		{
			if(mark[i] || c != (cur.length & 1 ? '1' : '0')) continue;

			cur ~= i + 1;
			mark[i] = true;
		}

		if(cur.length)
		{
			res ~= cur;
		}
		else
		{
			break;
		}
	}

	if(mark.all)
	{
		writeln(res.length);

		foreach(s; res)
		{
			writefln(`%u %(%u %)`, s.length, s);
		}
	}
	else
	{
		writeln(-1);
	}
}

import
		std.math,
		std.conv,
		std.file,
		std.range,
		std.array,
		std.stdio,
		std.string,
		std.bitmanip,
		std.algorithm;

void main()
{
	uint[][200_000] res;

	uint p, cnt;

	foreach(i, c; readln.strip)
	{
		if(c == '1')
		{
			if(p)
			{
				res[p--] ~= i + 1;
			}
			else
			{
				writeln(-1);
				break;
			}
		}
		else
		{
			res[p++] ~= i + 1;

			if(cnt < p)
			{
				cnt = p;
			}
		}
	}

	if(p != cnt)
	{
		writeln(-1);
	}
	else
	{
		writeln(cnt);

		foreach(r; res[0..cnt])
		{
			writefln(`%u %(%u %)`, r.length, r);
		}
	}
}

import
		std.math,
		std.conv,
		std.file,
		std.range,
		std.array,
		std.stdio,
		std.string,
		std.bitmanip,
		std.algorithm;

void main()
{
	uint[][200_000] res;

	uint p, cnt;

	foreach(i, c; readln.strip)
	{
		if(c == '1')
		{
			if(p)
			{
				res[p--] ~= i + 1;
			}
			else
			{
				writeln(-1);
				break;
			}
		}
		else if(p == cnt)
		{
			res[p = ++cnt] ~= i + 1;
		}
		else
		{
			res[p++] ~= i + 1;
		}
	}

	if(p != cnt)
	{
		writeln(-1);
	}
	else
	{
		writeln(cnt);

		foreach(r; res[0..cnt])
		{
			writefln(`%u %(%u %)`, r.length, r);
		}
	}
}

import
		std.math,
		std.conv,
		std.file,
		std.range,
		std.array,
		std.stdio,
		std.string,
		std.bitmanip,
		std.algorithm;

void main()
{
	uint[][200_000] res;

	uint p, cnt;

	foreach(i, c; readln.strip)
	{
		if(c == '1')
		{
			if(p)
			{
				res[p-- - 1] ~= i + 1;
			}
			else
			{
				writeln(-1);
				break;
			}
		}
		else
		{
			res[++p - 1] ~= i + 1;

			if(cnt < p)
			{
				cnt = p;
			}
		}
	}

	if(p != cnt)
	{
		writeln(-1);
	}
	else
	{
		writeln(cnt);

		foreach(r; res[0..cnt])
		{
			writefln(`%u %(%u %)`, r.length, r);
		}
	}
}

import
		std.math,
		std.conv,
		std.file,
		std.range,
		std.array,
		std.stdio,
		std.string,
		std.bitmanip,
		std.algorithm;

void main()
{
	auto arr = readln.strip.map!(a => a == '1').enumerate.array;

	uint[][] res;

	loop: while(true)
	{
		uint[] cur;
		uint n;

		while(n < arr.length)
		{
			if(arr[n].value != (cur.length & 1))
			{
				n++;
				continue;
			}

			cur ~= arr[n].index + 1;

			if(n) { arr = arr.remove(n); n--; }
			else arr.popFront;
		}

		if(cur.length)
		{
			if(!(cur.length & 1))
			{
				res = null;
				break;
			}
			else
			{
				res ~= cur;
			}
		}
		else
		{
			break;
		}
	}

	if(!arr.length && res.length)
	{
		writeln(res.length);

		foreach(s; res)
		{
			writefln(`%u %(%u %)`, s.length, s);
		}
	}
	else
	{
		writeln(-1);
	}
}


Vivek has encountered a problem. He has a maze that can be represented as an $$$n \times m$$$ grid. Each of the grid cells may represent the following:  Empty — '.'  Wall — '#'  Good person  — 'G'  Bad person — 'B' The only escape from the maze is at cell $$$(n, m)$$$.A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.It is guaranteed that the cell $$$(n,m)$$$ is empty. Vivek can also block this cell.

The first line contains one integer $$$t$$$ $$$(1 \le t \le 100)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$m$$$ $$$(1 \le n, m \le 50)$$$ — the number of rows and columns in the maze. Each of the next $$$n$$$ lines contain $$$m$$$ characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.

For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No" You may print every letter in any case (upper or lower).

NoteFor the first and second test cases, all conditions are already satisfied.For the third test case, there is only one empty cell $$$(2,2)$$$, and if it is replaced with a wall then the good person at $$$(1,2)$$$ will not be able to escape.For the fourth test case, the good person at $$$(1,1)$$$ cannot escape.For the fifth test case, Vivek can block the cells $$$(2,3)$$$ and $$$(2,2)$$$.For the last test case, Vivek can block the destination cell $$$(2, 2)$$$.

import core.bitop, std.bitmanip;
import core.checkedint;
import std.algorithm, std.functional, std.meta;
import std.array, std.container;
import std.bigint;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

void main()
{
    int t;
    readf("%s", &t);
    readln;

    while (t--) {
        int n, m;
        readf("%s %s", &n, &m);
        readln;

        auto arr = new dchar[][] (n + 2, m + 2);
        foreach (i; 0 .. n+2) {
            foreach (j; 0 .. m+2) {
                arr[i][j] = '#';
            }
        }

        foreach (i; 1 .. n+1) {
            foreach (j; 1 .. m+1) {
                readf("%s", &arr[i][j]);
            }

            readln;
        }

        debug { arr.writeln; }

        bool isOkCell(int i, int j) {
            if (arr[i][j] != 'B') { return true; }

            foreach (x; -1 .. 2) {
                foreach (y; -1 .. 2) {
                    if (abs(x) + abs(y) != 1) { continue; }
                    if (arr[i+x][y+j] == 'G') { return false; }
                }
            }

            return true;
        }

        void mark(int i, int j) {
            if (arr[i][j] != 'B') { return; }

            foreach (x; -1 .. 2) {
                foreach (y; -1 .. 2) {
                    if (abs(x) + abs(y) != 1) { continue; }
                    if (arr[i+x][j+y] == '.') { arr[i+x][j+y] = '#'; }
                }
            }
        }

        bool ans = true;
        foreach (i; 1 .. n+1) {
            foreach (j; 1 .. m+1) {
                ans &= isOkCell(i, j);
                mark(i, j);
            }
        }

        if (!ans) {
            writeln("No");
            continue;
        }

        debug { arr.writeln; }

        auto vis = new bool[][] (n+2, m+2);
        foreach (i; 0 .. n+2) {
            vis[i][] = false;
        }

        void dfs(int i, int j) {
            if (arr[i][j] == '#') { return; }

            vis[i][j] = true;
            foreach (x; -1 .. 2) {
                foreach (y; -1 .. 2) {
                    if (abs(x) + abs(y) != 1) { continue; }
                    if (vis[i+x][j+y]) { continue; }

                    dfs(i+x, y+j);
                }
            }
        }

        dfs(n, m);

        foreach (i; 1 .. n+1) {
            foreach (j; 1 .. m+1) {
                if (arr[i][j] == 'G' && !vis[i][j]) { ans = false; }
            }
        }

        writeln(ans ? "Yes" : "No");
    }
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

immutable int dirs = 4;
immutable int [dirs] dRow = [-1,  0, +1,  0];
immutable int [dirs] dCol = [ 0, -1,  0, +1];

void main ()
{
	foreach (test; 0..readln.strip.to !(int))
	{
		int rows, cols;
		readf !(" %s %s") (rows, cols);
		readln;
		char [] [] board;
		board ~= '#'.repeat (cols + 2).array;
		foreach (row; 1..rows + 1)
		{
			board ~= '#' ~ readln.strip.dup ~ '#';
		}
		board ~= '#'.repeat (cols + 2).array;

		int goods = 0;
		foreach (row; 1..rows + 1)
		{
			goods += board[row].count ('G');
		}

		foreach (row; 1..rows + 1)
		{
			foreach (col; 1..cols + 1)
			{
				if (board[row][col] != 'B')
				{
					continue;
				}
				foreach (dir; 0..dirs)
				{
					auto nRow = row + dRow[dir];
					auto nCol = col + dCol[dir];
					if (board[nRow][nCol] == '.')
					{
						board[nRow][nCol] = '#';
					}
				}
			}
		}

		bool recur (int row, int col)
		{
			if (board[row][col] == '#')
			{
				return true;
			}
			if (board[row][col] == 'B')
			{
				return false;
			}
			goods -= (board[row][col] == 'G');
			board[row][col] = '#';
			foreach (dir; 0..dirs)
			{
				auto nRow = row + dRow[dir];
				auto nCol = col + dCol[dir];
				if (!recur (nRow, nCol))
				{
					return false;
				}
			}
			return true;
		}

		bool ok = recur (rows, cols);
		ok &= (goods == 0);
		writeln (ok ? "Yes" : "No");
	}
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto m = RD!int;
		auto s = new char[][](n);
		foreach (i; 0..n)
		{
			s[i] = RD!(char[]);
		}

		bool visit(int y, int x)
		{
			if (!inside(y, 0, n) || !inside(x, 0, m)) return true;
			if (s[y][x] == 'G') return false;
			if (s[y][x] == '.')
			{
				s[y][x] = '#';
			}
			return true;
		}

		bool ok = true;
		int[][] good;
		(){
		foreach (int y; 0..n)
		{
			foreach (int x; 0..m)
			{
				if (s[y][x] == 'B')
				{

					ok &= visit(y-1, x);
					ok &= visit(y+1, x);
					ok &= visit(y, x-1);
					ok &= visit(y, x+1);
					if (!ok) return;
				}
				else if (s[y][x] == 'G')
				{
					good ~= [y, x];
				}
			}
		}}();
		if (!ok) continue;

		int[][] open;
		if (s[n-1][m-1] != '#')
		{
			open ~= [[n-1, m-1]];
		}
		auto dist = new int[][](n, m);
		foreach (i; 0..n)
		{
			dist[i][] = int.max;
		}
		dist[n-1][m-1] = 0;
		while (!open.empty)
		{
			auto nd = open.front; open.popFront;
			auto y = nd[0];
			auto x = nd[1];
			if (y != 0)
			{
				auto ny = y-1;
				auto nx = x;
				if (s[ny][nx] != '#')
				{
					if (dist[y][x]+1 < dist[ny][nx])
					{
						dist[ny][nx] = dist[y][x]+1;
						open ~= [ny, nx];
					}
				}
			}
			if (y != n-1)
			{
				auto ny = y+1;
				auto nx = x;
				if (s[ny][nx] != '#')
				{
					if (dist[y][x]+1 < dist[ny][nx])
					{
						dist[ny][nx] = dist[y][x]+1;
						open ~= [ny, nx];
					}
				}
			}
			if (x != 0)
			{
				auto ny = y;
				auto nx = x-1;
				if (s[ny][nx] != '#')
				{
					if (dist[y][x]+1 < dist[ny][nx])
					{
						dist[ny][nx] = dist[y][x]+1;
						open ~= [ny, nx];
					}
				}
			}
			if (x != m-1)
			{
				auto ny = y;
				auto nx = x+1;
				if (s[ny][nx] != '#')
				{
					if (dist[y][x]+1 < dist[ny][nx])
					{
						dist[ny][nx] = dist[y][x]+1;
						open ~= [ny, nx];
					}
				}
			}
		}

		foreach (e; good)
		{
			auto y = e[0];
			auto x = e[1];
			if (dist[y][x] == int.max)
			{
				ok = false;
				break;
			}
		}
		ans[ti] = ok;
	}

	foreach (e; ans)
		writeln(e ? "Yes" : "No");
	stdout.flush;
	debug readln;
}

import core.bitop, std.bitmanip;
import core.checkedint;
import std.algorithm, std.functional, std.meta;
import std.array, std.container;
import std.bigint;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

void main()
{
    int t;
    readf("%s", &t);
    readln;

    while (t--) {
        int n, m;
        readf("%s %s", &n, &m);
        readln;

        auto arr = new dchar[][] (n + 2, m + 2);
        foreach (i; 0 .. n+2) {
            foreach (j; 0 .. m+2) {
                arr[i][j] = '#';
            }
        }

        foreach (i; 1 .. n+1) {
            foreach (j; 1 .. m+1) {
                readf("%s", &arr[i][j]);
            }

            readln;
        }

        debug { arr.writeln; }

        bool isOkCell(int i, int j) {
            if (arr[i][j] != 'B') { return true; }

            foreach (x; -1 .. 2) {
                foreach (y; -1 .. 2) {
                    if (abs(x) + abs(y) != 1) { continue; }
                    if (arr[i+x][y+j] == 'G') { return false; }
                }
            }

            return true;
        }

        void mark(int i, int j) {
            if (arr[i][j] != 'B') { return; }

            foreach (x; -1 .. 2) {
                foreach (y; -1 .. 2) {
                    if (abs(x) + abs(y) != 1) { continue; }
                    if (arr[i+x][j+y] != 'G') { arr[i+x][j+y] = '#'; }
                }
            }
        }

        bool ans = true;
        foreach (i; 1 .. n+1) {
            foreach (j; 1 .. m+1) {
                ans &= isOkCell(i, j);
                mark(i, j);
            }
        }

        if (!ans) {
            writeln("No");
            continue;
        }

        debug { arr.writeln; }

        auto vis = new bool[][] (n+2, m+2);
        foreach (i; 0 .. n+2) {
            vis[i][] = false;
        }

        void dfs(int i, int j) {
            if (arr[i][j] == '#') { return; }

            vis[i][j] = true;
            foreach (x; -1 .. 2) {
                foreach (y; -1 .. 2) {
                    if (abs(x) + abs(y) != 1) { continue; }
                    if (vis[i+x][j+y]) { continue; }

                    dfs(i+x, y+j);
                }
            }
        }

        dfs(n, m);

        foreach (i; 1 .. n+1) {
            foreach (j; 1 .. m+1) {
                if (arr[i][j] == 'G' && !vis[i][j]) { ans = false; }
            }
        }

        writeln(ans ? "Yes" : "No");
    }
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto m = RD!int;
		auto s = new char[][](n);
		foreach (i; 0..n)
		{
			s[i] = RD!(char[]);
		}

		bool visit(int y, int x)
		{
			if (!inside(y, 0, n) || !inside(x, 0, m)) return true;
			if (s[y][x] == 'G') return false;
			if (s[y][x] == '.')
			{
				s[y][x] = '#';
			}
			return true;
		}

		bool ok = true;
		int[][] good;
		(){
		foreach (int y; 0..n)
		{
			foreach (int x; 0..m)
			{
				if (s[y][x] == 'B')
				{

					ok = visit(y-1, x);
					ok = visit(y+1, x);
					ok = visit(y, x-1);
					ok = visit(y, x+1);
					if (!ok) return;
				}
				else if (s[y][x] == 'G')
				{
					good ~= [y, x];
				}
			}
		}}();
		if (!ok) continue;

		int[][] open;
		if (s[n-1][m-1] != '#')
		{
			open ~= [[n-1, m-1]];
		}
		auto dist = new int[][](n, m);
		foreach (i; 0..n)
		{
			dist[i][] = int.max;
		}
		dist[n-1][m-1] = 0;
		while (!open.empty)
		{
			auto nd = open.front; open.popFront;
			auto y = nd[0];
			auto x = nd[1];
			if (y != 0)
			{
				auto ny = y-1;
				auto nx = x;
				if (s[ny][nx] != '#')
				{
					if (dist[y][x]+1 < dist[ny][nx])
					{
						dist[ny][nx] = dist[y][x]+1;
						open ~= [ny, nx];
					}
				}
			}
			if (y != n-1)
			{
				auto ny = y+1;
				auto nx = x;
				if (s[ny][nx] != '#')
				{
					if (dist[y][x]+1 < dist[ny][nx])
					{
						dist[ny][nx] = dist[y][x]+1;
						open ~= [ny, nx];
					}
				}
			}
			if (x != 0)
			{
				auto ny = y;
				auto nx = x-1;
				if (s[ny][nx] != '#')
				{
					if (dist[y][x]+1 < dist[ny][nx])
					{
						dist[ny][nx] = dist[y][x]+1;
						open ~= [ny, nx];
					}
				}
			}
			if (x != m-1)
			{
				auto ny = y;
				auto nx = x+1;
				if (s[ny][nx] != '#')
				{
					if (dist[y][x]+1 < dist[ny][nx])
					{
						dist[ny][nx] = dist[y][x]+1;
						open ~= [ny, nx];
					}
				}
			}
		}

		foreach (e; good)
		{
			auto y = e[0];
			auto x = e[1];
			if (dist[y][x] == int.max)
			{
				ok = false;
				break;
			}
		}
		ans[ti] = ok;
	}

	foreach (e; ans)
		writeln(e ? "Yes" : "No");
	stdout.flush;
	debug readln;
}


You are given an array $$$a$$$ consisting of $$$n$$$ positive integers.You are allowed to perform this operation any number of times (possibly, zero):   choose an index $$$i$$$ ($$$2 \le i \le n$$$), and change $$$a_i$$$ to $$$a_i - a_{i-1}$$$. Is it possible to make $$$a_i=0$$$ for all $$$2\le i\le n$$$?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 100$$$)  — the number of test cases. The description of the test cases follows. The first line contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the length of array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$).

For each test case, print "YES" (without quotes), if it is possible to change $$$a_i$$$ to $$$0$$$ for all $$$2 \le i \le n$$$, and "NO" (without quotes) otherwise. You can print letters in any case (upper or lower).

NoteIn the first test case, the initial array is $$$[5,10]$$$. You can perform $$$2$$$ operations to reach the goal:  Choose $$$i=2$$$, and the array becomes $$$[5,5]$$$.  Choose $$$i=2$$$, and the array becomes $$$[5,0]$$$. In the second test case, the initial array is $$$[1,2,3]$$$. You can perform $$$4$$$ operations to reach the goal:   Choose $$$i=3$$$, and the array becomes $$$[1,2,1]$$$.  Choose $$$i=2$$$, and the array becomes $$$[1,1,1]$$$.  Choose $$$i=3$$$, and the array becomes $$$[1,1,0]$$$.  Choose $$$i=2$$$, and the array becomes $$$[1,0,0]$$$. In the third test case, you can choose indices in the order $$$4$$$, $$$3$$$, $$$2$$$.

// cheese-cracker [2022-07-16]

void solve(){
    int n = scan!int;
    auto arr = scanArray;
    for(int i = 1; i < n; ++i){
        if(arr[i] % arr[0] != 0){
            writeln("NO");
            return;
        }
    }
    writeln("YES");
}

void main(){
    long tests = scan;        // Toggle!
    while(tests--) solve;
}

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm;
import std.container, std.math, std.numeric, std.functional;
string[] tk; alias tup = Tuple!(long, long);
T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }


Martians are actively engaged in interplanetary trade. Olymp City, the Martian city known for its spaceport, has become a place where goods from all the corners of our Galaxy come. To deliver even more freight from faraway planets, Martians need fast spaceships.A group of scientists conducts experiments to build a fast engine for the new spaceship. In the current experiment, there are $$$n$$$ elementary particles, the $$$i$$$-th of them has type $$$a_i$$$.Denote a subsegment of the particle sequence ($$$a_1, a_2, \dots, a_n$$$) as a sequence ($$$a_l, a_{l+1}, \dots, a_r$$$) for some left bound $$$l$$$ and right bound $$$r$$$ ($$$1 \le l \le r \le n$$$). For instance, the sequence $$$(1\ 4\ 2\ 8\ 5\ 7)$$$ for $$$l=2$$$ and $$$r=4$$$ has the sequence $$$(4\ 2\ 8)$$$ as a subsegment. Two subsegments are considered different if at least one bound of those subsegments differs.Note that the subsegments can be equal as sequences but still considered different. For example, consider the sequence $$$(1\ 1\ 1\ 1\ 1)$$$ and two of its subsegments: one with $$$l=1$$$ and $$$r=3$$$ and another with $$$l=2$$$ and $$$r=4$$$. Both subsegments are equal to $$$(1\ 1\ 1)$$$, but still considered different, as their left and right bounds differ.The scientists want to conduct a reaction to get two different subsegments of the same length. Denote this length $$$k$$$. The resulting pair of subsegments must be harmonious, i. e. for some $$$i$$$ ($$$1 \le i \le k$$$) it must be true that the types of particles on the $$$i$$$-th position are the same for these two subsegments. For example, the pair $$$(1\ 7\ 3)$$$ and $$$(4\ 7\ 8)$$$ is harmonious, as both subsegments have $$$7$$$ on the second position. The pair $$$(1\ 2\ 3)$$$ and $$$(3\ 1\ 2)$$$ is not harmonious.The longer are harmonious subsegments, the more chances for the scientists to design a fast engine. So, they asked you to calculate the maximal possible length of harmonious pair made of different subsegments.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The following are descriptions of the test cases. The first line contains an integer $$$n$$$ ($$$2 \le n \le 150\,000$$$) — the amount of elementary particles in the sequence. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 150\,000$$$) — types of elementary particles. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3\cdot10^5$$$.

For each test, print a single integer, maximal possible length of harmonious pair made of different subsegments. If such pair does not exist, print $$$-1$$$ instead.

NoteThe first test case is shown on the picture below:  As you can see from it, you may choose the subsegments $$$(2\ 1\ 3\ 4)$$$ and $$$(3\ 1\ 5\ 2)$$$, which are a harmonious pair. Their length is equal to $$$4$$$, so the answer is $$$4$$$.In the second test case, you need to take two subsegments: one with $$$l=1$$$ and $$$r=5$$$, and one with $$$l=2$$$ and $$$r=6$$$. It's not hard to observe that these segments are a harmonious pair and considered different even though they are both equal to $$$(1\ 1\ 1\ 1\ 1)$$$.In the third test case, you cannot make a harmonious pair, so the answer is $$$-1$$$.

import std;

T
read (alias T, string end = "") () {
    T x;
    readf!("%s" ~ end)(x);
    return x;
}

void main () {
    immutable tests = read!(uint, "\n");
    TEST_LOOP: foreach (test_index; 0 .. tests) {
        immutable n = read!(uint, "\n");
        immutable vec =
            readln.chomp.split(' ')
            .to!(uint[]);

        auto indexes = (){
            static assert(true);
            size_t[][uint] ret;
            foreach (ind, val; vec)
                ret[val] ~= ind;
            return ret;
        }();

        (cast(int)(
              -
                indexes
                .byValue
                .filter!"a.length > 1"
                .map!(x => zip(x, x.dropOne)
                        .minElement!"a[1] - a[0]")
                .map!(x => x[1] - x[0])
                .minElement(n + 1)
              + n

        ))
            .writeln;
    }
}
// ""

import std;

T
read (alias T, string end = "") () {
    T x;
    readf!("%s" ~ end)(x);
    return x;
}

void main () {
    immutable tests = read!(uint, "\n");
    TEST_LOOP: foreach (test_index; 0 .. tests) {
        immutable n = read!(uint, "\n");
        immutable vec =
            readln.chomp.split(' ')
            .to!(uint[]);

        auto indexes = (){
            static assert(true);
            size_t[][uint] ret;
            foreach (ind, val; vec)
                ret[val] ~= ind;
            return ret;
        }();

        (cast(int)(
              -
                indexes
                .byValue
                .filter!"a.length > 1"
                .map!(x => zip(x, x.dropOne)
                        .minElement!"a[1] - a[0]")
                .cache.map!(x => x[1] - x[0])
                .minElement(n + 1)
              + n

        ))
            .writeln;
    }
}
// ""

void main() { runSolver(); }

void problem() {
  auto QN = scan!int;

  auto solve() {
    long subSolve(long N, int[] A) {
      int[][int] indecies;
      foreach(int i, a; A) {
        indecies[a] ~= i;
      }
      // indecies.deb;

      long ans = -1;
      foreach(key, inds; indecies) {
        if (inds.length == 1) continue;

        long minDistance = int.max;
        foreach(i; 0..inds.length - 1) {
          minDistance = min(minDistance, inds[i + 1] - inds[i]);
        }

        ans = ans.max(N - minDistance);
      }

      return ans;
    }

    foreach(i; 0..QN) {
      const n = scan!int;
      subSolve(n, scan!int(n)).writeln;
    }
  }

  outputForAtCoder(&solve);
}

// ----------------------------------------------

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

// -----------------------------------------------

K binarySearch(K)(bool delegate(K) cond, K l, K r) { return binarySearch((K k) => k, cond, l, r); }
T binarySearch(T, K)(K delegate(T) fn, bool delegate(K) cond, T l, T r) {
  auto ok = l;
  auto ng = r;
  const T TWO = 2;

  bool again() {
    static if (is(T == float) || is(T == double) || is(T == real)) {
      return !ng.approxEqual(ok, 1e-08, 1e-08);
    } else {
      return abs(ng - ok) > 1;
    }
  }

  while(again()) {
    const half = (ng + ok) / TWO;
    const halfValue = fn(half);

    if (cond(halfValue)) {
      ok = half;
    } else {
      ng = half;
    }
  }

  return ok;
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

//long mod = 10^^9 + 7;
long mod = 998_244_353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA(-1);

		auto pos = new int[][](150000);
		foreach (i; 0..n)
		{
			pos[a[i]] ~= i;
		}

		foreach (i; 0..pos.length)
		{
			if (pos[i].length < 2) continue;
			foreach (j; 0..pos[i].length-1)
			{
				ans[ti].chmax(pos[i][j] + n - pos[i][j+1]);
			}
		}
		if (ans[ti] == 0)
			ans[ti] = -1;
	}

	foreach (e; ans)
		writeln(e);
	stdout.flush;
	debug readln;
}


You are planning to buy an apartment in a $$$n$$$-floor building. The floors are numbered from $$$1$$$ to $$$n$$$ from the bottom to the top. At first for each floor you want to know the minimum total time to reach it from the first (the bottom) floor.Let:  $$$a_i$$$ for all $$$i$$$ from $$$1$$$ to $$$n-1$$$ be the time required to go from the $$$i$$$-th floor to the $$$(i+1)$$$-th one (and from the $$$(i+1)$$$-th to the $$$i$$$-th as well) using the stairs;  $$$b_i$$$ for all $$$i$$$ from $$$1$$$ to $$$n-1$$$ be the time required to go from the $$$i$$$-th floor to the $$$(i+1)$$$-th one (and from the $$$(i+1)$$$-th to the $$$i$$$-th as well) using the elevator, also there is a value $$$c$$$ — time overhead for elevator usage (you need to wait for it, the elevator doors are too slow!). In one move, you can go from the floor you are staying at $$$x$$$ to any floor $$$y$$$ ($$$x \ne y$$$) in two different ways:  If you are using the stairs, just sum up the corresponding values of $$$a_i$$$. Formally, it will take $$$\sum\limits_{i=min(x, y)}^{max(x, y) - 1} a_i$$$ time units.  If you are using the elevator, just sum up $$$c$$$ and the corresponding values of $$$b_i$$$. Formally, it will take $$$c + \sum\limits_{i=min(x, y)}^{max(x, y) - 1} b_i$$$ time units. You can perform as many moves as you want (possibly zero).So your task is for each $$$i$$$ to determine the minimum total time it takes to reach the $$$i$$$-th floor from the $$$1$$$-st (bottom) floor.

The first line of the input contains two integers $$$n$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5, 1 \le c \le 1000$$$) — the number of floors in the building and the time overhead for the elevator rides. The second line of the input contains $$$n - 1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the time required to go from the $$$i$$$-th floor to the $$$(i+1)$$$-th one (and from the $$$(i+1)$$$-th to the $$$i$$$-th as well) using the stairs. The third line of the input contains $$$n - 1$$$ integers $$$b_1, b_2, \dots, b_{n-1}$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the time required to go from the $$$i$$$-th floor to the $$$(i+1)$$$-th one (and from the $$$(i+1)$$$-th to the $$$i$$$-th as well) using the elevator.

Print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$, where $$$t_i$$$ is the minimum total time to reach the $$$i$$$-th floor from the first floor if you can perform as many moves as you want.

import core.bitop, std.bitmanip;
import core.checkedint;
import std.algorithm, std.functional, std.meta;
import std.array, std.container;
import std.bigint;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.ascii, std.typecons;

void main()
{
    int n, c;
    readf("%s %s", &n, &c);
    readln;

    auto a = readln.chomp.split.map!(to!int).array;
    auto b = readln.chomp.split.map!(to!int).array;

    auto dp = new int[][] (n+2, 2);
    dp[0][1] = c;

    int[] ans;
    ans ~= 0;
    foreach (i; 0 .. n-1) {
        dp[i+1][0] = min(dp[i][0], dp[i][1]) + a[i];
        dp[i+1][1] = min(dp[i][0] + c, dp[i][1]) + b[i];
        debug { writeln(i, dp[i]); }
        ans ~= min(dp[i+1][0], dp[i+1][1]);
    }

    ans.map!(to!string).join(' ').writeln;
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
T[] RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[][] RDA2(T = long)(size_t n, T[] fix = []) { auto r = new T[][](n); foreach (i; 0..n) { r[i] = readln.chomp.split.to!(T[]); foreach (j, e; fix) r[i][j] += e; } return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
long lcm(long x, long y) { return x * (y / gcd(x, y)); }

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto n = RD!int;
	auto c = RD!int;
	auto a = RDA;
	auto b = RDA;

	auto dp = new long[][](n+1, 2);
	dp[0][1] = c;

	foreach (i; 0..n-1)
	{
		dp[i+1][0] = min(dp[i][0]+a[i], dp[i][1]+a[i]);
		dp[i+1][1] = min(dp[i][0]+b[i]+c, dp[i][1]+b[i]);
	}

	auto ans = new long[](n);
	foreach (i; 0..n-1)
	{
		ans[i+1] = min(dp[i+1][0], dp[i+1][1]);
	}

	ans.map!(to!string).join(" ").writeln;

	stdout.flush();
	debug readln();
}


Let's call a permutation $$$p$$$ of length $$$n$$$ anti-Fibonacci if the condition $$$p_{i-2} + p_{i-1} \ne p_i$$$ holds for all $$$i$$$ ($$$3 \le i \le n$$$). Recall that the permutation is the array of length $$$n$$$ which contains each integer from $$$1$$$ to $$$n$$$ exactly once.Your task is for a given number $$$n$$$ print $$$n$$$ distinct anti-Fibonacci permutations of length $$$n$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 48$$$) — the number of test cases.  The single line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 50$$$).

For each test case, print $$$n$$$ lines. Each line should contain an anti-Fibonacci permutation of length $$$n$$$. In each test case, you cannot print any permutation more than once. If there are multiple answers, print any of them. It can be shown that it is always possible to find $$$n$$$ different anti-Fibonacci permutations of size $$$n$$$ under the constraints of the problem.

void main() { runSolver(); }

void problem() {
  auto QN = scan!int;

  auto solve() {
    auto subSolve() {
      auto N = scan!int;

      auto used = new bool[](N + 1);
      auto queue = iota(1, N+1).array;
      auto ans = Array!int();
      int output;
      void dfs(int size = 0) {
        if (output == N) return;
        if (size == N) {
          output++;
          ans.array.toAnswerString.writeln;
          return;
        }

        foreach(p; queue) {
          if (used[p]) continue;

          if (ans.length < 2 || ans[$ - 1] + ans[$ - 2] != p) {
            ans.insertBack(p);
            used[p] = true;
            dfs(size + 1);
            ans.removeBack;
            used[p] = false;
          }
        }
      }

      dfs();

    }

    foreach(i; 0..QN) {
      subSolve();
    }
  }

  outputForAtCoder(&solve);
}

// ----------------------------------------------

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
T[] compress(T)(T[] arr, T origin = T.init) { T[T] indecies; arr.dup.sort.uniq.enumerate(origin).each!((i, t) => indecies[t] = i); return arr.map!(t => indecies[t]).array; }
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

// -----------------------------------------------

import std;

T
read (alias T, string end = "") () {
    T x;
    readf!("%s" ~ end)(x);
    return x;
}

void main () {
    immutable tests = read!(uint, "\n");
    TEST_LOOP: foreach (test_index; 0 .. tests) {
        immutable n = readln.chomp.to!uint;

        foreach (onePosition; 0 .. n) {
            chain(
                iota(n, n - onePosition, -1),
                [1u],
                iota(n - onePosition, 1 , -1)
            ).writefln!"%(%s %)";
        }
    }
}
// ""


Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.

First line contains two integers R (1 ≤ R ≤ 500) and C (1 ≤ C ≤ 500), denoting the number of rows and the numbers of columns respectively. Each of the following R lines is a string consisting of exactly C characters, representing one row of the pasture. Here, 'S' means a sheep, 'W' a wolf and '.' an empty cell.

If it is impossible to protect all sheep, output a single line with the word "No". Otherwise, output a line with the word "Yes". Then print R lines, representing the pasture after placing dogs. Again, 'S' means a sheep, 'W' a wolf, 'D' is a dog and '.' an empty space. You are not allowed to move, remove or add a sheep or a wolf. If there are multiple solutions, you may print any of them. You don't have to minimize the number of dogs.

NoteIn the first example, we can split the pasture into two halves, one containing wolves and one containing sheep. Note that the sheep at (2,1) is safe, as wolves cannot move diagonally.In the second example, there are no empty spots to put dogs that would guard the lone sheep.In the third example, there are no wolves, so the task is very easy. We put a dog in the center to observe the peacefulness of the meadow, but the solution would be correct even without him.

void main(){
  import std.stdio, std.string, std.conv, std.algorithm;

  int h, w; rd(h, w);
  auto c=new char[][](h, w);
  foreach(i; 0..h) c[i]=readln.chomp.to!(char[]);

  auto dir=[[1, 0], [-1, 0], [0, 1], [0, -1]];
  foreach(i; 0..h)foreach(j; 0..w){
    if(c[i][j]=='W'){
      foreach(d; dir){
        auto ni=i+d[0], nj=j+d[1];
        if(ni<0 || ni>=h || nj<0 || nj>=w) continue;
        if(c[ni][nj]=='S'){writeln("No"); return;}
      }
    }else if(c[i][j]=='.'){
      c[i][j]='D';
    }
  }

  writeln("Yes");
  foreach(i; 0..h) writefln("%(%c%)", c[i]);
}
void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x){
    e=l[i].to!(typeof(e));
  }
}

void main(){
  import std.stdio, std.string, std.conv, std.algorithm;

  int h, w; rd(h, w);
  auto c=new char[][](h, w);
  foreach(i; 0..h) c[i]=readln.chomp.to!(char[]);

  auto dir=[[1, 0], [-1, 0], [0, 1], [0, -1]];
  foreach(i; 0..h)foreach(j; 0..w){
    if(c[i][j]=='W'){
      foreach(d; dir){
        auto ni=i+d[0], nj=j+d[1];
        if(ni<0 || ni>=h || nj<0 || nj>=w) continue;
        if(c[ni][nj]=='S'){writeln("No"); return;}
      }
    }else if(c[i][j]=='.'){
      c[i][j]='D';
    }
  }

  foreach(i; 0..h) writefln("%(%c%)", c[i]);
}
void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x){
    e=l[i].to!(typeof(e));
  }
}


The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 40 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.

The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.

NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.

import std.stdio, std.string;
import std.conv, std.array;
import std.math, std.algorithm;

int main(string[] args)
{
    auto n = to!int(readln.strip);
    writeln("? 1 ", n);
    stdout.flush;
    auto pidx = to!int(readln.strip);
    auto left = 1, right = n;
    while (left < right)
    {
        auto mid = (left + right) >> 1;
        if (left == mid && right == mid + 1)
        {
            if (pidx == left) left = mid + 1;
            else right = mid;
            continue;
        }
        int lidx, ridx;
        if (left < mid)
        {
            writeln("? ", left, " ", mid);
            stdout.flush;
            lidx = to!int(readln.strip);
        }
        if (mid + 1 < right)
        {
            writeln("? ", mid + 1, " ", right);
            stdout.flush;
            ridx = to!int(readln.strip);
        }
        if (left == mid)
        {
            if (pidx == left || pidx == ridx) left = mid + 1, pidx = ridx;
            else right = mid;
            continue;
        }
        if (right == mid + 1)
        {
            if (pidx == right || pidx == lidx) right = mid, pidx = lidx;
            else left = mid + 1;
            continue;
        }
        if (pidx <= mid)
        {
            if (pidx == lidx) right = mid;
            else left = mid + 1;
        }
        else
        {
            if (pidx == ridx) left = mid + 1;
            else right = mid;
        }
        pidx = (left > mid ? ridx : lidx);
    }
    writeln("! ", left);
    return 0;
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

//long mod = 10^^9 + 7;
long mod = 998_244_353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto n = RD!int;

	int l = 1, r = n;
	writeln("? ", l, " ", r);
	stdout.flush;
	auto m = RD!int;
	while (r - l > 1)
	{
		auto m2 = (l+r)/2;
		if (m <= m2)
		{
			writeln("? ", l, " ", m2);
			stdout.flush;
			auto a = RD!int;
			if (a == m)
				r = m2;
			else
			{
				l = m2;
				writeln("? ", l, " ", r);
				stdout.flush;
				m = RD!int;
			}
		}
		else
		{
			writeln("? ", m2, " ", r);
			stdout.flush;
			auto a = RD!int;
			if (a == m)
				l = m2;
			else
			{
				r = m2;
				writeln("? ", l, " ", r);
				stdout.flush;
				m = RD!int;
			}
		}
	}

	if (m == l)
		writeln("! ", r);
	else
		writeln("! ", l);
	stdout.flush;
	debug readln;
}

import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric, std.container, std.range;

void get(Args...)(ref Args args)
{
    import std.traits, std.meta, std.typecons;

    static if (Args.length == 1) {
        alias Arg = Args[0];

        static if (isArray!Arg) {
          static if (isSomeChar!(ElementType!Arg)) {
            args[0] = readln.chomp.to!Arg;
          } else {
            args[0] = readln.split.to!Arg;
          }
        } else static if (isTuple!Arg) {
            auto input = readln.split;
            static foreach (i; 0..Fields!Arg.length) {
                args[0][i] = input[i].to!(Fields!Arg[i]);
            }
        } else {
            args[0] = readln.chomp.to!Arg;
        }
    } else {
        auto input = readln.split;
        assert(input.length == Args.length);

        static foreach (i; 0..Args.length) {
            args[i] = input[i].to!(Args[i]);
        }
    }
}

void get_lines(Args...)(size_t N, ref Args args)
{
    import std.traits, std.range;

    static foreach (i; 0..Args.length) {
        static assert(isArray!(Args[i]));
        args[i].length = N;
    }

    foreach (i; 0..N) {
        static if (Args.length == 1) {
            get(args[0][i]);
        } else {
            auto input = readln.split;
            static foreach (j; 0..Args.length) {
                args[j][i] = input[j].to!(ElementType!(Args[j]));
            }
        }
    }
}

void main()
{
    int N; get(N);
    writefln!"? %d %d"(1, N); stdout.flush();
    int p; get(p);
    int q;
    if (p == 1) {
        q = -1;
    } else if (p == N) {
        q = N;
    } else {
        writefln!"? %d %d"(1, p); stdout.flush();
        get(q);
    }
    if (p == q) {
        int l = 1, r = p;
        while (l + 1 < r) {
            auto m = (l + r) / 2;
            writefln!"? %d %d"(m, p); stdout.flush();
            get(q);
            if (p == q) {
                l = m;
            } else {
                r = m;
            }
        }
        writeln("! ", l); stdout.flush();
    } else {
        int l = p, r = N;
        while (l + 1 < r) {
            auto m = (l + r) / 2;
            writefln!"? %d %d"(p, m); stdout.flush();
            get(q);
            if (p == q) {
                r = m;
            } else {
                l = m;
            }
        }
        writeln("! ", r); stdout.flush();
    }
}

import std.stdio, std.string;
import std.conv, std.array;
import std.math, std.algorithm;

int main(string[] args)
{
    auto n = to!int(readln.strip);
    writeln("? 1 ", n);
    stdout.flush;
    auto pidx = to!int(readln.strip);
    auto left = 1, right = n;
    while (left < right)
    {
        auto mid = (left + right) >> 1;
        if (left == mid && right == mid + 1)
        {
            if (pidx == left) left = mid + 1;
            else right = mid;
            continue;
        }
        int lidx, ridx;
        if (left < mid)
        {
            writeln("? ", left, " ", mid);
            stdout.flush;
            lidx = to!int(readln.strip);
        }
        if (mid + 1 < right)
        {
            writeln("? ", mid + 1, " ", right);
            stdout.flush;
            ridx = to!int(readln.strip);
        }
        if (left == mid)
        {
            if (pidx == left) left = mid + 1, pidx = ridx;
            else right = mid;
            continue;
        }
        if (right == mid + 1)
        {
            if (pidx == right) right = mid, pidx = lidx;
            else left = mid + 1;
            continue;
        }
        if (pidx <= mid)
        {
            if (pidx == lidx) right = mid;
            else left = mid + 1;
        }
        else
        {
            if (pidx == ridx) left = mid + 1;
            else right = mid;
        }
        if (left > mid) pidx = ridx;
        else pidx = lidx;
    }
    writeln("! ", left);
    return 0;
}

import std.stdio, std.string;
import std.conv, std.array;
import std.math, std.algorithm;

int main(string[] args)
{
    auto n = to!int(readln.strip);
    writeln("? 1 ", n);
    stdout.flush;
    auto pidx = to!int(readln.strip);
    auto left = 1, right = n;
    while (left < right)
    {
        auto mid = (left + right) >> 1;
        if (left == mid && right == mid + 1)
        {
            if (pidx == left) left = mid + 1;
            else right = mid;
            continue;
        }
        int lidx, ridx;
        if (left < mid)
        {
            writeln("? ", left, " ", mid);
            stdout.flush;
            lidx = to!int(readln.strip);
        }
        if (mid + 1 < right)
        {
            writeln("? ", mid + 1, " ", right);
            stdout.flush;
            ridx = to!int(readln.strip);
        }
        if (left == mid)
        {
            if (pidx == left) left = mid + 1, pidx = ridx;
            else right = mid;
            continue;
        }
        if (right == mid + 1)
        {
            if (pidx == right) right = mid, pidx = lidx;
            else left = mid + 1;
            continue;
        }
        if (pidx < mid)
        {
            if (pidx == lidx) right = mid;
            else left = mid + 1;
        }
        else
        {
            if (pidx == ridx) left = mid + 1;
            else right = mid;
        }
        if (left > mid) pidx = ridx;
        else pidx = lidx;
    }
    writeln("! ", left);
    return 0;
}

import std.stdio, std.string;
import std.conv, std.array;
import std.math, std.algorithm;

int main(string[] args)
{
    auto n = to!int(readln.strip);
    writeln("? 1 ", n);
    stdout.flush;
    auto pidx = to!int(readln.strip);
    auto left = 1, right = n;
    while (left < right)
    {
        auto mid = (left + right) >> 1;
        if (left == mid)
        {
            if (pidx == left) left = mid + 1;
            else right = mid - 1;
            continue;
        }
        if (right == mid + 1)
        {
            if (pidx == right) right = mid - 1;
            else left = mid + 1;
            continue;
        }
        writeln("? ", left, " ", mid);
        stdout.flush;
        auto lidx = to!int(readln.strip);
        writeln("? ", mid + 1, " ", right);
        stdout.flush;
        auto ridx = to!int(readln.strip);
        if (pidx < mid)
        {
            if (pidx == lidx) right = mid - 1;
            else left = mid + 1;
        }
        else
        {
            if (pidx == ridx) left = mid + 1;
            else right = mid - 1;
        }
        if (left > mid) pidx = ridx;
        else pidx = lidx;
    }
    writeln("! ", left);
    return 0;
}


Given an integer $$$n$$$, find the maximum value of integer $$$k$$$ such that the following condition holds:  $$$n$$$ & ($$$n-1$$$) & ($$$n-2$$$) & ($$$n-3$$$) & ... ($$$k$$$) = $$$0$$$  where & denotes the bitwise AND operation.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case, output a single integer — the required integer $$$k$$$.

NoteIn the first testcase, the maximum value for which the continuous & operation gives 0 value, is 1.In the second testcase, the maximum value for which the continuous & operation gives 0 value, is 3. No value greater then 3, say for example 4, will give the & sum 0.   $$$5 \, \& \, 4 \neq 0$$$,  $$$5 \, \& \, 4 \, \& \, 3 = 0$$$. Hence, 3 is the answer.

import std.algorithm, std.array, std.container, std.conv, std.math, std.range, std.stdio, std.string, std.typecons;
import core.bitop;

void main() {
    foreach(i; 0 .. to!int(readln.strip)) {
        int n = to!int(readln.strip);
        int r = bsr(n);
        writeln(pow(2, r)-1);
    }
}

import std.stdio;
void main()
{
    int q;
    readf!"%d\n"(q);
    foreach (_; 0 .. q)
    {
        int n;
        readf!"%d\n"(n);
        int res = 0;
        while (n)
        {
            res++;
            n /= 2;
        }
        writeln((1 << (res - 1)) - 1);
    }
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD;

		long x;
		foreach (i; 0..33)
		{
			auto bit = 1L << i;
			if (n & bit)
				x = bit;
		}
		ans[ti] = x - 1;
	}

	foreach (e; ans)
		writeln(e);
	stdout.flush;
	debug readln;
}