There are $$$n$$$ distinct points on a coordinate line, the coordinate of $$$i$$$-th point equals to $$$x_i$$$. Choose a subset of the given set of points such that the distance between each pair of points in a subset is an integral power of two. It is necessary to consider each pair of points, not only adjacent. Note that any subset containing one element satisfies the condition above. Among all these subsets, choose a subset with maximum possible size.In other words, you have to choose the maximum possible number of points $$$x_{i_1}, x_{i_2}, \dots, x_{i_m}$$$ such that for each pair $$$x_{i_j}$$$, $$$x_{i_k}$$$ it is true that $$$|x_{i_j} - x_{i_k}| = 2^d$$$ where $$$d$$$ is some non-negative integer number (not necessarily the same for each pair of points).

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line contains $$$n$$$ pairwise distinct integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$) — the coordinates of points.

In the first line print $$$m$$$ — the maximum possible number of points in a subset that satisfies the conditions described above. In the second line print $$$m$$$ integers — the coordinates of points in the subset you have chosen. If there are multiple answers, print any of them.

NoteIn the first example the answer is $$$[7, 3, 5]$$$. Note, that $$$|7-3|=4=2^2$$$, $$$|7-5|=2=2^1$$$ and $$$|3-5|=2=2^1$$$. You can't find a subset having more points satisfying the required property.

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    A.sort();

    bool[long] D;
    foreach (i; 0..N) {
        D[A[i]] = true;
    }

    int max_v = 1;
    long[] ans = [A[0]];

    foreach (a; A) {
        for (long d = 1; d < 10L^^10; d *= 2) {
            if ((a + d) in D && (a + 2*d) in D) {
                writeln(3);
                writeln(a, " ", a+d, " ", a+2*d);
                return;
            } else if (max_v == 1 && (a + d) in D) {
                max_v = 2;
                ans = [a, a+d];
            }
        }
    }

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

import std.algorithm;
import std.array;
import std.bitmanip;
import std.container;
import std.conv;
import std.functional;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main()
{
    readln;

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

    debug { a.writeln; }

    bool [int] v;
    a.each!(x => v[x] = true);

    int[] getAns(int x) {
        int ans = 0;
        uint p = 1;
        while (p <= 10^^9 * 2) {
            auto left = x - cast(int)p in v;
            auto right = x + cast(int)p in v;
            if (left && right) {
                ans = p;
                break;
            }
            if (left || right) ans = p;

            p *= 2;
        }

        if (ans == 0) return [x];

        auto ret = [x];
        if (x - ans in v) ret ~= x - ans;
        if (x + ans in v) ret ~= x + ans;
        return ret;
    }

    auto ans = a.map!(e => getAns(e)).maxElement!(e => e.length);

    ans.length.writeln;
    ans.writefln!("%(%s %)");
}

import std.algorithm;
import std.array;
import std.bitmanip;
import std.container;
import std.conv;
import std.functional;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main()
{
    readln;

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

    debug { a.writeln; }

    bool [int] v;
    a.each!(x => v[x] = true);

    int[] getAns(int x) {
        int ans = 0;
        auto powersOf2 = recurrence!(q{ a[n-1] * 2 })(1U);
        foreach (p; powersOf2.until!(x => x > 10^^9 * 2)) {
            auto left = x - cast(int)p in v;
            auto right = x + cast(int)p in v;
            if (left && right) {
                ans = p;
                break;
            }
            if (left || right) ans = p;
        }

        if (ans == 0) return [x];

        auto ret = [x];
        if (x - ans in v) ret ~= x - ans;
        if (x + ans in v) ret ~= x + ans;
        return ret;
    }

    auto ans = a.map!(e => getAns(e)).maxElement!(e => e.length);

    ans.length.writeln;
    ans.writefln!("%(%s %)");
}

import std.algorithm;
import std.array;
import std.bitmanip;
import std.container;
import std.conv;
import std.functional;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main()
{
    readln;

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

    debug { a.writeln; }

    bool [int] v;
    a.each!(x => v[x] = true);

    int[] getAns(int x) {
        int ans = 0;
        auto powersOf2 = recurrence!((a, n) => a[n-1] * 2)(1U);
        foreach (p; powersOf2.until!(x => x > 10^^9 * 2)) {
            auto left = x - cast(int)p in v;
            auto right = x + cast(int)p in v;
            if (left && right) {
                ans = p;
                break;
            }
            if (left || right) ans = p;
        }

        if (ans == 0) return [x];

        auto ret = [x];
        if (x - ans in v) ret ~= x - ans;
        if (x + ans in v) ret ~= x + ans;
        return ret;
    }

    auto ans = a.map!(e => getAns(e)).maxElement!(e => e.length);

    ans.length.writeln;
    ans.writefln!("%(%s %)");
}

import std.algorithm;
import std.array;
import std.bitmanip;
import std.container;
import std.conv;
import std.functional;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main()
{
    readln;

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

    debug { a.writeln; }

    bool [int] v;
    a.each!(x => v[x] = true);

    int[] getAns(int x) {
        int ans = 0;
        uint p = 1;
        while (p <= 10^^9 * 2) {
            auto left = (x - cast(int)p) in v;
            auto right = (x + cast(int)p) in v;
            if (left && right) {
                ans = p;
                break;
            }
            if (left || right) ans = cast(int)p;

            p *= 2;
        }

        if (ans == 0) return [x];

        auto ret = [x];
        if (x - ans in v) ret ~= x - ans;
        if (x + ans in v) ret ~= x + ans;
        return ret;
    }

    int[] ans = [];
    foreach (e; a) {
        auto cur = getAns(e);
        if (cur.length > ans.length) ans = cur;
    }

    ans.length.writeln;
    ans.writefln!("%(%s %)");
}

import std.stdio;
import std.algorithm;
import std.container.rbtree;
import std.algorithm.comparison : equal;

int main()
{
	int n;
	scanf("%d",&n);

	auto arr = new long[n];

	for(int i = 0; i < n; i++)
		scanf("%lld", &arr[i]);

	auto rbt = redBlackTree(arr);

	long[] subset = [arr[0]];

	for(int i = 0; i < n; i++)
	{
		for(long d = 1; d < (1L << 31); d*= 2)
		{
			if(!rbt.equalRange(arr[i] + d).empty()) {
				if (!rbt.equalRange(arr[i] + d * 2).empty()) {
					printf("3\n");
					printf("%lld %lld %lld\n",arr[i], arr[i] + d, arr[i] + 2 * d);
					return 0;
				}

				subset = [arr[i], arr[i] + d];
			}
		}
	}

	printf("%d\n",subset.length);

	for(int i =0; i < subset.length;i++)
		printf("%lld ",subset[i]);

	return 0;
}

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

  int n; rd(n);
  auto a=readln.split.to!(long[]);

  sort(a);
  import std.range;
  auto p=a.assumeSorted;
  long[] ans;
  foreach(b; 0..31){
    long d=1L<<b;
    auto used=new bool[](n);
    foreach(int i; 0..n){
      if(used[i]) continue;
      used[i]=true;
      int j=i;
      long[] beta=[a[j]];
      while(j<n){
        auto tri=p.trisect(a[j]+d);
        if(tri[1].empty){
          break;
        }else{
          j=tri[0].length.to!(int);
          beta~=a[j];
          used[j]=true;
        }
        if(beta.length==3) break;
      }
      if(ans.length<beta.length) ans=beta.dup;
    }
  }
  writeln(ans.length);
  writefln("%(%s %)", ans);
}

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.algorithm;
import std.array;
import std.bitmanip;
import std.container;
import std.conv;
import std.functional;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main()
{
    readln;

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

    debug { a.writeln; }

    bool [int] v;
    a.each!(x => v[x] = true);

    int[] getAns(int x) {
        int ans = 0;
        auto powersOf2 = recurrence!(q{ a[n-1] * 2 })(1U);
        foreach (p; powersOf2.until!(x => x <= 10^^9 * 2)) {
            auto left = x - cast(int)p in v;
            auto right = x + cast(int)p in v;
            if (left && right) {
                ans = p;
                break;
            }
            if (left || right) ans = p;
        }

        if (ans == 0) return [x];

        auto ret = [x];
        if (x - ans in v) ret ~= x - ans;
        if (x + ans in v) ret ~= x + ans;
        return ret;
    }

    auto ans = a.map!(e => getAns(e)).maxElement!(e => e.length);

    ans.length.writeln;
    ans.writefln!("%(%s %)");
}

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

  int n; rd(n);
  auto a=readln.split.to!(long[]);
  sort(a);

  import std.range;
  auto p=a.assumeSorted;
  long[] ans;
  foreach(b; 0..31){
    long d=1L<<b;
    auto used=new bool[](n);
    foreach(i; 0..n){
      if(used[i]) continue;
      used[i]=true;
      int j=i, cnt=1;
      long[] beta=[a[i]];
      while(j<n){
        auto tri=p.trisect(a[j]+d);
        if(tri[1].empty){
          break;
        }else{
          cnt++;
          j=tri[0].length.to!(int);
          used[j]=true;
          beta~=a[j];
        }
      }
      if(ans.length<beta.length) ans=beta.dup;
    }
  }

  writeln(ans.length);
  writefln("%(%s %)", ans);
}

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.algorithm, std.string, std.conv;

  int n; rd(n);
  auto a=readln.split.to!(long[]);

  sort(a);
  import std.range;
  auto p=a.assumeSorted;
  long[] ans;
  foreach(b; 0..31){
    long d=1L<<b;
    auto used=new bool[](n);
    foreach(int i; 0..n){
      if(used[i]) continue;
      used[i]=true;
      int j=i;
      long[] beta=[a[j]];
      while(j<n){
        auto tri=p.trisect(a[j]+d);
        if(tri[1].empty){
          break;
        }else{
          j=tri[0].length.to!(int);
          beta~=a[j];
          used[j]=true;
        }
      }
      if(ans.length<beta.length){
        ans=beta.dup;
        if(ans.length==3){
          writeln(ans.length);
          writefln("%(%s %)", ans);
          return;
        }
      }
    }
  }
  writeln(ans.length);
  writefln("%(%s %)", ans);
}

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.algorithm, std.string, std.conv;
  import std.random;

  int n; rd(n);
  auto a=readln.split.to!(long[]);

  // int n=15;
  // long[] a;
  // bool[long] h;
  // foreach(_; 0..n){
  //   long e=uniform(-100, 100);
  //   while(e in h){
  //     e=uniform(-100, 100);
  //   }
  //   a~=e;
  //   h[e]=true;
  // }

  sort(a);
  // writeln(a);

  import std.range;
  import core.bitop;
  auto p=a.assumeSorted;
  long[] ans;
  foreach(b; 0..32){
    long d=1L<<b;
    auto used=new bool[](n);
    foreach(i; 0..n){
      if(used[i]) continue;
      used[i]=true;
      int j=i;
      long[] beta=[a[i]];
      while(j<n){
        auto tri=p.trisect(a[j]+d);
        if(tri[1].empty){
          break;
        }else{
          j=tri[0].length.to!(int);
          used[j]=true;
          beta~=a[j];
        }
      }
      if(ans.length<beta.length){
        if(b==0){
          if(popcnt(beta.length)==1) ans=beta.dup;
        }else{
            ans=beta.dup;
        }
      }
    }
  }

  writeln(ans.length);
  writefln("%(%s %)", ans);

  // solve(a);
}

void solve(long[] a){
  import core.bitop, std.conv, std.math, std.algorithm;
  import std.stdio;
  int n=a.length.to!(int);
  long[] ret;
  foreach(bit; 0..(1<<n)){
    long[] cord;
    foreach(i; 0..n)if(bit&(1<<i)) cord~=a[i];
    int m=cord.length.to!(int);
    foreach(i; 0..m)foreach(j; 0..i){
      long dif=(cord[i]-cord[j]).abs;
      if(popcnt(dif)>1) goto hell;
    }
    if(ret.length<cord.length) ret=cord.dup;
    hell:;
  }
  writeln(ret.length);
  writeln(ret);
}

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));
}


Goa'uld Apophis captured Jack O'Neill's team again! Jack himself was able to escape, but by that time Apophis's ship had already jumped to hyperspace. But Jack knows on what planet will Apophis land. In order to save his friends, Jack must repeatedly go through stargates to get to this planet.Overall the galaxy has n planets, indexed with numbers from 1 to n. Jack is on the planet with index 1, and Apophis will land on the planet with index n. Jack can move between some pairs of planets through stargates (he can move in both directions); the transfer takes a positive, and, perhaps, for different pairs of planets unequal number of seconds. Jack begins his journey at time 0.It can be that other travellers are arriving to the planet where Jack is currently located. In this case, Jack has to wait for exactly 1 second before he can use the stargate. That is, if at time t another traveller arrives to the planet, Jack can only pass through the stargate at time t + 1, unless there are more travellers arriving at time t + 1 to the same planet.Knowing the information about travel times between the planets, and the times when Jack would not be able to use the stargate on particular planets, determine the minimum time in which he can get to the planet with index n.

The first line contains two space-separated integers: n (2 ≤ n ≤ 105), the number of planets in the galaxy, and m (0 ≤ m ≤ 105) — the number of pairs of planets between which Jack can travel using stargates. Then m lines follow, containing three integers each: the i-th line contains numbers of planets ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), which are connected through stargates, and the integer transfer time (in seconds) ci (1 ≤ ci ≤ 104) between these planets. It is guaranteed that between any pair of planets there is at most one stargate connection. Then n lines follow: the i-th line contains an integer ki (0 ≤ ki ≤ 105) that denotes the number of moments of time when other travellers arrive to the planet with index i. Then ki distinct space-separated integers tij (0 ≤ tij < 109) follow, sorted in ascending order. An integer tij means that at time tij (in seconds) another traveller arrives to the planet i. It is guaranteed that the sum of all ki does not exceed 105.

Print a single number — the least amount of time Jack needs to get from planet 1 to planet n. If Jack can't get to planet n in any amount of time, print number -1.

NoteIn the first sample Jack has three ways to go from planet 1. If he moves to planet 4 at once, he spends 8 seconds. If he transfers to planet 3, he spends 3 seconds, but as other travellers arrive to planet 3 at time 3 and 4, he can travel to planet 4 only at time 5, thus spending 8 seconds in total. But if Jack moves to planet 2, and then — to planet 4, then he spends a total of only 2 + 5 = 7 seconds.In the second sample one can't get from planet 1 to planet 3 by moving through stargates.

import std.algorithm;
import std.c.stdio;
import std.stdio;
import std.conv;
import std.math;
import std.array;
import std.container;

int curc;
bool eof = false;

void sb()
{
    do
    {
        curc = getchar ();
    }
    while (0 <= curc && curc <= 32);
    if (curc == EOF)
    {
        eof = true;
    }
}

char rc ()
{
    sb ();
    return cast (char) curc;
}

int ni ()
{
    sb ();
    int res = 0;
    do
    {
        res = res * 10 + cast (int) (curc - '0');
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

long nl ()
{
    sb ();
    long res = 0;
    do
    {
        res = res * 10 + cast (long) (curc - '0');
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

char[] ns ()
{
    sb ();
    char[] res = [];
    do
    {
        res ~= to!char(curc);
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

void CFBETA142D()
{
    import std.array;
    alias immutable int[] tuple;
    alias int[int] setint;
    alias long[long] setlong;
    long inf = (1L << 63) - 1;
    auto n = ni(), m = ni();
    int[][] g = new int[][](n, 0);
    int[tuple] weights;
    for (int i=0; i<m; ++i)
    {
        auto a = ni() - 1, b = ni() - 1, w = ni();
        weights[cast(tuple)[a,b]] = w;
        weights[cast(tuple)[b,a]] = w;
        g[a] ~= b;
        g[b] ~= a;
    }
    setlong[] t = new setlong[n];
    for (int i=0; i<n-1; ++i)
    {
        auto k = ni();
        int[] tmp = new int[k];
        for (int j = 0; j < k; ++j)
            tmp[j] = ni();
        for (int j = k - 1; j >= 0; --j)
        {
            auto p = (tmp[j] + 1) in t[i];
            if (p is null)
                t[i][tmp[j]] = tmp[j] + 1;
            else
                t[i][tmp[j]] = t[i][tmp[j] + 1];
        }
    }
    long get(long i, long time)
    {
        if ((time in t[cast(uint)i]) is null) return time;
        else return t[cast(uint)i][time];
    }
    long[] planets = new long[n];
    for (auto i=0; i<n; ++i) planets[i] = inf;
    planets[0] = get(0, 0);
    struct S
    {
        int v;
        int opCmp(ref const S s) const
        {
            if (planets[v] == planets[s.v])
                return v - s.v;
            else
                return planets[v] > planets[s.v] ? 1 : -1;
        }
    }
    auto q = redBlackTree!("a < b", true)(cast(S)0);
    while (!q.empty())
    {
        auto v = q.front().v;
        q.removeFront();
        foreach (int to; g[v])
        {
            auto len = weights[cast(tuple)[v, to]];
            if (get(to, planets[v] + len) < planets[to])
            {
                q.removeKey(cast(S)to);
                planets[to] = get(to, planets[v] + len);
                q.insert(cast(S)to);
            }
        }
    }
    writeln(planets[n - 1] == inf ? -1 : planets[n - 1]);
}

void main()
{
    CFBETA142D();
}

import std.algorithm;
import std.c.stdio;
import std.stdio;
import std.conv;
import std.math;
import std.array;
import std.container;

int curc;
bool eof = false;

void sb()
{
    do
    {
        curc = getchar ();
    }
    while (0 <= curc && curc <= 32);
    if (curc == EOF)
    {
        eof = true;
    }
}

char rc ()
{
    sb ();
    return cast (char) curc;
}

int ni ()
{
    sb ();
    int res = 0;
    do
    {
        res = res * 10 + cast (int) (curc - '0');
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

long nl ()
{
    sb ();
    long res = 0;
    do
    {
        res = res * 10 + cast (long) (curc - '0');
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

char[] ns ()
{
    sb ();
    char[] res = [];
    do
    {
        res ~= to!char(curc);
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

void CFBETA142D()
{
    import std.array;
    alias immutable int[] tuple;
    alias int[int] setint;
    alias long[long] setlong;
    long inf = (1L << 63) - 1;
    auto n = ni(), m = ni();
    int[][] g = new int[][](n, 0);
    int[tuple] weights;
    for (int i=0; i<m; ++i)
    {
        auto a = ni() - 1, b = ni() - 1, w = ni();
        weights[cast(tuple)[a,b]] = w;
        weights[cast(tuple)[b,a]] = w;
        g[a] ~= b;
        g[b] ~= a;
    }
    setlong[] t = new setlong[n];
    for (int i=0; i<n-1; ++i)
    {
        auto k = ni();
        int[] tmp = new int[k];
        for (int j = 0; j < k; ++j)
            tmp[j] = ni();
        for (int j = k - 1; j >= 0; --j)
        {
            auto p = (tmp[j] + 1) in t[i];
            if (p is null)
                t[i][tmp[j]] = tmp[j] + 1;
            else
                t[i][tmp[j]] = t[i][tmp[j] + 1];
        }
    }
    long get(long i, long time)
    {
        if ((time in t[cast(uint)i]) is null) return time;
        else return t[cast(uint)i][time];
    }
    long[] planets = new long[n];
    for (auto i=0; i<n; ++i) planets[i] = inf;
    planets[0] = get(0, 0);
    struct S
    {
        int v;
        int opCmp(ref const S s) const
        {
            if (planets[v] == planets[s.v])
                return v - s.v;
            else
                return planets[v] > planets[s.v] ? 1 : -1;
        }
    }
    auto q = redBlackTree!("a < b", false)(cast(S)0);
    while (!q.empty())
    {
        auto v = q.front().v;
        q.removeFront();
        foreach (int to; g[v])
        {
            auto len = weights[cast(tuple)[v, to]];
            if (get(to, planets[v] + len) < planets[to])
            {
                q.removeKey(cast(S)to);
                planets[to] = get(to, planets[v] + len);
                q.insert(cast(S)to);
            }
        }
    }
    writeln(planets[n - 1] == inf ? -1 : planets[n - 1]);
}

void main()
{
    CFBETA142D();
}

import std.algorithm;
import std.c.stdio;
import std.stdio;
import std.conv;
import std.math;
import std.array;
import std.container;

int curc;
bool eof = false;

void sb()
{
    do
    {
        curc = getchar ();
    }
    while (0 <= curc && curc <= 32);
    if (curc == EOF)
    {
        eof = true;
    }
}

char rc ()
{
    sb ();
    return cast (char) curc;
}

int ni ()
{
    sb ();
    int res = 0;
    do
    {
        res = res * 10 + cast (int) (curc - '0');
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

long nl ()
{
    sb ();
    long res = 0;
    do
    {
        res = res * 10 + cast (long) (curc - '0');
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

char[] ns ()
{
    sb ();
    char[] res = [];
    do
    {
        res ~= to!char(curc);
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

void CFBETA142D()
{
    import std.array;
    alias immutable int[] tuple;
    alias int[int] setint;
    alias long[long] setlong;
    long inf = (1L << 63) - 1;
    auto n = ni(), m = ni();
    int[][] g = new int[][](n, 0);
    int[tuple] weights;
    for (int i=0; i<m; ++i)
    {
        auto a = ni() - 1, b = ni() - 1, w = ni();
        weights[cast(tuple)[a,b]] = w;
        weights[cast(tuple)[b,a]] = w;
        g[a] ~= b;
        g[b] ~= a;
    }
    setlong[] t = new setlong[n];
    for (int i=0; i<n; ++i)
    {
        auto k = ni();
        int[] tmp = new int[k];
        for (int j = 0; j < k; ++j)
            tmp[j] = ni();
        for (int j = k - 1; j >= 0; --j)
        {
            auto p = (tmp[j] + 1) in t[i];
            if (p is null)
                t[i][tmp[j]] = tmp[j] + 1;
            else
                t[i][tmp[j]] = t[i][tmp[j] + 1];
        }
    }
    long get(long i, long time)
    {
        if ((time in t[cast(uint)i]) is null) return time;
        else return t[cast(uint)i][time];
    }
    long[] planets = new long[n];
    for (auto i=0; i<n; ++i) planets[i] = inf;
    planets[0] = t[0] !is null ? t[0][0] : 0;
    struct S
    {
        int v;
        int opCmp(ref const S s) const
        {
            if (planets[v] == planets[s.v])
                return v - s.v;
            else
                return planets[v] > planets[s.v] ? 1 : -1;
        }
    }
    auto q = redBlackTree!("a < b", true)(cast(S)0);
    while (!q.empty())
    {
        auto v = q.front().v;
        q.removeFront();
        foreach (int to; g[v])
        {
            auto len = weights[cast(tuple)[v, to]];
            if (get(to, planets[v] + len) < planets[to])
            {
                q.removeKey(cast(S)to);
                planets[to] = get(to, planets[v] + len);
                q.insert(cast(S)to);
            }
        }
    }
    writeln(planets[n - 1] == inf ? -1 : planets[n - 1]);
}

void main()
{
    CFBETA142D();
}


You are given an array $$$a$$$ of $$$n$$$ non-negative integers. In one operation you can change any number in the array to any other non-negative integer.Let's define the cost of the array as $$$\operatorname{DIFF}(a) - \operatorname{MEX}(a)$$$, where $$$\operatorname{MEX}$$$ of a set of non-negative integers is the smallest non-negative integer not present in the set, and $$$\operatorname{DIFF}$$$ is the number of different numbers in the array.For example, $$$\operatorname{MEX}(\{1, 2, 3\}) = 0$$$, $$$\operatorname{MEX}(\{0, 1, 2, 4, 5\}) = 3$$$.You should find the minimal cost of the array $$$a$$$ if you are allowed to make at most $$$k$$$ operations.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^5$$$, $$$0 \le k \le 10^5$$$) — the length of the array $$$a$$$ and the number of operations that you are allowed to make. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output a single integer — minimal cost that it is possible to get making at most $$$k$$$ operations.

NoteIn the first test case no operations are needed to minimize the value of $$$\operatorname{DIFF} - \operatorname{MEX}$$$.In the second test case it is possible to replace $$$5$$$ by $$$1$$$. After that the array $$$a$$$ is $$$[0,\, 2,\, 4,\, 1]$$$, $$$\operatorname{DIFF} = 4$$$, $$$\operatorname{MEX} = \operatorname{MEX}(\{0, 1, 2, 4\}) = 3$$$, so the answer is $$$1$$$.In the third test case one possible array $$$a$$$ is $$$[4,\, 13,\, 0,\, 0,\, 13,\, 1,\, 2]$$$, $$$\operatorname{DIFF} = 5$$$, $$$\operatorname{MEX} = 3$$$.In the fourth test case one possible array $$$a$$$ is $$$[1,\, 2,\, 3,\, 0,\, 0,\, 0]$$$.

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

void main ()
{
	auto tests = readln.strip.to !(int);
multitest_loop:
	foreach (test; 0..tests)
	{
		int n, k;
		readf !(" %s %s") (n, k);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		sort (a);
		auto b = a.group.array;

		if (k >= n)
		{
			writeln (0);
			continue multitest_loop;
		}

		auto cnt = new int [n + 1];
		auto pilesOfSize = new int [n + 2];
		auto haveSizes = redBlackTree !(int);
		int extras = 0;
		foreach (ref g; b)
		{
			debug {writeln (g);}
			auto cur = g[1].to !(int);
			if (g[0] <= n)
			{
				cnt[g[0]] = cur;
			}
			else
			{
				pilesOfSize[cur] += 1;
				haveSizes.insert (cur);
				extras += 1;
			}
		}

		int gaps = 0;
		foreach (mex; 0..n + 1)
		{
			gaps += (cnt[mex] == 0);
		}

		int res = n;
		foreach_reverse (mex; 0..n + 1)
		{
			scope (exit)
			{
				if (cnt[mex] > 0)
				{
					pilesOfSize[cnt[mex]] += 1;
					haveSizes.insert (cnt[mex]);
					extras += 1;
				}
			}

			gaps -= (cnt[mex] == 0);
			if (gaps > k)
			{
				continue;
			}
			debug {writeln ("mex = ", mex, ", extras = ", extras);}

			if (cnt[mex] > k)
			{
				continue;
			}
			int kRem = k - cnt[mex];

			int diff = mex + extras;
			foreach (i; haveSizes)
			{
				int cur = pilesOfSize[i];
				int toTake = min (cur, k / i);
				diff -= toTake;
				k -= toTake * i;
				if (toTake < cur)
				{
					break;
				}
 			}
			debug {writeln (diff, " ", mex, " ", extras);}
			res = min (res, diff - mex);
		}

		writeln (res);
	}
}


This is an interactive problem.This is an easy version of the problem. The difference from the hard version is that in the easy version $$$t=1$$$ and the number of queries is limited to $$$20$$$.Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the $$$k$$$-th zero from the left $$$t$$$ times.Polycarp can make no more than $$$20$$$ requests of the following type:   ? $$$l$$$ $$$r$$$ — find out the sum of all elements in positions from $$$l$$$ to $$$r$$$ ($$$1 \le l \le r \le n$$$) inclusive. In this (easy version) of the problem, this paragraph doesn't really make sense since $$$t=1$$$ always. To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the $$$k$$$-th zero was $$$x$$$, then after Polycarp guesses this position, the $$$x$$$-th element of the array will be replaced from $$$0$$$ to $$$1$$$. Of course, this feature affects something only for $$$t>1$$$.Help Polycarp win the game.

NoteIn the first test, the $$$[1, 0, 1, 1, 0, 1]$$$ array is hidden. In this test $$$k=2$$$.

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); }

T binarySearch(alias pred, T)(T ok, T ng)
{
	while (abs(ok-ng) > 1)
	{
		auto mid = (ok+ng)/2;
		if (unaryFun!pred(mid)) ok = mid;
		else ng = mid;
	}
	return ok;
}

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

	bool f(int x)
	{
		writeln("? 1 ", x);
		stdout.flush;
		auto r = RD;
		auto zero = x - r;
		return zero >= k;
	}

	auto ans = binarySearch!(f)(n+1, 0);

	writeln("! ", ans);
	stdout.flush;
	debug readln;
}

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

int main(string[] args)
{
    auto ret = readln.strip.split(" ").map!(to!int).array;
    auto n = ret[0];
    auto k = to!int(readln.strip);
    auto res = 0;
    auto left = 1, right = n;
    while (left <= right)
    {
        auto mid = (left + right) >> 1;
        writeln("? 1 ", mid);
        stdout.flush;
        auto sum = to!int(readln.strip);
        if (mid - sum < k)
        {
            left = mid + 1;
        }
        else
        {
            right = mid - 1;
            res = mid;
        }
    }
    writeln("! ", res);
    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)); }
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); }

T binarySearch(alias pred, T)(T ok, T ng)
{
	while (abs(ok-ng) > 1)
	{
		auto mid = (ok+ng)/2;
		if (unaryFun!pred(mid)) ok = mid;
		else ng = mid;
	}
	return ok;
}

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

	bool f(int x)
	{
		writeln("? 1 ", x);
		stdout.flush;
		auto r = RD;
		auto zero = x - r;
		return zero >= k;
	}

	auto ans = binarySearch!(f)(n+1, 1);

	writeln("! ", ans);
	stdout.flush;
	debug readln;
}


You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer q. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circles around the hotel. Let us remind you that a number's divisor is called non-trivial if it is different from one and from the divided number itself. The first person who can't make a move wins as he continues to lie in his warm bed under three blankets while the other one keeps running. Determine which player wins considering that both players play optimally. If the first player wins, print any winning first move.

The first line contains the only integer q (1 ≤ q ≤ 1013). Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.

In the first line print the number of the winning player (1 or 2). If the first player wins then the second line should contain another integer — his first move (if the first player can't even make the first move, print 0). If there are multiple solutions, print any of them.

NoteNumber 6 has only two non-trivial divisors: 2 and 3. It is impossible to make a move after the numbers 2 and 3 are written, so both of them are winning, thus, number 6 is the losing number. A player can make a move and write number 6 after number 30; 6, as we know, is a losing number. Thus, this move will bring us the victory.

import std.stdio;
import std.conv;
import std.string;
import std.typecons;
import std.algorithm;
import std.array;
import std.range;
import std.math;
import std.regex;

void main()
{
	auto n = readln().chomp().to!long();

	auto cnt = 0;
	long[] prim;

	for (long i = 2; i < sqrt(n.to!float) + 1; i++) {
		while (n % i == 0) {
			n /= i;
			cnt++;
			if (cnt > 2) break;
			prim ~= i;
		}
	}

	if (n != 1) {
		prim ~= n;
		cnt++;
	}

	if (cnt == 2) writeln("2");
	else if (cnt > 2) writeln("1\n", prim[0] * prim[1]);
	else writeln("1\n0");

}

import std.stdio;
import std.conv;
import std.string;
import std.typecons;
import std.algorithm;
import std.array;
import std.range;
import std.math;
import std.regex;

void main()
{
	auto n = readln().chomp().to!int();

	auto cnt = 0;
	int[] prim;
	for (int i = 2; i < sqrt(n.to!float()) + 1; i++) {
		if (n % i == 0) {
			cnt++;
			if (cnt > 2) break;
			prim ~= i;
		}
	}

	if (cnt == 0) writeln("1\n0");
	else if (cnt == 2) writeln("2");
	else writeln("1\n", prim.reduce!("a * b"));
}

import std.stdio;
import std.conv;
import std.string;
import std.typecons;
import std.algorithm;
import std.array;
import std.range;
import std.math;
import std.regex;

void main()
{
	auto n = readln().chomp().to!long();

	auto cnt = 0;
	long[] prim;
	for (long i = 2; i < sqrt(n.to!float()) + 1; i++) {
		if (n % i == 0) {
			cnt++;
			if (cnt > 2) break;
			prim ~= i;
		}
	}

	if (cnt == 2) writeln("2");
	else if (cnt > 2) writeln("1\n", prim.reduce!("a * b"));
	else writeln("1\n0");

}

import std.stdio;
import std.conv;
import std.string;
import std.typecons;
import std.algorithm;
import std.array;
import std.range;
import std.math;
import std.regex;

void main()
{
	auto n = readln().chomp().to!long();

	auto cnt = 0;
	long[] prim;

	if (n % 2 == 0 && n != 2) {
		n /= 2;
		prim ~= 2;
		cnt++;
	}

	for (long i = 3; i < sqrt(n.to!float) + 1; i+=2) {
		while (n % i == 0) {
			n /= i;
			cnt++;
			if (cnt > 2) break;
			prim ~= i;
		}
	}

	prim ~= n;
	cnt++;

	if (cnt == 2) writeln("2");
	else if (cnt > 2) writeln("1\n", prim[0] * prim[1]);
	else writeln("1\n0");

}

import std.stdio;
import std.conv;
import std.string;
import std.typecons;
import std.algorithm;
import std.array;
import std.range;
import std.math;
import std.regex;

void main()
{
	auto n = readln().chomp().to!long();

	auto cnt = 0;
	long[] prim;

	if (n % 2 == 0 && n != 2) {
		n /= 2;
		prim ~= 2;
		cnt++;
	}

	for (long i = 3; i < sqrt(n.to!float) + 1; i+=2) {
		while (n % i == 0) {
			n /= i;
			cnt++;
			if (cnt > 2) break;
			prim ~= i;
		}
	}

	if (n != 1) {
		prim ~= n;
		cnt++;
	}

	if (cnt == 2) writeln("2");
	else if (cnt > 2) writeln("1\n", prim[0] * prim[1]);
	else writeln("1\n0");

}


There is a square field of size $$$n \times n$$$ in which two cells are marked. These cells can be in the same row or column.You are to mark two more cells so that they are the corners of a rectangle with sides parallel to the coordinate axes.For example, if $$$n=4$$$ and a rectangular field looks like this (there are asterisks in the marked cells):$$$$$$ \begin{matrix} . & . & * & . \\ . & . & . & . \\ * & . & . & . \\ . & . & . & . \\ \end{matrix} $$$$$$Then you can mark two more cells as follows$$$$$$ \begin{matrix} * & . & * & . \\ . & . & . & . \\ * & . & * & . \\ . & . & . & . \\ \end{matrix} $$$$$$If there are several possible solutions, then print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 400$$$). Then $$$t$$$ test cases follow. The first row of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 400$$$) — the number of rows and columns in the table. The following $$$n$$$ lines each contain $$$n$$$ characters '.' or '*' denoting empty and marked cells, respectively. It is guaranteed that the sums of $$$n$$$ for all test cases do not exceed $$$400$$$. It is guaranteed that there are exactly two asterisks on the field. They can be in the same row/column. It is guaranteed that the solution exists.

For each test case, output $$$n$$$ rows of $$$n$$$ characters — a field with four asterisks marked corresponding to the statements. If there multiple correct answers, print any of them.


During a New Year special offer the "Sudislavl Bars" offered n promo codes. Each promo code consists of exactly six digits and gives right to one free cocktail at the bar "Mosquito Shelter". Of course, all the promocodes differ.As the "Mosquito Shelter" opens only at 9, and partying in Sudislavl usually begins at as early as 6, many problems may arise as to how to type a promotional code without errors. It is necessary to calculate such maximum k, that the promotional code could be uniquely identified if it was typed with no more than k errors. At that, k = 0 means that the promotional codes must be entered exactly.A mistake in this problem should be considered as entering the wrong numbers. For example, value "123465" contains two errors relative to promocode "123456". Regardless of the number of errors the entered value consists of exactly six digits.

The first line of the output contains number n (1 ≤ n ≤ 1000) — the number of promocodes. Each of the next n lines contains a single promocode, consisting of exactly 6 digits. It is guaranteed that all the promocodes are distinct. Promocodes can start from digit "0".

Print the maximum k (naturally, not exceeding the length of the promocode), such that any promocode can be uniquely identified if it is typed with at most k mistakes.

NoteIn the first sample k < 3, so if a bar customer types in value "090909", then it will be impossible to define which promocode exactly corresponds to it.

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

immutable int INF = 10L ^^ 9 + 23;

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

    string[] arr;
    foreach (_; 0 .. n) {
        arr ~= readln.chomp;
    }

    int ans = 6;
    foreach (i; 0 .. n) {
        foreach (j; i+1 .. n) {
            int curd = 0;
            foreach (k; 0 .. 6) {
                curd += arr[i][k] != arr[j][k];
            }

            int cur = (curd - 1) / 2;
            ans = min(ans, cur);
        }
    }

    ans.writeln;
}


One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal. The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with size $$$1\times1$$$, Rainbow Dash has an infinite amount of light blue blocks, Fluttershy has an infinite amount of yellow blocks. The blocks are placed according to the following rule: each newly placed block must touch the built on the previous turns figure by a side (note that the outline borders of the grid are built initially). At each turn, one pony can place any number of blocks of her color according to the game rules.Rainbow and Fluttershy have found out that they can build patterns on the grid of the game that way. They have decided to start with something simple, so they made up their mind to place the blocks to form a chess coloring. Rainbow Dash is well-known for her speed, so she is interested in the minimum number of turns she and Fluttershy need to do to get a chess coloring, covering the whole grid with blocks. Please help her find that number!Since the ponies can play many times on different boards, Rainbow Dash asks you to find the minimum numbers of turns for several grids of the games.The chess coloring in two colors is the one in which each square is neighbor by side only with squares of different colors.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of grids of the games.  Each of the next $$$T$$$ lines contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$): the size of the side of the grid of the game.

For each grid of the game print the minimum number of turns required to build a chess coloring pattern out of blocks on it.

NoteFor $$$3\times3$$$ grid ponies can make two following moves:

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

void main () {
	foreach (t; 0..readln.strip.to !(int))
		writeln (readln.strip.to !(int) / 2 + 1);
}

import std.container;
import std.algorithm;
import std.range;
import std.array;
import std.stdio;
import std.utf;
import std.math;
import std.typecons;

alias type = multi;
struct TestCase
{
  mixin prettyPrinting;

  long n;

  void solve(long tc = -1)
  {
    writeln(n / 2 + 1);
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(t[i]);
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}

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 int[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		ans[ti] = n / 2 + 1;
	}

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

import std.container;
import std.algorithm;
import std.range;
import std.array;
import std.stdio;
import std.utf;
import std.math;
import std.typecons;

alias type = multi;
struct TestCase
{
  mixin prettyPrinting;

  long n;

  void solve(long tc = -1)
  {
    if (n % 2 == 0)
      {
        writeln(n / 2 + 1);
      }
    else
      {
        writeln(n - 1);
      }
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

void read(T...)(ref T t)
{
  void basicTypeRead(W)(ref W w)
  {
    import std.stdio: readln;
    while(_words.empty)
      {
        import std.array: split;
        foreach(word; readln.split)
          {
            _words.insertBack(word);
          }
      }
    import std.conv: to;
    string word = _words.front;
    _words.removeFront;
    w = to!W(word);
  }
  void iterableRead(W)(ref W w)
  {
    foreach(ref element; w)
      read(element);
  }
  void tupleRead(W)(ref W w)
  {
    static foreach(j; 0 .. W.length)
      read(w[j]);
  }
  void structRead(W)(ref W readStruct)
  {
    static foreach(fieldName; FieldNameTuple!W)
      {
        with(readStruct)
          {
            alias fieldSymbol = mixin(W.stringof, ".", fieldName);
            alias typeOfField = typeof(mixin(fieldName));
            static if (hasUDA!(fieldSymbol, If))
              enum condition = getUDAs!(fieldSymbol, If)[0].condition;
            else
              enum condition = "true";

            if (mixin(condition))
              {
                static if (hasUDA!(fieldSymbol, Dim))
                  {
                    static assert(isDynamicArray!(typeOfField)
                                  , text(W.stringof, ".", fieldName, " has Dim UDA but isn't a Dynamic Array."));
                    enum uda = getUDAs!(fieldSymbol, Dim)[0];
                    static assert(getArrayLevel!(typeOfField) == uda.levels,
                                  text(W.stringof, ".", fieldName, " has a Dim UDA with different number of dimensions than it's type."));
                    mixin(fieldName) = mixin(q{makeSlice!(baseType!typeOfField)(}, uda.dimensions, q{)});
                  }
                else static if (isDynamicArray!typeOfField && !is(typeOfField == string))
                  {
                    pragma(msg, "Warning: You probably want to add dimension to input ", W.stringof, ".", fieldName);
                  }
                read(mixin(fieldName));
              }
          }
      }
  }
  static foreach(i; 0 .. T.length)
    {
      static if (isBasicType!(T[i]) || is(T[i] == string))
        basicTypeRead(t[i]);
      else static if (is(typeof({foreach(ref e; t[i]){}})))
        iterableRead(t[i]);
      else static if (isTuple!(T[i]))
        tupleRead(t[i]);
      else static if (isAggregateType!(T[i]))
        structRead(t[i]);
    }
}

auto next(T)()
{
  T t;
  read(t);
  return t;
}

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}


The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example:  $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$,  $$$1$$$ is a good number: $$$1 = 3^0$$$,  $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$,  but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$),  $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid),  $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The only line of the query contains one integer $$$n$$$ ($$$1 \le n \le 10^4$$$).

For each query, print such smallest integer $$$m$$$ (where $$$n \le m$$$) that $$$m$$$ is a good number.

// https://codeforces.com/problemset/problem/1249/C1
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main() {
    int[] good;
    for(int mask = 1; mask < (1<<10); mask++) {
        int m = 0;
        for(int bit = 0; bit < 10; bit++) {
            if(mask&(1<<bit)) {
                m += 3^^bit;
            }
        }
        good ~= m;
    }
    foreach(line; stdin.byLine.dropOne) {
        int q = line.chomp.to!int;
        foreach(m; good) {
            if(m >= q) {
                m.writeln;
                break;
            }
        }
    }
}

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 q = RD!int;
	auto ans = new long[](q);

	long[] list = [1];
	while (true)
	{
		auto x = list[$-1] * 3;
		if (x < list[$-1])
			break;
		list ~= x;
	}

	foreach (i; 0..q)
	{
		auto n = RD!int;
		int pos;
		while (list[pos] < n)
		{
			++pos;
		}
		if (pos != 0)
			--pos;
		auto l = 2L^^pos;
		auto r = 2L^^(list.length);
		foreach (j; l..r)
		{
			long x;
			foreach (k; 0..32)
			{
				auto bit = 1L << k;
				if (j & bit)
				{
					x += list[k];
				}
			}
			if (x >= n)
			{
				ans[i] = x;
				break;
			}
		}
	}

	foreach (e; ans)
		writeln(e);

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

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 q = RD!int;
	auto ans = new long[](q);

	long[] list = [1];
	while (true)
	{
		auto x = list[$-1] * 3;
		if (x < list[$-1])
			break;
		list ~= x;
	}
	list.reverse;
	debug writeln("a");

	foreach (loop; 0..q)
	{
		auto n = RD;
		long[] x;
		auto dp = new long[][](list.length+1);
		dp[0] = [0];
		foreach (i; 0..list.length)
		{
			foreach (j; 0..dp[i].length)
			{
				auto tmp = dp[i][j] + list[i];
				if (tmp >= n)
				{
					x ~= tmp;
					dp[i+1] ~= dp[i][j];
				}
				else if (dp[i][j] + list[i]*2 >= n)
				{
					dp[i+1] ~= tmp;
					dp[i+1] ~= dp[i][j];
				}
			}
		}
		debug writeln(x);
		debug writeln(dp);
		ans[loop] = x[x.MIN_POS];
	}

	foreach (e; ans)
		writeln(e);

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

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 q = RD!int;
	auto ans = new long[](q);

	long[] list = [1];
	while (true)
	{
		auto x = list[$-1] * 3;
		if (x < list[$-1])
			break;
		list ~= x;
	}

	foreach (i; 0..q)
	{
		auto n = RD!int;
		int pos;
		while (list[pos] < n)
		{
			++pos;
		}
		if (pos != 0)
			--pos;
		foreach (j; 2^^pos..2^^(list.length))
		{
			long x;
			foreach (k; 0..32)
			{
				auto bit = 1L << k;
				if (j & bit)
				{
					x += list[k];
				}
			}
			if (x >= n)
			{
				ans[i] = x;
				break;
			}
		}
	}

	foreach (e; ans)
		writeln(e);

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

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 q = RD!int;
	auto ans = new long[](q);

	long[] list = [1];
	while (true)
	{
		auto x = list[$-1] * 3;
		if (x < list[$-1])
			break;
		list ~= x;
	}

	foreach (i; 0..q)
	{
		auto n = RD!int;
		int pos;
		while (list[pos] < n)
		{
			++pos;
		}
		if (pos != 0)
			--pos;
		foreach (long j; 2^^pos..2^^(list.length))
		{
			long x;
			foreach (k; 0..32)
			{
				auto bit = 1L << k;
				if (j & bit)
				{
					x += list[k];
				}
			}
			if (x >= n)
			{
				ans[i] = x;
				break;
			}
		}
	}

	foreach (e; ans)
		writeln(e);

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


Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps:  Find any continuous subsequence (substring) of three characters of string q, which doesn't equal to either string "zyx", "xzy", "yxz". If q doesn't contain any such subsequence, terminate the algorithm, otherwise go to step 2.  Rearrange the letters of the found subsequence randomly and go to step 1. Sereja thinks that the algorithm works correctly on string q if there is a non-zero probability that the algorithm will be terminated. But if the algorithm anyway will work for infinitely long on a string, then we consider the algorithm to work incorrectly on this string.Sereja wants to test his algorithm. For that, he has string s = s1s2... sn, consisting of n characters. The boy conducts a series of m tests. As the i-th test, he sends substring slisli + 1... sri (1 ≤ li ≤ ri ≤ n) to the algorithm input. Unfortunately, the implementation of his algorithm works too long, so Sereja asked you to help. For each test (li, ri) determine if the algorithm works correctly on this test or not.

The first line contains non-empty string s, its length (n) doesn't exceed 105. It is guaranteed that string s only contains characters: 'x', 'y', 'z'. The second line contains integer m (1 ≤ m ≤ 105) — the number of tests. Next m lines contain the tests. The i-th line contains a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).

For each test, print "YES" (without the quotes) if the algorithm works correctly on the corresponding test and "NO" (without the quotes) otherwise.

NoteIn the first example, in test one and two the algorithm will always be terminated in one step. In the fourth test you can get string "xzyx" on which the algorithm will terminate. In all other tests the algorithm doesn't work correctly.

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

void main ()
{
	string s;
	while ((s = readln ()) != "")
	{
		s = s.strip ();
		int [] x, y, z;
		x = [0];
		y = [0];
		z = [0];
		foreach (c; s)
		{
			x ~= x[$ - 1] + (c == 'x');
			y ~= y[$ - 1] + (c == 'y');
			z ~= z[$ - 1] + (c == 'z');
		}

		int q;
		readf (" %s", &q);
		foreach (i; 0..q)
		{
			int l, r;
			readf (" %s %s", &l, &r);
			int nx = x[r] - x[l - 1];
			int ny = y[r] - y[l - 1];
			int nz = z[r] - z[l - 1];
			int lo = min (nx, min (ny, nz));
			int hi = max (nx, max (ny, nz));
			writeln ((r - l < 2 || hi - lo <= 1) ? "YES" : "NO");
		}
	}
}

import std.stdio, std.string, std.conv;
import std.algorithm, std.array, std.bigint, std.math, std.range;
import core.thread;

//  Input
string[] tokens;
int tokenId = 0;
string readToken() { for (; tokenId == tokens.length; ) tokens = readln.split, tokenId = 0; return tokens[tokenId++]; }

int readInt() { return to!int(readToken); }
long readLong() { return to!long(readToken); }
real readReal() { return to!real(readToken); }

//  chmin/chmax
void chmin(T)(ref T t, T f) { if (t > f) t = f; }
void chmax(T)(ref T t, T f) { if (t < f) t = f; }

immutable int MAXN = 100005;

int M;
string S;

int[100005][5] dp;

void main () {
    S = readToken();
    M = readInt();

    int A, B;

    foreach(int i; 0 .. to!int(S.length)) {
        dp[to!int(S[i] - 'x')][i + 1] += 1;

        foreach(int j; 0 .. 3) {
            dp[j][i +    1] += dp[j][i];
        }
    }

    foreach (int i; 0 .. M) {
        A = readInt();
        B = readInt();

        if (B - A < 2) {
            writeln("YES");
        } else {
            int[3] buff;

            foreach(int j; 0 .. 3) {
                buff[j] = dp[j][B] - dp[j][A - 1];
            }

            buff.sort;

            if (buff[2] <= buff[0] + 1) {
                writeln("YES");
            } else {
                writeln("NO");
            }
        }
    }
}

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

void main ()
{
	string s;
	while ((s = readln ()) != "")
	{
		s = s.strip ();
		int [] x, y, z;
		x = [0];
		y = [0];
		z = [0];
		foreach (c; s)
		{
			x ~= x[$ - 1] + (c == 'x');
			y ~= y[$ - 1] + (c == 'y');
			z ~= z[$ - 1] + (c == 'z');
		}

		int q;
		readf (" %s", &q);
		foreach (i; 0..q)
		{
			int l, r;
			readf (" %s %s", &l, &r);
			int nx = x[r] - x[l - 1];
			int ny = y[r] - y[l - 1];
			int nz = z[r] - z[l - 1];
			int lo = min (nx, min (ny, nz));
			int hi = max (nx, max (ny, nz));
			writeln ((hi - lo <= 1) ? "YES" : "NO");
		}
	}
}


On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.Help the child to find out, what is the minimum total energy he should spend to remove all n parts.

The first line contains two integers n and m (1 ≤ n ≤ 1000; 0 ≤ m ≤ 2000). The second line contains n integers: v1, v2, ..., vn (0 ≤ vi ≤ 105). Then followed m lines, each line contains two integers xi and yi, representing a rope from part xi to part yi (1 ≤ xi, yi ≤ n; xi ≠ yi). Consider all the parts are numbered from 1 to n.

Output the minimum total energy the child should spend to remove all n parts of the toy.

NoteOne of the optimal sequence of actions in the first sample is:  First, remove part 3, cost of the action is 20.  Then, remove part 2, cost of the action is 10.  Next, remove part 4, cost of the action is 10.  At last, remove part 1, cost of the action is 0. So the total energy the child paid is 20 + 10 + 10 + 0 = 40, which is the minimum.In the second sample, the child will spend 400 no matter in what order he will remove the parts.

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

void main ()
{
	int n;
	int m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto v = new int [n];
		foreach (ref x; v)
		{
			readf (" %s", &x);
		}
		auto a = new int [] [n];
		foreach (k; 0..m)
		{
			int i;
			int j;
			readf (" %s %s", &i, &j);
			i--;
			j--;
			a[i] ~= j;
			a[j] ~= i;
		}

		auto d = n.iota.array;
		sort !((a, b) => v[a] > v[b], SwapStrategy.stable) (d);
		long res = 0;
		foreach (x; d)
		{
			foreach (i; a[x])
			{
				res += v[i];
			}
			v[x] = 0;
		}

		writeln (res);
	}
}


Little C loves number «3» very much. He loves all things about it.Now he has a positive integer $$$n$$$. He wants to split $$$n$$$ into $$$3$$$ positive integers $$$a,b,c$$$, such that $$$a+b+c=n$$$ and none of the $$$3$$$ integers is a multiple of $$$3$$$. Help him to find a solution.

A single line containing one integer $$$n$$$ ($$$3 \leq n \leq 10^9$$$) — the integer Little C has.

Print $$$3$$$ positive integers $$$a,b,c$$$ in a single line, such that $$$a+b+c=n$$$ and none of them is a multiple of $$$3$$$. It can be proved that there is at least one solution. If there are multiple solutions, print any of them.

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

  int n;
  rd(n);
  if (n % 3 < 2) {
    writeln(1, " ", 1, " ", n - 2);
  } else {
    writeln(1, " ", 2, " ", n - 3);
  }
}

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.stdio;
int main()
{
	int a=0;
	readf(" %s", &a);
	for (int i=0; i<a+1; i++)
	{
		if (i%3!=0)
		{
			int b=a-i;
			for (int j=0; j<b+1; j++)
			{
				if (j%3!=0)
				{
					if ((a-i-j)%3!=0)
					{
						writeln(i);
						writeln(j);
						writeln(a-i-j);
						return 0;
					}
				}
			}
		}
	}
	return 0;
}


You are given a sequence $$$a_1, a_2, \dots, a_n$$$, consisting of integers.You can apply the following operation to this sequence: choose some integer $$$x$$$ and move all elements equal to $$$x$$$ either to the beginning, or to the end of $$$a$$$. Note that you have to move all these elements in one direction in one operation.For example, if $$$a = [2, 1, 3, 1, 1, 3, 2]$$$, you can get the following sequences in one operation (for convenience, denote elements equal to $$$x$$$ as $$$x$$$-elements):   $$$[1, 1, 1, 2, 3, 3, 2]$$$ if you move all $$$1$$$-elements to the beginning;  $$$[2, 3, 3, 2, 1, 1, 1]$$$ if you move all $$$1$$$-elements to the end;  $$$[2, 2, 1, 3, 1, 1, 3]$$$ if you move all $$$2$$$-elements to the beginning;  $$$[1, 3, 1, 1, 3, 2, 2]$$$ if you move all $$$2$$$-elements to the end;  $$$[3, 3, 2, 1, 1, 1, 2]$$$ if you move all $$$3$$$-elements to the beginning;  $$$[2, 1, 1, 1, 2, 3, 3]$$$ if you move all $$$3$$$-elements to the end; You have to determine the minimum number of such operations so that the sequence $$$a$$$ becomes sorted in non-descending order. Non-descending order means that for all $$$i$$$ from $$$2$$$ to $$$n$$$, the condition $$$a_{i-1} \le a_i$$$ is satisfied.Note that you have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — the number of the queries. Each query is represented by two consecutive lines. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of elements. The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le n$$$) — the elements. It is guaranteed that the sum of all $$$n$$$ does not exceed $$$3 \cdot 10^5$$$.

For each query print one integer — the minimum number of operation for sorting sequence $$$a$$$ in non-descending order.

NoteIn the first query, you can move all $$$1$$$-elements to the beginning (after that sequence turn into $$$[1, 1, 1, 3, 6, 6, 3]$$$) and then move all $$$6$$$-elements to the end.In the second query, the sequence is sorted initially, so the answer is zero.In the third query, you have to move all $$$2$$$-elements to the beginning.

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, 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)); }

int N;
int[] A;

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        N = readInt();
        A = new int[N];
        foreach (i; 0 .. N) {
          A[i] = readInt() - 1;
        }

        auto ls = new int[N];
        auto rs = new int[N];
        ls[] = N;
        rs[] = -1;
        foreach (i; 0 .. N) {
          chmin(ls[A[i]], i);
          chmax(rs[A[i]], i);
        }

        Tuple!(int, int)[] ps;
        foreach (x; 0 .. N) {
          if (ls[x] <= rs[x]) {
            ps ~= tuple(ls[x], rs[x]);
          }
        }
        debug {
          writeln("ps = ", ps);
        }
        const psLen = cast(int)(ps.length);
        int last = -1;
        int mx;
        foreach (j; 0 .. psLen) {
          if (j == 0 || ps[j - 1][1] > ps[j][0]) {
            last = j;
          }
          chmax(mx, j - last + 1);
        }
        writeln(psLen - mx);
      }
    }
  } catch (EOFException e) {
  }
}

import std.conv, std.functional, std.range, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, 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 bChmax(T)(T[] bit, int pos, T val)
in {
  assert(0 <= pos && pos < bit.length, "bAdd: 0 <= pos < |bit| must hold");
}
do {
  for (int x = pos; x < bit.length; x |= x + 1) {
    chmax(bit[x], val);
  }
}

// max of [0, pos)
T bMax(T)(T[] bit, int pos)
in {
  assert(0 <= pos && pos <= bit.length, "bSum: 0 <= pos <= |bit| must hold");
}
do {
  T sum = 0;
  for (int x = pos - 1; x >= 0; x = (x & (x + 1)) - 1) {
    chmax(sum, bit[x]);
  }
  return sum;
}

int N;
int[] A;

void main() {
  try {
    for (; ; ) {
      const numCases = readInt();
      foreach (caseId; 0 .. numCases) {
        N = readInt();
        A = new int[N];
        foreach (i; 0 .. N) {
          A[i] = readInt() - 1;
        }

        auto ls = new int[N];
        auto rs = new int[N];
        ls[] = N;
        rs[] = -1;
        foreach (i; 0 .. N) {
          chmin(ls[A[i]], i);
          chmax(rs[A[i]], i);
        }
        auto bit = new int[N];
        int ans;
        foreach (i; 0 .. N) {
          if (ls[i] <= rs[i]) {
            ++ans;
            const res = bit.bMax(ls[i]);
            bit.bChmax(rs[i], res + 1);
          }
        }
        ans -= bit.bMax(N);
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}


Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them.

The first line of the input contains a single integer n (1 ≤ n ≤ 500 000) — the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500 000.

Print the resulting hashtags in any of the optimal solutions.

NoteWord a1, a2, ..., am of length m is lexicographically not greater than word b1, b2, ..., bk of length k, if one of two conditions hold:   at first position i, such that ai ≠ bi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ;  if there is no such position i and m ≤ k, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two.

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

immutable int INF = 10L ^^ 9 + 23;

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

    string[] arr;
    foreach (_; 0 .. n) { arr ~= readln.chomp; }

    foreach_reverse (i; 0 .. n-1) {
        int k = 0;
        while (k < min(arr[i].length, arr[i+1].length) && arr[i][k] == arr[i+1][k]) { ++k; }

        if (k < min(arr[i].length, arr[i+1].length) && arr[i][k] < arr[i+1][k]) { continue; }

        arr[i] = arr[i][0 .. k];
    }

    foreach (ref s; arr) { s.writeln; }
}


Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.

The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.

In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.

5
Misha ILoveCodeforces
Vasya Petrov
Petrov VasyaPetrov123
ILoveCodeforces MikeMirzayanov
Petya Ivanov

3
Petya Ivanov
Misha MikeMirzayanov
Vasya VasyaPetrov123

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

string[string] map;

void main() {

	short n;

	scanf("%hd", &n);

	foreach (i; 0 .. n) {
		string a, b, c;
		a = readln(' ').strip();
		b = readln().strip();
		if (a !in map)
			map[a] = a;
		map[b] = map[a];
		map.remove(a);
	}

	writeln(map.length);

	foreach (i; map.keys)
		writeln(map[i], ' ', i);
}

import std.string;
import std.stdio;
import std.array;
void main() {
	int n;
	stdin.readf("%s\n", &n);
	int[string] map;
	string[1001] orig;
	string[1001] rmap;
	int count = 0;
	for (int i = 0; i < n; i++) {
		string line = stdin.readln();
		line = line.stripRight();
		string[] names = line.split();
		int *p = (names[0] in map);
		if (p is null) {
			//New name
			map[names[0]] = count++;
			orig[map[names[0]]] = names[0];
		}
		map[names[1]] = map[names[0]];
		rmap[map[names[0]]] = names[1];
	}
	stdout.writefln("%s", count);
	for (int i = 0; i < count; i++)
		stdout.writefln("%s %s", orig[i], rmap[i]);
}