Vasily the bear has got a sequence of positive integers a1, a2, ..., an. Vasily the Bear wants to write out several numbers on a piece of paper so that the beauty of the numbers he wrote out was maximum. The beauty of the written out numbers b1, b2, ..., bk is such maximum non-negative integer v, that number b1 and b2 and ... and bk is divisible by number 2v without a remainder. If such number v doesn't exist (that is, for any non-negative integer v, number b1 and b2 and ... and bk is divisible by 2v without a remainder), the beauty of the written out numbers equals -1. Tell the bear which numbers he should write out so that the beauty of the written out numbers is maximum. If there are multiple ways to write out the numbers, you need to choose the one where the bear writes out as many numbers as possible.Here expression x and y means applying the bitwise AND operation to numbers x and y. In programming languages C++ and Java this operation is represented by "&", in Pascal — by "and".

The first line contains integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ a1 < a2 < ... < an ≤ 109).

In the first line print a single integer k (k > 0), showing how many numbers to write out. In the second line print k integers b1, b2, ..., bk — the numbers to write out. You are allowed to print numbers b1, b2, ..., bk in any order, but all of them must be distinct. If there are multiple ways to write out the numbers, choose the one with the maximum number of numbers to write out. If there still are multiple ways, you are allowed to print any of them.

import std.stdio, std.string;
import std.random;

int getPosition(T)(T[] arr, int[] index, T tar)
{
    int l = 0, r = index.length - 1, idx = -1;
    while (l <= r)
    {
        int m = (l + r) >> 1;
        if (arr[index[m]] < tar)
        {
            l = m + 1;
        }
        else
        {
            idx = m;
            r = m - 1;
        }
    }
    if (idx == -1)
    {
        idx = index.length;
    }
    return idx;
}

void solve(int[] a)
{
    int[] one[40];
    int[] zero[40];
    foreach (int i; 0 .. 32)
    {
        foreach (int j; 0 .. a.length)
        {
            if ((a[j] & (1 << i)) == 0)
            {
                zero[i] ~= j;
            }
            else
            {
                one[i] ~= j;
            }
        }
    }
    int tar = -1;
    for (int pos = 30; pos >= 0; -- pos)
    {
        if (one[pos].length > 0)
        {
            int i;
            for (i = 0; i < pos; ++ i)
            {
                if (zero[i].length == 0)
                {
                    break;
                }
                int j;
                int idx = getPosition(a, zero[i], 1 << pos);
                for (j = idx; j < zero[i].length; ++ j)
                {
                    if (a[zero[i][j]] & (1 << pos))
                    {
                        break;
                    }
                }
                if (j == zero[i].length)
                {
                    break;
                }
            }
            if (i == pos)
            {
                tar = pos;
                break;
            }
        }
    }
    if (tar == -1)
    {
        writefln("-1");
        return;
    }
    bool[] flag = new bool[a.length];
    int k = 0;
    foreach (int i; 0 .. one[tar].length)
    {
        ++ k;
        flag[one[tar][i]] = true;
    }
    foreach (int i; 0 .. tar)
    {
        foreach (int j; 0 .. zero[i].length)
        {
            if ((a[zero[i][j]] & (1 << tar)) && flag[zero[i][j]] == false)
            {
                ++ k;
                flag[zero[i][j]] = true;
            }
        }
    }
    foreach (int i; 0 .. a.length)
    {
        if (flag[i] == false && (a[i] & (1 << tar)) != 0)
        {
            ++ k;
            flag[i] = true;
        }
    }
    writefln("%d", k);
    foreach (int i; 0 .. a.length)
    {
        if (flag[i] == true)
        {
            writef("%d ", a[i]);
        }
    }
    writefln("");
}

void main(string[] args)
{
    int n;
    while (scanf("%d", &n) == 1)
    {
        int[] a = new int[n];
        foreach (int i; 0 .. n)
        {
            //a[i] = uniform(0, 1000000000) + 1;
            //a[i] = 1000000000 - i;
            scanf("%d", &a[i]);
        }
        solve(a);
    }
}

import std.stdio, std.string;
import std.random;

void solve(int[] a)
{
	int[] one[40];
	int[] zero[40];
	foreach (int i; 0 .. 32)
	{
		foreach (int j; 0 .. a.length)
		{
			if ((a[j] & (1 << i)) == 0)
			{
				zero[i] ~= j;
			}
			else
			{
				one[i] ~= j;
			}
		}
	}
	int tar = -1;
	for (int pos = 30; pos >= 0; -- pos)
	{
		if (one[pos].length > 0)
		{
			int i;
			for (i = 0; i < pos; ++ i)
			{
				if (zero[i].length == 0)
				{
					break;
				}
				int j;
				for (j = 0; j < zero[i].length; ++ j)
				{
					if (a[zero[i][j]] & (1 << pos))
					{
						break;
					}
				}
				if (j == zero[i].length)
				{
					break;
				}
			}
			if (i == pos)
			{
				tar = pos;
				break;
			}
		}
	}
	if (tar == -1)
	{
		writefln("-1");
		return;
	}
	bool[] flag = new bool[a.length];
	int k = 0;
	foreach (int i; 0 .. one[tar].length)
	{
		++ k;
		flag[one[tar][i]] = true;
	}
	foreach (int i; 0 .. tar)
	{
		foreach (int j; 0 .. zero[i].length)
		{
			if ((a[zero[i][j]] & (1 << tar)) && flag[zero[i][j]] == false)
			{
				++ k;
				flag[zero[i][j]] = true;
			}
		}
	}
	foreach (int i; 0 .. a.length)
	{
		if (flag[i] == false && (a[i] & (1 << tar)) != 0)
		{
			++ k;
			flag[i] = true;
		}
	}
	writefln("%d", k);
	foreach (int i; 0 .. a.length)
	{
		if (flag[i] == true)
		{
			writef("%d ", a[i]);
		}
	}
	writefln("");
}

void main(string[] args)
{
	int n;
	while (scanf("%d", &n) == 1)
	{
		int[] a = new int[n];
		foreach (int i; 0 .. n)
		{
			//a[i] = uniform(0, 1000000000) + 1;
			//a[i] = 1000000000 - i;
			scanf("%d", &a[i]);
		}
		solve(a);
	}
}

import std.stdio, std.string;
import std.random;

void solve(int[] a)
{
    int[] one[40];
    int[] zero[40];
    foreach (int i; 0 .. 32)
    {
        foreach (int j; 0 .. a.length)
        {
            if ((a[j] & (1 << i)) == 0)
            {
                zero[i] ~= j;
            }
            else
            {
                one[i] ~= j;
            }
        }
    }
    int tar = -1;
    for (int pos = 30; pos >= 0; -- pos)
    {
        if (one[pos].length > 0)
        {
            int i;
            for (i = 0; i < pos; ++ i)
            {
                if (zero[i].length == 0)
                {
                    break;
                }
                int j;
                for (j = 0; j < zero[i].length; ++ j)
                {
                    if (a[zero[i][j]] & (1 << pos))
                    {
                        break;
                    }
                }
                if (j == zero[i].length)
                {
                    break;
                }
            }
            if (i == pos)
            {
                tar = pos;
                break;
            }
        }
    }
    if (tar == -1)
    {
        writefln("-1");
        return;
    }
    bool[] flag = new bool[a.length];
    int k = 0;
    foreach (int i; 0 .. one[tar].length)
    {
        ++ k;
        flag[one[tar][i]] = true;
    }
    foreach (int i; 0 .. tar)
    {
        foreach (int j; 0 .. zero[i].length)
        {
            if ((a[zero[i][j]] & (1 << tar)) && flag[zero[i][j]] == false)
            {
                ++ k;
                flag[zero[i][j]] = true;
            }
        }
    }
    writefln("%d", k);
    foreach (int i; 0 .. a.length)
    {
        if (flag[i] == true)
        {
            writef("%d ", a[i]);
        }
    }
    writefln("");
}

void main(string[] args)
{
    int n;
    while (scanf("%d", &n) == 1)
    {
        int[] a = new int[n];
        foreach (int i; 0 .. n)
        {
            //a[i] = uniform(0, 1000000000) + 1;
            //a[i] = 1000000000 - i;
            scanf("%d", &a[i]);
        }
        solve(a);
    }
}

import std.stdio, std.string;
import std.random;

int getPosition(T)(T[] arr, int[] index, T tar)
{
    int l = 0, r = index.length - 1, idx = -1;
    while (l <= r)
    {
        int m = (l + r) >> 1;
        if (arr[index[m]] < tar)
        {
            l = m + 1;
        }
        else
        {
            idx = m;
            r = m - 1;
        }
    }
    if (idx == -1)
    {
        idx = index.length;
    }
    return idx;
}

void solve(int[] a)
{
    int[] one[40];
    int[] zero[40];
    foreach (int i; 0 .. 32)
    {
        foreach (int j; 0 .. a.length)
        {
            if ((a[j] & (1 << i)) == 0)
            {
                zero[i] ~= j;
            }
            else
            {
                one[i] ~= j;
            }
        }
    }
    int tar = -1;
    for (int pos = 30; pos >= 0; -- pos)
    {
        if (one[pos].length > 0)
        {
            int i;
            for (i = 0; i < pos; ++ i)
            {
                if (zero[i].length == 0)
                {
                    break;
                }
                int j;
                int idx = getPosition(a, zero[i], 1 << pos);
                for (j = idx; j < zero[i].length; ++ j)
                {
                    if (a[zero[i][j]] & (1 << pos))
                    {
                        break;
                    }
                }
                if (j == zero[i].length)
                {
                    break;
                }
            }
            if (i == pos)
            {
                tar = pos;
                break;
            }
        }
    }
    if (tar == -1)
    {
        writefln("-1");
        return;
    }
    bool[] flag = new bool[a.length];
    int k = 0;
    foreach (int i; 0 .. one[tar].length)
    {
        ++ k;
        flag[one[tar][i]] = true;
    }
    foreach (int i; 0 .. tar)
    {
        foreach (int j; 0 .. zero[i].length)
        {
            if ((a[zero[i][j]] & (1 << tar)) && flag[zero[i][j]] == false)
            {
                ++ k;
                flag[zero[i][j]] = true;
            }
        }
    }
    /*foreach (int i; 0 .. a.length)
    {
        if (flag[i] == false && (a[i] & (1 << tar)) != 0)
        {
            ++ k;
            flag[i] = true;
        }
    }*/
    writefln("%d", k);
    foreach (int i; 0 .. a.length)
    {
        if (flag[i] == true)
        {
            writef("%d ", a[i]);
        }
    }
    writefln("");
}

void main(string[] args)
{
    int n;
    while (scanf("%d", &n) == 1)
    {
        int[] a = new int[n];
        foreach (int i; 0 .. n)
        {
            //a[i] = uniform(0, 1000000000) + 1;
            //a[i] = 1000000000 - i;
            scanf("%d", &a[i]);
        }
        solve(a);
    }
}


Two kittens, Max and Min, play with a pair of non-negative integers x and y. As you can guess from their names, kitten Max loves to maximize and kitten Min loves to minimize. As part of this game Min wants to make sure that both numbers, x and y became negative at the same time, and kitten Max tries to prevent him from doing so.Each kitten has a set of pairs of integers available to it. Kitten Max has n pairs of non-negative integers (ai, bi) (1 ≤ i ≤ n), and kitten Min has m pairs of non-negative integers (cj, dj) (1 ≤ j ≤ m). As kitten Max makes a move, it can take any available pair (ai, bi) and add ai to x and bi to y, and kitten Min can take any available pair (cj, dj) and subtract cj from x and dj from y. Each kitten can use each pair multiple times during distinct moves.Max moves first. Kitten Min is winning if at some moment both numbers a, b are negative simultaneously. Otherwise, the winner of the game is kitten Max. Determine which kitten wins if both of them play optimally.

The first line contains two integers, n and m (1 ≤ n, m ≤ 100 000) — the number of pairs of numbers available to Max and Min, correspondingly. The second line contains two integers x, y (1 ≤ x, y ≤ 109) — the initial values of numbers with which the kittens are playing. Next n lines contain the pairs of numbers ai, bi (1 ≤ ai, bi ≤ 109) — the pairs available to Max. The last m lines contain pairs of numbers cj, dj (1 ≤ cj, dj ≤ 109) — the pairs available to Min.

Print «Max» (without the quotes), if kitten Max wins, or "Min" (without the quotes), if kitten Min wins.

NoteIn the first test from the statement Min can respond to move (2, 3) by move (3, 10), and to move (3, 2) by move (10, 3). Thus, for each pair of Max and Min's moves the values of both numbers x and y will strictly decrease, ergo, Min will win sooner or later.In the second sample test after each pair of Max and Min's moves both numbers x and y only increase, thus none of them will become negative.

import std.algorithm, std.range, std.stdio, std.typecons;
alias Point = Tuple !(long, q{x}, int, q{y}, int, q{t});
void main ()
{
    int n, m;
    readf (" %s %s ", &n, &m);
    readln ();
    auto p = new Point [n + m];
    foreach (i, ref c; p)
    {
        readf (" %s %s", &c.x, &c.y);
        c.t = (i >= n);
    }
    p ~= Point (p[n..$].minPos!q{a.x > b.x}.front.x, 0, 1);
    p ~= Point (0, p[n..$].minPos!q{a.y > b.y}.front.y, 1);
    sort !((a, b) => (a.x * b.y < a.y * b.x) ||
        ((a.x * b.y == a.y * b.x) && (a.x + a.y < b.x + b.y))) (p);
    Point [] q, s;
    foreach (c; p)
    {
        if (q.length > 0 && c.x == q[$ - 1].x && c.y == q[$ - 1].y)
            q[$ - 1].t &= c.t;
        else
            q ~= c;
    }
    foreach (c; q)
    {
        while (s.length > 1 &&
            (s[$ - 1].x - s[$ - 2].x) * (c.y - s[$ - 2].y) >
            (s[$ - 1].y - s[$ - 2].y) * (c.x - s[$ - 2].x))
            s.length--;
        s.assumeSafeAppend ();
        s ~= c;
    }
    writeln (s.all!q{a.t == 1} ? "Min" : "Max");
}

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;

alias Point = Tuple !(int, q{x}, int, q{y}, int, q{t});

void main ()
{
	int n, m;
	while (readf (" %s %s ", &n, &m) > 0)
	{
		readln ();
		auto p = new Point [n + m + 2];
		int xmax = int.min;
		int ymax = int.min;
		foreach (i; 0..n + m)
		{
			readf (" %s %s", &p[i].x, &p[i].y);
			p[i].t = (i >= n);
			if (i >= n)
			{
				xmax = max (xmax, p[i].x);
				ymax = max (ymax, p[i].y);
			}
		}
		p[n + m + 0] = Point (xmax, 0, 1);
		p[n + m + 1] = Point (0, ymax, 1);
		sort !((a, b) => (a.x * 1L * b.y < a.y * 1L * b.x) ||
		    ((a.x * 1L * b.y == a.y * 1L * b.x) &&
		    (a.x + a.y < b.x + b.y)),
		    SwapStrategy.stable) (p);

		Point [] q;
		foreach (c; p)
		{
			if (q.length > 0 &&
			    c.x == q[$ - 1].x &&
			    c.y == q[$ - 1].y)
			{
				q[$ - 1].t &= c.t;
			}
			else
			{
				q ~= c;
			}
		}
		p = q;
		debug {writeln (p.map !(to !(string)).join ("\n"));}
		debug {writeln ();}

		Point [] s;
		s.reserve (n + m + 4);
		foreach (c; p)
		{
			while (s.length > 1 &&
			    (s[$ - 1].x - s[$ - 2].x) * 1L *
			    (c.y - s[$ - 2].y) >
			    (s[$ - 1].y - s[$ - 2].y) * 1L *
			    (c.x - s[$ - 2].x))
			{
				s.length--;
			}
			s.assumeSafeAppend ();
			s ~= c;
		}
		debug {writeln (s.map !(to !(string)).join ("\n"));}

		writeln (all !(a => a.t == 1) (s) ? "Min" : "Max");
	}
}


Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm.Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current sequence and adds them c times to the end. More formally, if we represent the current sequence as a1, a2, ..., an, then after we apply the described operation, the sequence transforms into a1, a2, ..., an[, a1, a2, ..., al] (the block in the square brackets must be repeated c times). A day has passed and Sereja has completed the sequence. He wonders what are the values of some of its elements. Help Sereja.

The first line contains integer m (1 ≤ m ≤ 105) — the number of stages to build a sequence.  Next m lines contain the description of the stages in the order they follow. The first number in the line is a type of stage (1 or 2). Type 1 means adding one number to the end of the sequence, in this case the line contains integer xi (1 ≤ xi ≤ 105) — the number to add. Type 2 means copying a prefix of length li to the end ci times, in this case the line further contains two integers li, ci (1 ≤ li ≤ 105, 1 ≤ ci ≤ 104), li is the length of the prefix, ci is the number of copyings. It is guaranteed that the length of prefix li is never larger than the current length of the sequence. The next line contains integer n (1 ≤ n ≤ 105) — the number of elements Sereja is interested in. The next line contains the numbers of elements of the final sequence Sereja is interested in. The numbers are given in the strictly increasing order. It is guaranteed that all numbers are strictly larger than zero and do not exceed the length of the resulting sequence. Consider the elements of the final sequence numbered starting from 1 from the beginning to the end of the sequence. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

Print the elements that Sereja is interested in, in the order in which their numbers occur in the input.

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;

immutable int MAX_L = 100_005;
immutable int NA = -1;

void main ()
{
	int m;
	while (readf (" %s", &m) > 0)
	{
		int [] f;
		auto len = new long [m + 1];
		len[0] = 0L;
		auto v = new int [m + 1];
		auto l = new int [m + 1];
		auto c = new int [m + 1];
		foreach (i; 1..m + 1)
		{
			int t;
			readf (" %s", &t);
			if (t == 1)
			{
				readf (" %s", &v[i]);
				l[i] = c[i] = NA;
				len[i] = len[i - 1] + 1;
				if (f.length < MAX_L)
				{
					f ~= v[i];
				}
			}
			else if (t == 2)
			{
				readf (" %s %s", &l[i], &c[i]);
				v[i] = NA;
				len[i] = len[i - 1] + l[i] * c[i];
j_loop:				foreach (j; 0..c[i])
				{
					foreach (k; 0..l[i])
					{
						if (f.length >= MAX_L)
						{
							break j_loop;
						}
						f ~= f[k];
					}
				}
			}
			else
			{
				enforce (false);
			}
		}

		int [] res;
		int n;
		readf (" %s", &n);
		foreach (i; 0..n)
		{
			long r;
			readf (" %s", &r);
			int lo = 0;
			int hi = m;
			while (lo < hi)
			{
				int me = (lo + hi) >> 1;
				if (len[me] < r)
				{
					lo = me + 1;
				}
				else
				{
					hi = me;
				}
			}
			enforce (lo > 0);
			if (v[lo] != NA)
			{
				res ~= v[lo];
			}
			else
			{
				r -= len[lo - 1] + 1;
				r %= l[lo];
				res ~= f[to !(int) (r)];
			}
		}
		writefln ("%(%s %)", res);
	}
}


Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.The boy started to memorize the order of the flags' colours that he had seen. But soon he fell asleep again. Unfortunately, he didn't sleep long, he woke up and went on memorizing the colours. Then he fell asleep again, and that time he slept till the end of the journey.At the station he told his parents about what he was doing, and wrote two sequences of the colours that he had seen before and after his sleep, respectively.Peter's parents know that their son likes to fantasize. They give you the list of the flags' colours at the stations that the train passes sequentially on the way from A to B, and ask you to find out if Peter could see those sequences on the way from A to B, or from B to A. Remember, please, that Peter had two periods of wakefulness.Peter's parents put lowercase Latin letters for colours. The same letter stands for the same colour, different letters — for different colours.

The input data contains three lines. The first line contains a non-empty string, whose length does not exceed 105, the string consists of lowercase Latin letters — the flags' colours at the stations on the way from A to B. On the way from B to A the train passes the same stations, but in reverse order.  The second line contains the sequence, written by Peter during the first period of wakefulness. The third line contains the sequence, written during the second period of wakefulness. Both sequences are non-empty, consist of lowercase Latin letters, and the length of each does not exceed 100 letters. Each of the sequences is written in chronological order.

Output one of the four words without inverted commas:    «forward» — if Peter could see such sequences only on the way from A to B;  «backward» — if Peter could see such sequences on the way from B to A;  «both» — if Peter could see such sequences both on the way from A to B, and on the way from B to A;  «fantasy» — if Peter could not see such sequences.

NoteIt is assumed that the train moves all the time, so one flag cannot be seen twice. There are no flags at stations A and 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 input = readln().chomp();
  auto p1 = readln().chomp();
  auto p2 = readln().chomp();

  auto f1 = match(input, p1 ~ ".*" ~ p2);
  auto f2 = match(input, p2.retro().text ~ ".*" ~ p1.retro().text);

  if (f1 && f2) writeln("both");
  else if (f1) writeln("forward");
  else if (f2) writeln("backward");
  else writeln("fantasy");
}


You are given array $$$a_1, a_2, \ldots, a_n$$$, consisting of non-negative integers.Let's define operation of "elimination" with integer parameter $$$k$$$ ($$$1 \leq k \leq n$$$) as follows:  Choose $$$k$$$ distinct array indices $$$1 \leq i_1 < i_2 < \ldots < i_k \le n$$$.  Calculate $$$x = a_{i_1} ~ \& ~ a_{i_2} ~ \& ~ \ldots ~ \& ~ a_{i_k}$$$, where $$$\&$$$ denotes the bitwise AND operation (notes section contains formal definition).  Subtract $$$x$$$ from each of $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$; all other elements remain untouched. Find all possible values of $$$k$$$, such that it's possible to make all elements of array $$$a$$$ equal to $$$0$$$ using a finite number of elimination operations with parameter $$$k$$$. It can be proven that exists at least one possible $$$k$$$ for any array $$$a$$$.Note that you firstly choose $$$k$$$ and only after that perform elimination operations with value $$$k$$$ you've chosen initially.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i < 2^{30}$$$) — array $$$a$$$ itself. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$200\,000$$$.

For each test case, print all values $$$k$$$, such that it's possible to make all elements of $$$a$$$ equal to $$$0$$$ in a finite number of elimination operations with the given parameter $$$k$$$. Print them in increasing order.

NoteIn the first test case:  If $$$k = 1$$$, we can make four elimination operations with sets of indices $$$\{1\}$$$, $$$\{2\}$$$, $$$\{3\}$$$, $$$\{4\}$$$. Since $$$\&$$$ of one element is equal to the element itself, then for each operation $$$x = a_i$$$, so $$$a_i - x = a_i - a_i = 0$$$.  If $$$k = 2$$$, we can make two elimination operations with, for example, sets of indices $$$\{1, 3\}$$$ and $$$\{2, 4\}$$$: $$$x = a_1 ~ \& ~ a_3$$$ $$$=$$$ $$$a_2 ~ \& ~ a_4$$$ $$$=$$$ $$$4 ~ \& ~ 4 = 4$$$. For both operations $$$x = 4$$$, so after the first operation $$$a_1 - x = 0$$$ and $$$a_3 - x = 0$$$, and after the second operation — $$$a_2 - x = 0$$$ and $$$a_4 - x = 0$$$.  If $$$k = 3$$$, it's impossible to make all $$$a_i$$$ equal to $$$0$$$. After performing the first operation, we'll get three elements equal to $$$0$$$ and one equal to $$$4$$$. After that, all elimination operations won't change anything, since at least one chosen element will always be equal to $$$0$$$.  If $$$k = 4$$$, we can make one operation with set $$$\{1, 2, 3, 4\}$$$, because $$$x = a_1 ~ \& ~ a_2 ~ \& ~ a_3 ~ \& ~ a_4$$$ $$$= 4$$$. In the second test case, if $$$k = 2$$$ then we can make the following elimination operations:  Operation with indices $$$\{1, 3\}$$$: $$$x = a_1 ~ \& ~ a_3$$$ $$$=$$$ $$$13 ~ \& ~ 25 = 9$$$. $$$a_1 - x = 13 - 9 = 4$$$ and $$$a_3 - x = 25 - 9 = 16$$$. Array $$$a$$$ will become equal to $$$[4, 7, 16, 19]$$$.  Operation with indices $$$\{3, 4\}$$$: $$$x = a_3 ~ \& ~ a_4$$$ $$$=$$$ $$$16 ~ \& ~ 19 = 16$$$. $$$a_3 - x = 16 - 16 = 0$$$ and $$$a_4 - x = 19 - 16 = 3$$$. Array $$$a$$$ will become equal to $$$[4, 7, 0, 3]$$$.  Operation with indices $$$\{2, 4\}$$$: $$$x = a_2 ~ \& ~ a_4$$$ $$$=$$$ $$$7 ~ \& ~ 3 = 3$$$. $$$a_2 - x = 7 - 3 = 4$$$ and $$$a_4 - x = 3 - 3 = 0$$$. Array $$$a$$$ will become equal to $$$[4, 4, 0, 0]$$$.  Operation with indices $$$\{1, 2\}$$$: $$$x = a_1 ~ \& ~ a_2$$$ $$$=$$$ $$$4 ~ \& ~ 4 = 4$$$. $$$a_1 - x = 4 - 4 = 0$$$ and $$$a_2 - x = 4 - 4 = 0$$$. Array $$$a$$$ will become equal to $$$[0, 0, 0, 0]$$$. Formal definition of bitwise AND:Let's define bitwise AND ($$$\&$$$) as follows. Suppose we have two non-negative integers $$$x$$$ and $$$y$$$, let's look at their binary representations (possibly, with leading zeroes): $$$x_k \dots x_2 x_1 x_0$$$ and $$$y_k \dots y_2 y_1 y_0$$$. Here, $$$x_i$$$ is the $$$i$$$-th bit of number $$$x$$$, and $$$y_i$$$ is the $$$i$$$-th bit of number $$$y$$$. Let $$$r = x ~ \& ~ y$$$ is a result of operation $$$\&$$$ on number $$$x$$$ and $$$y$$$. Then binary representation of $$$r$$$ will be $$$r_k \dots r_2 r_1 r_0$$$, where:$$$$$$ r_i = \begin{cases} 1, ~ \text{if} ~ x_i = 1 ~ \text{and} ~ y_i = 1 \\ 0, ~ \text{if} ~ x_i = 0 ~ \text{or} ~ y_i = 0 \end{cases} $$$$$$

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

// https://www.geeksforgeeks.org/find-divisors-natural-number-set-1/
long[] SortedDivisors(long n)
{
  long[] ans;
  for (long i = 1; i * i <= n; i++) {
    if (n % i == 0) {
      // If divisors are equal, print only one
      if (n/i == i) {
        ans ~= i;
      } else { // Otherwise print both
        ans ~= i;
        ans ~= n / i;
      }
    }
  }
  ans.sort;
  return ans;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!long;
    auto a = readln.strip.split.map!(to!long).array;
    long tmp = long.max;
    long[32] cnt;
    foreach (x ; a) {
      foreach (i ; 0 .. 32) {
        if (x & (1L << i))
          cnt[i]++;
      }
    }
    long[] filtered_cnt;
    foreach (i ; 0 .. 32) {
      if (cnt[i] != 0)
        filtered_cnt ~= cnt[i];
    }
    if (filtered_cnt.length == 0) {
      writeln(iota(1, n + 1).map!text.join(" "));
    } else {
      long ans = filtered_cnt[0];
      foreach (x ; filtered_cnt)
        ans = gcd(ans, x);
      writeln(SortedDivisors(ans).map!text.join(" "));
    }
  }
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto cnt = new long[](30);
		foreach (i; 0..n)
		{
			foreach (j; 0..30)
			{
				auto bit = 1L << j;
				if (a[i] & bit)
					++cnt[j];
			}
		}

		foreach (i; 1..n+1)
		{
			bool ok = true;
			foreach (j; 0..30)
			{
				if (cnt[j] % i)
					ok = false;
			}
			if (ok)
				ans[ti] ~= i;
		}
	}

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

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto a = ma(n, readInt!int);
	int ans = 0;
	foreach(i; 0 .. 30)
	{
		int count = 0;
		foreach(ai; a) if (ai & (1 << i)) count++;
		ans = gcd(ans, count);
	}
	if (ans == 0)
	{
		foreach(i; 1 .. n + 1) write(i, " ");
		writeln;
		return;
	}
	foreach(i; 1 .. ans + 1)
	{
		if (ans % i == 0) write(i, " ");
	}
	writeln;
}

//{{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
//}}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	import core.stdc.stdio;
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
	{
		popChar;
	}
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}

import core.bitop;
import std.algorithm;
import std.conv;
import std.numeric;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		int k = 0;
		foreach (z; 0..30)
		{
			int v = 0;
			foreach (i; 0..n)
			{
				v += (a[i] >> z) & 1;
			}
			k = gcd (k, v);
		}
		writefln !("%(%s %)") (iota (1, n + 1)
		    .filter !(c => k % c == 0));
	}
}

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

// https://www.geeksforgeeks.org/find-divisors-natural-number-set-1/
long[] SortedDivisors(long n)
{
  long[] ans;
  for (long i = 1; i * i <= n; i++) {
    if (n % i == 0) {
      // If divisors are equal, print only one
      if (n/i == i) {
        ans ~= i;
      } else { // Otherwise print both
        ans ~= i;
        ans ~= n / i;
      }
    }
  }
  ans.sort;
  return ans;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    auto n = readln.strip.to!long;
    auto a = readln.strip.split.map!(to!long).array;
    long tmp = long.max;
    long[32] cnt;
    foreach (x ; a) {
      foreach (i ; 0 .. 32) {
        if (x & (1L << i))
          cnt[i]++;
      }
    }
    long[] filtered_cnt;
    foreach (i ; 0 .. 32) {
      if (cnt[i] != 0)
        filtered_cnt ~= cnt[i];
    }
    if (filtered_cnt.length == 0) {
      writeln(n);
    } else {
      long ans = filtered_cnt[0];
      foreach (x ; filtered_cnt)
        ans = gcd(ans, x);
      writeln(SortedDivisors(ans).map!text.join(" "));
    }
  }
}


Polycarp found under the Christmas tree an array $$$a$$$ of $$$n$$$ elements and instructions for playing with it:   At first, choose index $$$i$$$ ($$$1 \leq i \leq n$$$) — starting position in the array. Put the chip at the index $$$i$$$ (on the value $$$a_i$$$).  While $$$i \leq n$$$, add $$$a_i$$$ to your score and move the chip $$$a_i$$$ positions to the right (i.e. replace $$$i$$$ with $$$i + a_i$$$).  If $$$i > n$$$, then Polycarp ends the game. For example, if $$$n = 5$$$ and $$$a = [7, 3, 1, 2, 3]$$$, then the following game options are possible:   Polycarp chooses $$$i = 1$$$. Game process: $$$i = 1 \overset{+7}{\longrightarrow} 8$$$. The score of the game is: $$$a_1 = 7$$$.  Polycarp chooses $$$i = 2$$$. Game process: $$$i = 2 \overset{+3}{\longrightarrow} 5 \overset{+3}{\longrightarrow} 8$$$. The score of the game is: $$$a_2 + a_5 = 6$$$.  Polycarp chooses $$$i = 3$$$. Game process: $$$i = 3 \overset{+1}{\longrightarrow} 4 \overset{+2}{\longrightarrow} 6$$$. The score of the game is: $$$a_3 + a_4 = 3$$$.  Polycarp chooses $$$i = 4$$$. Game process: $$$i = 4 \overset{+2}{\longrightarrow} 6$$$. The score of the game is: $$$a_4 = 2$$$.  Polycarp chooses $$$i = 5$$$. Game process: $$$i = 5 \overset{+3}{\longrightarrow} 8$$$. The score of the game is: $$$a_5 = 3$$$. Help Polycarp to find out the maximum score he can get if he chooses the starting index in an optimal way.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the array $$$a$$$. The next line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output on a separate line one number — the maximum score that Polycarp can get by playing the game on the corresponding array according to the instruction from the statement. Note that Polycarp chooses any starting position from $$$1$$$ to $$$n$$$ in such a way as to maximize his result.

NoteThe first test case is explained in the statement.In the second test case, the maximum score can be achieved by choosing $$$i = 1$$$.In the third test case, the maximum score can be achieved by choosing $$$i = 2$$$.In the fourth test case, the maximum score can be achieved by choosing $$$i = 1$$$.

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

string FMT_F = "%.10f";

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

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

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

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

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

		auto score = new long[](n);
		foreach_reverse (i; 0..n)
		{
			score[i] = a[i];
			auto j = cast(int)(i + a[i]);
			if (j < n)
			{
				score[i] += score[j];
			}
		}

		ans[ti] = score.maxElement;
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto v = new int [n];
		foreach_reverse (i; 0..n)
		{
			auto j = i + a[i];
			v[i] = a[i] + (j >= n ? 0 : v[j]);
		}
		writeln (v.maxElement);
	}
}


Analyzing the mistakes people make while typing search queries is a complex and an interesting work. As there is no guaranteed way to determine what the user originally meant by typing some query, we have to use different sorts of heuristics.Polycarp needed to write a code that could, given two words, check whether they could have been obtained from the same word as a result of typos. Polycarpus suggested that the most common typo is skipping exactly one letter as you type a word.Implement a program that can, given two distinct words S and T of the same length n determine how many words W of length n + 1 are there with such property that you can transform W into both S, and T by deleting exactly one character. Words S and T consist of lowercase English letters. Word W also should consist of lowercase English letters.

The first line contains integer n (1 ≤ n ≤ 100 000) — the length of words S and T. The second line contains word S. The third line contains word T. Words S and T consist of lowercase English letters. It is guaranteed that S and T are distinct words.

Print a single integer — the number of distinct words W that can be transformed to S and T due to a typo.

NoteIn the first sample test the two given words could be obtained only from word "treading" (the deleted letters are marked in bold).In the second sample test the two given words couldn't be obtained from the same word by removing one letter.In the third sample test the two given words could be obtained from either word "tory" or word "troy".

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

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

    string[] s;
    foreach (i; 0 .. 2) { s ~= readln.chomp; }

    debug { s.writeln; }

    int chk(int ix1) {
        int section = 1;
        int it1 = 0, it2 = 0;
        while (it1 < n && it2 < n) {
            if (s[ix1][it1] == s[1-ix1][it2]) {
                it1 += 1;
                it2 += 1;
                continue;
            }

            if (section == 1) {
                section += 1;
                it1 += 1;
            } else if (section == 2) {
                section += 1;
                it2 += 1;
            } else {
                return 0;
            }
        }

        return 1;
    }

    int ans = chk(0) + chk(1);

    ans.writeln;
}

import std.range;
import std.stdio;
import std.string;

void main ()
{
	int n;
	while (readf (" %s ", &n) > 0)
	{
		auto s = readln ().strip ();
		auto t = readln ().strip ();
		while (!s.empty && s.front == t.front)
		{
			s.popFront ();
			t.popFront ();
		}
		while (!s.empty && s.back == t.back)
		{
			s.popBack ();
			t.popBack ();
		}
		writeln ((s[1..$] == t[0..$ - 1]) + (s[0..$ - 1] == t[1..$]));
	}
}


Wu got hungry after an intense training session, and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset $$$S$$$ of vertices of the left half we define $$$N(S)$$$ as the set of all vertices of the right half adjacent to at least one vertex in $$$S$$$, and $$$f(S)$$$ as the sum of all numbers in vertices of $$$N(S)$$$. Find the greatest common divisor of $$$f(S)$$$ for all possible non-empty subsets $$$S$$$ (assume that GCD of empty set is $$$0$$$).Wu is too tired after his training to solve this problem. Help him!

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 500\,000$$$) — the number of test cases in the given test set. Test case descriptions follow. The first line of each case description contains two integers $$$n$$$ and $$$m$$$ ($$$1~\leq~n,~m~\leq~500\,000$$$) — the number of vertices in either half of the graph, and the number of edges respectively. The second line contains $$$n$$$ integers $$$c_i$$$ ($$$1 \leq c_i \leq 10^{12}$$$). The $$$i$$$-th number describes the integer in the vertex $$$i$$$ of the right half of the graph. Each of the following $$$m$$$ lines contains a pair of integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$), describing an edge between the vertex $$$u_i$$$ of the left half and the vertex $$$v_i$$$ of the right half. It is guaranteed that the graph does not contain multiple edges. Test case descriptions are separated with empty lines. The total value of $$$n$$$ across all test cases does not exceed $$$500\,000$$$, and the total value of $$$m$$$ across all test cases does not exceed $$$500\,000$$$ as well.

For each test case print a single integer — the required greatest common divisor.

NoteThe greatest common divisor of a set of integers is the largest integer $$$g$$$ such that all elements of the set are divisible by $$$g$$$.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and $$$f(S)$$$ for any non-empty subset is $$$2$$$, thus the greatest common divisor of these values if also equal to $$$2$$$.In the second sample case the subset $$$\{1\}$$$ in the left half is connected to vertices $$$\{1, 2\}$$$ of the right half, with the sum of numbers equal to $$$2$$$, and the subset $$$\{1, 2\}$$$ in the left half is connected to vertices $$$\{1, 2, 3\}$$$ of the right half, with the sum of numbers equal to $$$3$$$. Thus, $$$f(\{1\}) = 2$$$, $$$f(\{1, 2\}) = 3$$$, which means that the greatest common divisor of all values of $$$f(S)$$$ is $$$1$$$.

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

immutable int limit = 10 ^^ 6;

long [] h;

void prepare ()
{
	rndGen.seed (126346);
	h = [];
	h.reserve (limit);
	foreach (i; 0..limit)
	{
		h ~= uniform (0, 10L ^^ 18);
	}
}

void main ()
{
	prepare ();

	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		readln;
		auto c = readln.splitter.map !(to !(long)).array;
		auto z = new long [n];
		foreach (j; 0..m)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			z[v] ^= h[u];
		}
		long [long] x;
		foreach (v; 0..n)
		{
			x[z[v]] += c[v];
		}
		x.remove (0);
		debug {writeln (x);}
		writeln (x.byValue.fold !(gcd));
	}
}

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

immutable int limit = 10 ^^ 6;

long [] h;

void prepare ()
{
	rndGen.seed (126346);
	h = [];
	h.reserve (limit);
	foreach (i; 0..limit)
	{
		h ~= uniform (0, 10L ^^ 18);
	}
}

void main ()
{
	prepare ();

	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		readln;
		auto c = readln.splitter.map !(to !(long)).array;
		auto z = new long [n];
		foreach (j; 0..m)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			z[v] ^= h[u];
		}
		long [long] x;
		foreach (v; 0..n)
		{
			x[z[v]] += c[v];
		}
		writeln (x.byValue.fold !(gcd));
	}
}


You are given a directed graph with n nodes and m edges, with all edges having a certain weight. There might be multiple edges and self loops, and the graph can also be disconnected. You need to choose a path (possibly passing through same vertices multiple times) in the graph such that the weights of the edges are in strictly increasing order, and these edges come in the order of input. Among all such paths, you need to find the the path that has the maximum possible number of edges, and report this value.Please note that the edges picked don't have to be consecutive in the input.

The first line contains two integers n and m (1 ≤ n ≤ 100000,1 ≤ m ≤ 100000) — the number of vertices and edges in the graph, respectively.  m lines follows.  The i-th of these lines contains three space separated integers ai, bi and wi (1 ≤ ai, bi ≤ n, 0 ≤ wi ≤ 100000), denoting an edge from vertex ai to vertex bi having weight wi

Print one integer in a single line — the maximum number of edges in the path.

NoteThe answer for the first sample input is 2: . Note that you cannot traverse  because edge  appears earlier in the input than the other two edges and hence cannot be picked/traversed after either of the other two edges.In the second sample, it's optimal to pick 1-st, 3-rd and 5-th edges to get the optimal answer: .

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

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}

void main()
{
  int n, m; readV(n, m);

  struct WL { int w, l; }
  alias rbt = RedBlackTree!(WL, "a.w < b.w");

  auto dp = new rbt[](n);
  foreach (i; 0..n) dp[i] = new rbt([WL(-1, 0)]);

  auto ans = 0;
  foreach (_; 0..m) {
    int u, v, w; readV(u, v, w); --u; --v;
    auto s = dp[u].lowerBound(WL(w, 0)).back, nl = s.l+1;
    ans = max(ans, nl);

    auto t = dp[v].lowerBound(WL(w+1, 0)).back;
    if (t.l >= nl) continue;

    dp[v].insert(WL(w, nl));
    dp[v].removeKey(dp[v].upperBound(WL(w, 0)).filter!(wl => wl.l < nl));
  }

  writeln(ans);
}

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

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

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

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

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

      // incr w, incr val
      alias Entry = Tuple!(int, "w", int, "val");
      auto sets = new RedBlackTree!Entry[N];
      foreach (u; 0 .. N) {
        sets[u] = new RedBlackTree!Entry;
      }
      auto dp = new int[M];
      foreach (i; 0 .. M) {
        // w < W[i]
        auto ranA = sets[A[i]].lowerBound(Entry(W[i], -1));
        if (!ranA.empty) {
          dp[i] = ranA.back.val;
        }
        dp[i] += 1;
        // insert
        auto ranL = sets[B[i]].lowerBound(Entry(W[i], M + 1));
        if (!ranL.empty && ranL.back.val >= dp[i]) {
          continue;
        }
        auto ranR = sets[B[i]].upperBound(Entry(W[i], -1));
        Entry[] rems;
        foreach (e; ranR) {
          if (dp[i] >= e.val) {
            rems ~= e;
          } else {
            break;
          }
        }
        foreach (e; rems) {
          sets[B[i]].removeKey(e);
        }
        sets[B[i]].insert(Entry(W[i], dp[i]));
      }
      debug {
        writeln("dp = ", dp);
      }
      const ans = dp.maxElement;
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}

void main()
{
  int n, m; readV(n, m);

  struct WL { int w, l; }
  alias rbt = RedBlackTree!(WL, "a.w < b.w");

  auto dp = new rbt[](n);
  foreach (i; 0..n) dp[i] = new rbt([WL(-1, 0)]);

  auto ans = 0;
  foreach (_; 0..m) {
    int u, v, w; readV(u, v, w); --u; --v;
    auto s = dp[u].lowerBound(WL(w, 0)).back, nl = s.l+1;
    ans = max(ans, nl);

    auto t = dp[v].lowerBound(WL(w+1, 0)).back;
    if (t.l >= nl) continue;

    dp[v].insert(WL(w, nl));
  }

  writeln(ans);
}


Some company is going to hold a fair in Byteland. There are $$$n$$$ towns in Byteland and $$$m$$$ two-way roads between towns. Of course, you can reach any town from any other town using roads.There are $$$k$$$ types of goods produced in Byteland and every town produces only one type. To hold a fair you have to bring at least $$$s$$$ different types of goods. It costs $$$d(u,v)$$$ coins to bring goods from town $$$u$$$ to town $$$v$$$ where $$$d(u,v)$$$ is the length of the shortest path from $$$u$$$ to $$$v$$$. Length of a path is the number of roads in this path.The organizers will cover all travel expenses but they can choose the towns to bring goods from. Now they want to calculate minimum expenses to hold a fair in each of $$$n$$$ towns.

There are $$$4$$$ integers $$$n$$$, $$$m$$$, $$$k$$$, $$$s$$$ in the first line of input ($$$1 \le n \le 10^{5}$$$, $$$0 \le m \le 10^{5}$$$, $$$1 \le s \le k \le min(n, 100)$$$) — the number of towns, the number of roads, the number of different types of goods, the number of different types of goods necessary to hold a fair. In the next line there are $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_{i} \le k$$$), where $$$a_i$$$ is the type of goods produced in the $$$i$$$-th town. It is guaranteed that all integers between $$$1$$$ and $$$k$$$ occur at least once among integers $$$a_{i}$$$. In the next $$$m$$$ lines roads are described. Each road is described by two integers $$$u$$$ $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$) — the towns connected by this road. It is guaranteed that there is no more than one road between every two towns. It is guaranteed that you can go from any town to any other town via roads.

Print $$$n$$$ numbers, the $$$i$$$-th of them is the minimum number of coins you need to spend on travel expenses to hold a fair in town $$$i$$$. Separate numbers with spaces.

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

void main ()
{
	int n, m, k, s;
	while (readf (" %s %s %s %s", &n, &m, &k, &s) > 0)
	{
		readln;
		auto w = readln.splitter.map !(to !(int)).array;
		w[] -= 1;
		auto a = new int [] [n];
		foreach (j; 0..m)
		{
			int u, v;
			readf (" %s %s", &u, &v);
			u -= 1;
			v -= 1;
			a[u] ~= v;
			a[v] ~= u;
		}

		auto q = new int [n];
		int qb, qe;
		auto d = new int [] [] (n, k);
		auto d0 = new int [] [] (k, n);
		foreach (ref line; d0)
		{
			line[] = int.max;
		}

		foreach (v; 0..k)
		{
			auto cd = d0[v];
			qb = 0;
			qe = 0;
			foreach (i; 0..n)
			{
				if (w[i] == v)
				{
					cd[i] = 0;
					q[qe++] = i;
				}
			}
			while (qb < qe)
			{
				int i = q[qb++];
				auto r = cd[i] + 1;
				foreach (j; a[i])
				{
					if (cd[j] == int.max)
					{
						cd[j] = r;
						q[qe++] = j;
					}
				}
			}
		}

		foreach (i; 0..n)
		{
			foreach (j; 0..k)
			{
				d[i][j] = d0[j][i];
			}
		}

		auto ans = new int [n];
		foreach (i; 0..n)
		{
			topN (d[i], s - 1);
			ans[i] = sum (d[i][0..s]);
		}
		writefln ("%(%s %)", ans);
	}
}

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

import std.container;
alias Edge = SList!int;

void main() {
  int n, m, k, s;
  readf (" %d %d %d %d", &n, &m, &k, &s);
  auto a = new int[n];
  auto h = new Edge[k];
  foreach (i; 0 .. n) {
    readf (" %d", &a[i]);
    --a[i];
    h[a[i]].insert (i);
  }
  auto e = new Edge[n];
  foreach (t; 0 .. m) {
    int i, j;
    readf (" %d %d", &i, &j);
    --i; --j;
    e[i].insert(j);
    e[j].insert(i);
  }
  auto c = new int[][] (k, n);
  auto q = new int[n];
  auto age = new int[n];
  age[] = -1;
  foreach (t; 0 .. k) {
    int left, right;
    auto d = c[t];
    foreach (i; h[t]) {
      d[i] = 0;
      age[i] = t;
      q[right++] = i;
    }
    while (left != right) {
      auto i = q[left++];
      foreach (j; e[i]) {
        if (age[j] != t) {
          age[j] = t;
          d[j] = d[i] + 1;
          q[right++] = j;
        }
      }
    }
  }
  auto res = new int[n];
  auto g = new int[k];
  int r = k - s;
  foreach (i; 0 .. n) {
    foreach (j; 0 .. k) g[j] = c[j][i];
    if (s < r) {
      partialSort (g, s);
      res[i] = g[0 .. s].sum;
    } else {
      partialSort! ("a > b") (g, r);
      res[i] = g[r .. k].sum;
    }
  }
  writeln (res.map! (i => i.text).join(' '));
}

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

import std.container;
alias Edge = SList!int;

void main() {
  int n, m, k, s;
  readf (" %d %d %d %d", &n, &m, &k, &s);
  auto a = new int[n];
  auto h = new Edge[k];
  foreach (i; 0 .. n) {
    readf (" %d", &a[i]);
    --a[i];
    h[a[i]].insert (i);
  }
  auto e = new Edge[n];
  foreach (t; 0 .. m) {
    int i, j;
    readf (" %d %d", &i, &j);
    --i; --j;
    e[i].insert(j);
    e[j].insert(i);
  }
  auto c = new int[][] (k, n);
  auto q = new int[n];
  auto age = new int[n];
  age[] = -1;
  foreach (t; 0 .. k) {
    int left, right;
    auto d = c[t];
    foreach (i; h[t]) {
      d[i] = 0;
      age[i] = t;
      q[right++] = i;
    }
    while (left != right) {
      auto i = q[left++];
      foreach (j; e[i]) {
        if (age[j] != t) {
          age[j] = t;
          d[j] = d[i] + 1;
          q[right++] = j;
        }
      }
    }
  }
  auto res = new int[n];
  auto g = new int[k];
  int r = k - s;
  foreach (i; 0 .. n) {
    foreach (j; 0 .. k) g[j] = c[j][i];
    if (s < r) {
      topN (g, s - 1);
      res[i] = g[0 .. s].sum;
    } else {
      if (r > 0) {
        topN! ("a > b") (g, r);
      }
      res[i] = g[r .. k].sum;
    }
  }
  writeln (res.map! (i => i.text).join(' '));
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt();
      const K = readInt();
      const S = readInt();
      auto A = new int[N];
      foreach (u; 0 .. N) {
        A[u] = readInt() - 1;
      }
      auto U = new int[M];
      auto V = new int[M];
      foreach (i; 0 .. M) {
        U[i] = readInt() - 1;
        V[i] = readInt() - 1;
      }

      auto G = new int[][N];
      foreach (i; 0 .. M) {
        G[U[i]] ~= V[i];
        G[V[i]] ~= U[i];
      }

      auto ds = new int[][](N, K);
      auto que = new int[N];
      auto dist = new int[N];
      foreach (k; 0 .. K) {
        int qb, qe;
        dist[] = N;
        foreach (u; 0 .. N) {
          if (A[u] == k) {
            dist[u] = 0;
            que[qe++] = u;
          }
        }
        for (; qb != qe; ) {
          const u = que[qb++];
          foreach (v; G[u]) {
            if (chmin(dist[v], dist[u] + 1)) {
              que[qe++] = v;
            }
          }
        }
        foreach (u; 0 .. N) {
          ds[u][k] = dist[u];
        }
      }

      foreach (u; 0 .. N) {
        if (u > 0) write(" ");
        ds[u].sort;
        const ans = ds[u][0 .. S].sum;
        write(ans);
      }
      writeln();
    }
  } catch (EOFException e) {
  }
}

import std.stdio;
import std.range;
import std.array;
import std.string;
import std.conv;
import std.typecons;
import std.algorithm;
import std.container;
import std.typecons;
import std.random;
import std.csv;
import std.regex;
import std.math;
import core.time;
import std.ascii;
import std.digest.sha;
import std.outbuffer;
import std.numeric;
import std.bigint;
import core.checkedint;

void main()
{
	int n, m, k, s;
	readln.chomp.split.tie(n, m, k, s);
	int[] a = readln.chomp.split.map!(to!int).map!(a => a -1).array;
	int[][] adj = new int[][](n);
	foreach (i; 0..m) {
		int u, v;
		readln.chomp.split.tie(u, v);
		--u;
		--v;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	int[][] types = new int[][](k);
	foreach (int i, t; a) {
		types[t] ~= i;
	}
	int[][] dist = new int[][](k, n);
	foreach (i; 0..k) {
		dist[i] []= int.max;
		int[] queue;
		foreach (j; types[i]) {
			queue ~= j;
			dist[i][j] = 0;
		}
		while (queue.length) {
			int node = queue.front;
			queue = queue[1..$];
			foreach (next; adj[node]) {
				if (dist[i][next] <= dist[i][node] + 1) {
					continue;
				}
				dist[i][next] = dist[i][node] + 1;
				queue ~= next;
			}
		}
	}
	foreach (i; 0..n) {
		int[] arr = new int[](k);
		foreach (j; 0..k) {
			arr[j] = dist[j][i];
		}
		std.algorithm.sort(arr);
		int ans = arr[0..s].sum;
		if (i) write = " ";
		ans.write;
	}
	writeln;
}

void tie(R, Args...)(R arr, ref Args args)
		if (isRandomAccessRange!R || isArray!R)
in
{
	assert (arr.length == args.length);
}
body
{
	foreach (i, ref v; args) {
		alias T = typeof(v);
		v = arr[i].to!T;
	}
}

void verbose(Args...)(in Args args)
{
	stderr.write("[");
	foreach (i, ref v; args) {
		if (i) stderr.write(", ");
		stderr.write(v);
	}
	stderr.writeln("]");
}


Given $$$n$$$ strings, each of length $$$2$$$, consisting of lowercase Latin alphabet letters from 'a' to 'k', output the number of pairs of indices $$$(i, j)$$$ such that $$$i < j$$$ and the $$$i$$$-th string and the $$$j$$$-th string differ in exactly one position.In other words, count the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$.The answer may not fit into 32-bit integer type, so you should use 64-bit integers like long long in C++ to avoid integer overflow.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of strings. Then follows $$$n$$$ lines, the $$$i$$$-th of which containing a single string $$$s_i$$$ of length $$$2$$$, consisting of lowercase Latin letters from 'a' to 'k'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a single integer — the number of pairs $$$(i, j)$$$ ($$$i < j$$$) such that the $$$i$$$-th string and the $$$j$$$-th string have exactly one position $$$p$$$ ($$$1 \leq p \leq 2$$$) such that $$${s_{i}}_{p} \neq {s_{j}}_{p}$$$.  Please note, that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).

4
6
ab
cb
db
aa
cc
ef
7
aa
bb
cc
ac
ca
bb
aa
4
kk
kk
ab
ab
5
jf
jf
jk
jk
jk

NoteFor the first test case the pairs that differ in exactly one position are: ("ab", "cb"), ("ab", "db"), ("ab", "aa"), ("cb", "db") and ("cb", "cc").For the second test case the pairs that differ in exactly one position are: ("aa", "ac"), ("aa", "ca"), ("cc", "ac"), ("cc", "ca"), ("ac", "aa") and ("ca", "aa").For the third test case, the are no pairs satisfying the conditions.

import std;

immutable int total = 11;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		int [total] [total] c;
		foreach (i; 0..n)
		{
			auto s = readln.strip;
			auto u = (s[0] - 'a');
			auto v = (s[1] - 'a');
			c[u][v] += 1;
		}
		long res = 0;
		foreach (u; 0..total)
		{
			foreach (v; 0..total)
			{
				foreach (x; 0..total)
				{
					foreach (y; 0..total)
					{
						if ((u == x) ^ (v == y))
						{
							res += c[u][v] * 1L *
							    c[x][y];
						}
					}
				}
			}
		}
		writeln (res / 2);
	}
}


It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin.We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can carry only one bottle at once each. For both Adil and Bera the process looks as follows:   Choose to stop or to continue to collect bottles.  If the choice was to continue then choose some bottle and walk towards it.  Pick this bottle and walk to the recycling bin.  Go to step 1. Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles.They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin.

First line of the input contains six integers ax, ay, bx, by, tx and ty (0 ≤ ax, ay, bx, by, tx, ty ≤ 109) — initial positions of Adil, Bera and recycling bin respectively. The second line contains a single integer n (1 ≤ n ≤ 100 000) — the number of bottles on the ground. Then follow n lines, each of them contains two integers xi and yi (0 ≤ xi, yi ≤ 109) — position of the i-th bottle. It's guaranteed that positions of Adil, Bera, recycling bin and all bottles are distinct.

Print one real number — the minimum possible total distance Adil and Bera need to walk in order to put all bottles into recycling bin. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct if .

NoteConsider the first sample.Adil will use the following path: .Bera will use the following path: .Adil's path will be  units long, while Bera's path will be  units long.

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;

real dist(real x1, real y1, real x2, real y2) {
    return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}

void main() {
    auto s = readln.split.map!(to!long);
    auto ax = s[0];
    auto ay = s[1];
    auto bx = s[2];
    auto by = s[3];
    auto tx = s[4];
    auto ty = s[5];
    auto N = readln.chomp.to!int;
    auto X = new long[](N);
    auto Y = new long[](N);
    foreach (i; 0..N) {
        s = readln.split.map!(to!long);
        X[i] = s[0];
        Y[i] = s[1];
    }

    auto D = new real[](N);
    foreach (i; 0..N) D[i] = dist(X[i], Y[i], tx, ty) * 2;

    auto DA = new Tuple!(real, int)[](N);
    auto DB = new Tuple!(real, int)[](N);

    foreach (i; 0..N) {
        DA[i] = tuple(dist(X[i], Y[i], ax, ay) + dist(X[i], Y[i], tx, ty) - D[i], i);
        DB[i] = tuple(dist(X[i], Y[i], bx, by) + dist(X[i], Y[i], tx, ty) - D[i], i);
    }

    DA.sort();
    DB.sort();

    auto S = D.sum;
    real ans1 = real.max;
    real ans2 = real.max;
    real ans3 = real.max;
    real ans4 = real.max;

    if (N == 1) {
        ans1 = dist(X[0], Y[0], ax, ay) + dist(X[0], Y[0], tx, ty);
        ans2 = dist(X[0], Y[0], bx, by) + dist(X[0], Y[0], tx, ty);
    } else if (DA[0][1] == DB[0][1]){
        ans1 = S + DA[0][0] + DB[1][0];
        ans2 = S + DA[1][0] + DB[0][0];
    } else {
        ans1 = S + DA[0][0] + DB[0][0];
    }
    ans3 = S + DA[0][0];
    ans4 = S + DB[0][0];

    writefln("%.9f", min(ans1, ans2, ans3, ans4));
}

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;

real dist(real x1, real y1, real x2, real y2) {
    return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}

void main() {
    auto s = readln.split.map!(to!long);
    auto ax = s[0];
    auto ay = s[1];
    auto bx = s[2];
    auto by = s[3];
    auto tx = s[4];
    auto ty = s[5];
    auto N = readln.chomp.to!int;
    auto X = new long[](N);
    auto Y = new long[](N);
    foreach (i; 0..N) {
        s = readln.split.map!(to!long);
        X[i] = s[0];
        Y[i] = s[1];
    }

    auto D = new real[](N);
    foreach (i; 0..N) D[i] = dist(X[i], Y[i], tx, ty) * 2;

    auto DA = new Tuple!(real, int)[](N);
    auto DB = new Tuple!(real, int)[](N);

    foreach (i; 0..N) {
        DA[i] = tuple(dist(X[i], Y[i], ax, ay) + dist(X[i], Y[i], tx, ty) - D[i], i);
        DB[i] = tuple(dist(X[i], Y[i], bx, by) + dist(X[i], Y[i], tx, ty) - D[i], i);
    }

    DA.sort();
    DB.sort();

    auto S = D.sum;
    real ans1 = real.max;
    real ans2 = real.max;
    real ans3 = real.max;
    real ans4 = real.max;

    if (N == 1) {
        ans1 = dist(X[0], Y[0], ax, ay);
        ans2 = dist(X[0], Y[0], bx, by);
    } else if (DA[0][1] == DB[0][1]){
        ans1 = S + DA[0][0] + DB[1][0];
        ans2 = S + DA[1][0] + DB[0][0];
    } else {
        ans1 = S + DA[0][0] + DB[0][0];
    }
    ans3 = S + DA[0][0];
    ans4 = S + DB[0][0];

    writefln("%.9f", min(ans1, ans2, ans3, ans4));
}


Inna loves digit 9 very much. That's why she asked Dima to write a small number consisting of nines. But Dima must have misunderstood her and he wrote a very large number a, consisting of digits from 1 to 9.Inna wants to slightly alter the number Dima wrote so that in the end the number contained as many digits nine as possible. In one move, Inna can choose two adjacent digits in a number which sum equals 9 and replace them by a single digit 9.For instance, Inna can alter number 14545181 like this: 14545181 → 1945181 → 194519 → 19919. Also, she can use this method to transform number 14545181 into number 19991. Inna will not transform it into 149591 as she can get numbers 19919 and 19991 which contain more digits nine.Dima is a programmer so he wants to find out how many distinct numbers containing as many digits nine as possible Inna can get from the written number. Help him with this challenging task.

The first line of the input contains integer a (1 ≤ a ≤ 10100000). Number a doesn't have any zeroes.

In a single line print a single integer — the answer to the problem. It is guaranteed that the answer to the problem doesn't exceed 263 - 1. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteNotes to the samplesIn the first sample Inna can get the following numbers: 369727 → 99727 → 9997, 369727 → 99727 → 9979.In the second sample, Inna can act like this: 123456789987654321 → 12396789987654321 → 1239678998769321.

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

void main() {
    string a = stdin.readln.chop;
    long acc = 1;
    for (int i = 1; i < a.length; i++) {
        int x, y, c, j;
        for (j = 0; i + j < a.length; j++) {
            x = a[i+j-1] - '0';
            y = a[i+j] - '0';
            if (x + y == 9) {
                c++;
            } else {
                break;
            }
        }
        i += j;
        if (c % 2 == 0) {
            acc *= c / 2 + 1;
        }
    }
    acc.writeln;
}

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

void main() {
	string S =chomp(readln());
	int N =S.length;
	int poc[];
	long pos[];
	poc.length =pos.length =N+1;
	pos[0] =1, poc[0] =0;

	for(int i =0; i < N; i++) {
		int a =poc[i], b =0, c =0, j =i;
		while(true) {
			c +=cast(int)(S[j]-'0');
			if(c >= 9 || j == 0) break;
			j--;}
		b =poc[j];
		if(c == 9 && j == i-1) b++;
		poc[i+1] =max(a,b);
		pos[i+1] =0;
		if(poc[i+1] == a) pos[i+1] +=pos[i];
		if(poc[i+1] == b && b > poc[j]) pos[i+1] +=pos[j];}
//		writeln(pos[i]," ",poc[i]);}

	writeln(pos[N]);}

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

void main() {
	string S =chomp(readln());
	int N =S.length;
	int poc[];
	long pos[];
	poc.length =pos.length =N+1;
	pos[0] =1, poc[0] =0;

	for(int i =0; i < N; i++) {
		int a =poc[i], b =0, c =0, j =i;
		while(true) {
			c +=cast(int)(S[j]-'0');
			if(c >= 9 || j == 0) break;
			j--;}
		b =poc[j];
		if(c == 9) b++;
		poc[i+1] =max(a,b);
		pos[i+1] =0;
		if(poc[i+1] == a) pos[i+1] +=pos[i];
		if(poc[i+1] == b && c == 9) pos[i+1] +=pos[j];}
//		writeln(pos[i]," ",poc[i]);}

	writeln(pos[N]);}