Recently Pashmak has been employed in a transportation company. The company has k buses and has a contract with a school which has n students. The school planned to take the students to d different places for d days (each day in one place). Each day the company provides all the buses for the trip. Pashmak has to arrange the students in the buses. He wants to arrange the students in a way that no two students become close friends. In his ridiculous idea, two students will become close friends if and only if they are in the same buses for all d days.Please help Pashmak with his weird idea. Assume that each bus has an unlimited capacity.

The first line of input contains three space-separated integers n, k, d (1 ≤ n, d ≤ 1000; 1 ≤ k ≤ 109).

If there is no valid arrangement just print -1. Otherwise print d lines, in each of them print n integers. The j-th integer of the i-th line shows which bus the j-th student has to take on the i-th day. You can assume that the buses are numbered from 1 to k.

NoteNote that two students become close friends only if they share a bus each day. But the bus they share can differ from day to day.

import std.stdio;
import std.string;
import std.bigint;
import std.array;
import std.ascii;
import std.math;
import std.numeric;
import std.algorithm;
import std.container;
import std.conv;
import core.bitop;

alias Int = int;
immutable Int N_MAX = pow(10, 3) + 11;
immutable Int D_MAX = pow(10, 3) + 11;
immutable Int K_MAX = pow(10, 9) + 11;

Int T[D_MAX][N_MAX];

mixin template Inputter() {
  Int N;
  Int K;
  Int D;

  bool input(T)(T s) {
    if ( readf(" %s %s %s", &N, &K, &D) ) {
      debug writefln("N = %s, K = %s, D = %s", N, K, D);
      return true;
    }
    return false;
  }
}

mixin template Outputter() {
  bool ok;

  void output() {
    if ( ok ) {
      foreach ( i; 0 .. D ) {
        foreach ( j; 0 .. N ) {
          writef("%s ", T[i][j]);
        }
        writeln("");
      }
    } else {
      writefln("-1");
    }
  }
}

mixin template Solver() {
  void init() {
  }

  void solve() {
    foreach ( i; 0 .. D ) {
      T[i][0] = 1;
    }
    ok = find(1);
  }

  bool find( int c ) {
    debug writefln("@find: c = %s", c);
    if ( c >= N ) return true;
    foreach ( i; 0 .. D ) {
      T[i][c] = T[i][c - 1];
    }
    if ( ! add(c, 0) ) return false;
    return find(c + 1);
  }

  bool add( int c, int r ) {
    if ( r >= D ) return false;
    debug writefln("@add: c = %s, r = %s", c, r);
    if ( T[r][c] + 1 > K ) {
      T[r][c] = 1;
      return add(c, r + 1);
    }
    T[r][c] ++;
    return true;
  }
}

// Runner {{{
mixin template Runner() {
  void run() {
    while ( input(stdin) ) {
      init();
      solve();
      output();
    }
  }
}
// }}}

// Solution {{{
struct Solution {
  mixin Solver;
  mixin Inputter;
  mixin Outputter;
  mixin Runner;
}
// }}}

// main() {{{
Solution s;
void main() {
  s.run();
}
// }}}

import std.stdio;
import std.uni;
import std.conv;
import std.container;
import std.functional;
import std.algorithm;
import std.array;
import std.typecons;
import std.range;
import std.numeric;
import std.traits;

void main(string[] args)
{
  auto n = next!int;
  auto k = next!long;
  auto d = next!int;
  // k ^ d >= n
  long pot = 1;
  bool possible = false;
  foreach(p; 0 .. d + 1)
    {
      if (pot >= n) {possible = true; break;}
      pot *= k;
    }
  if (!possible) return writeln(-1);
  auto res = new long[][](d, n);
  foreach(i; 0 .. d) res[i][0] = 0;
  foreach(j; 1 .. n)
    {
      long carry = 1;
      foreach(i; 0 .. d)
	{
	  if (carry)
	    {
	      res[i][j] = res[i][j - 1] + carry;
	      if (res[i][j] == k)
		{
		  res[i][j] = 0;
		  carry = 1;
		}
	      else
		{
		  carry = 0;
		}
	    }
	  else
	    {
	      res[i][j] = res[i][j - 1];
	    }
	}
      assert(carry == 0);
    }
  foreach(row; res)
    {
      foreach(elem; row)
	{
	  write(elem + 1, " ");
	}
      writeln;
    }
}

static this()
{
  popChar;
}

struct Any(T)
{
  static auto read()
  {
    static if (is(T == char))
      {
	auto res = frontChar;
	popChar;
	return res;
      }
  }
}

struct Unsigned(T)
{
  auto read()
  {
    auto res = T(0);
    while(!frontChar.isDigit) popChar;
    do
      {
	res = res * T(10) + T(frontChar - '0');
	popChar;
      }
    while(frontChar.isDigit);
    return res;
  }
}

struct Matrix(T, alias rows, alias cols)
{
  T[][] _cell;
  alias _cell this;
  // Ring constructor
  this(int n)
  {
    final switch(n)
      {
      case 0:
	_cell = new T[][](rows, cols);
	break;
      case 1:
	debug assert(rows == cols);
	_cell = new T[][](rows, cols);
	foreach(i; 0 .. rows)
	  _cell[i][i] = T(1);
	break;
      }
  }
  // Copy constructor
  this(Matrix!(T, rows, cols) other)
  {
    _cell = new T[][](rows, cols);
    foreach(i; 0 .. rows)
      _cell[i][] = other[i][];
  }
  auto opBinary(string op)(Matrix!(T, rows, cols) other)
       if (op == "+" || op == "-")
	 {
	   auto res = Matrix!(T, rows, cols)(0);
	   foreach(i; 0 .. rows)
	     foreach(j; 0 .. cols)
	       res[i][j] = mixin(q{this[i][j]}, op, q{other[i][j]});
	   return res;
	 }
  auto opBinary(string op, alias otherRows, alias otherCols)(Matrix!(T, otherRows, otherCols) other)
       if (op == "*")
	 {
	   debug assert(cols == otherRows);
	   auto res = Matrix!(T, rows, otherCols)(0);
	   foreach(i; 0 .. rows)
	     foreach(k; 0 .. cols)
	       foreach(j; 0 .. otherCols)
		 res[i][j] += this[i][k] * other[k][j];
	   return res;
	 }
  ref auto opOpAssign(string op)(Matrix!(T, rows, cols) other)
  {
    static if (op == "*")
      {
	debug assert(rows == cols);
	alias n = rows;
	auto res = Matrix!(T, n, n)(0);
	T factor;
	foreach(i; 0 .. n)
	  foreach(k; 0 .. n)
	    foreach(j; 0 .. n)
	      res[i][j] += this[i][k] * other[k][j];
	foreach(i; 0 .. n)
	  this[i][] = res[i][];
      }
    else
      {
	foreach(i; 0 .. rows)
	  foreach(j; 0 .. cols)
	    mixin(q{this[i][j] }, text(op, q{=}), q{ other[i][j];});
      }
    return this;
  }
  mixin powMethod;
}

struct Mod(T, alias mod)
{
  alias This = Mod!(T, mod);
  T _rep;
  this(T t)
  {
    _rep = t % mod;
    if (_rep < 0) _rep += mod;
  }
  static auto plain(T t)
  {
    auto res = Mod!(T, mod)();
    res._rep = t;
    return res;
  }
  static auto fromPositive(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod);
  }
  static auto fromNegative(T t)
  {
    pragma(inline, true);
    return Mod!(T, mod).plain(t % mod + mod);
  }
  string toString()
  {
    return to!string(_rep);
  }
  debug invariant
  {
    assert(_rep >= 0 && _rep < mod);
  }
  auto opBinary(string op)(This b)
  {
    static if (op == "+")
      {
	T resrep = _rep + b._rep;
	if (resrep >= mod) resrep -= mod;
	return This.plain(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plain(resrep);
      }
    else static if (op == "*")
      {
	return This.fromPositive(_rep * b._rep);
      }
  }
  auto opOpAssign(string op)(This b)
  {
    mixin(q{_rep }, text(op, "="), q{b._rep;});
    static if (op == "+")
      {
	if (_rep >= mod) _rep -= mod;
      }
    else static if (op == "-")
      {
	if (_rep < 0) _rep += mod;
      }
    else static if (op == "*")
      {
	_rep %= mod;
      }
    return this;
  }

  auto opBinary(string op)(long exp)
       if (op == "^^")
	 {
	   return pow(exp);
	 }
  mixin powMethod;
}

mixin template powMethod()
{
  auto pow(this ThisType)(long exp)
    {
      auto res = ThisType(1);
      auto pow = ThisType(this);
      while(exp)
	{
	  if (exp & 1) res *= pow;
	  pow *= pow;
	  exp >>= 1;
	}
      return res;
    }
}
// INPUT
char frontChar;
void popChar()
{
  import core.stdc.stdio;
  frontChar = cast(char) getchar;
  if (feof(stdin)) frontChar = ' ';
}
auto makeArray(T, S...)(S s)
{
  enum brackets = () {
    string res;
    foreach(i; 0 .. s.length)
      res ~= "[]";
    return res;
  } ();
  mixin(q{alias Type = T}, brackets, q{;});
  return new Type(s);
}
template isNumberLike(T)
{
  enum isNumberLike = is(typeof((){T test; test = test + test * test; test *= test;}()));
}
void popWhite()
{
  import std.ascii;
  while (frontChar.isWhite) popChar;
}
void print(T...)(T t)
{
  static foreach(ti; t)
    {
      static if (is(typeof(ti) == string))
	{
	  write(ti, " ");
	}
      else static if (isArray!(typeof(ti)))
	{
	  foreach(e; ti) print(e);
	}
      else static if (isTuple!(typeof(ti)))
	{
	  static foreach(i; ti.length) writesp(ti[i]);
	}
      else
	{
	  write(ti, " ");
	}
    }
}
void println(T...)(T t)
{
  static if (t.length == 0)
    writeln;
  static foreach(ti; t)
    {
      print(ti);
      writeln;
    }
}
auto next(alias T, S...)(S s)
{
  pragma(inline, true);
  static if (s.length > 0)
    {
      auto res = makeArray!(typeof(next!T()))(s);
      S t;
      enum loops = () {
	string res;
	foreach(i; 0 .. s.length)
	  {
	    auto ti = text(q{t[}, i, q{]});
	    res ~= text(q{for(}, ti, q{ = 0;}, ti , q{ < s[}, i, q{];}, ti, q{++)});
	  }
	return res;
      } ();
      enum indexing = () {
	string res = "res";
	foreach(i; 0 .. s.length)
	  res ~= text(q{[t[}, i, q{]]});
	return res;
      } ();
      mixin(loops, indexing, q{ = next!T;});
      return res;
    }
  else
    {
      static if (isNumberLike!T)
	{
	  import std.ascii: isDigit;
	  T res;
	  while(frontChar.isWhite) popChar;
	  T multiplier = T(1);
	  if (frontChar == '-')
	    {
	      multiplier = T(-1);
	      popChar;
	    }
	  else if (frontChar == '+')
	    {
	      popChar;
	    }
	  debug assert(frontChar.isDigit);
	  do
	    {
	      res = res * T(10) + T(frontChar - '0');
	      popChar;
	    }
	  while(frontChar.isDigit);
	  return multiplier * res;
	}
      else static if (is(T == string))
	{
	  import std.ascii: isWhite;
	  string res;
	  while(frontChar.isWhite)
	    popChar;
	  while(!frontChar.isWhite)
	    {
	      res ~= frontChar;
	      popChar;
	    }
	  return res;
	}
      else static if (is(T == char))
	{
	  while(frontChar.isWhite) popChar;
	  auto res = frontChar;
	  popChar;
	  return res;
	}
      else
	{
	  return T.read;
	}
    }
}


Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains $$$26$$$ buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning. To check which buttons need replacement, Polycarp pressed some buttons in sequence, and a string $$$s$$$ appeared on the screen. When Polycarp presses a button with character $$$c$$$, one of the following events happened:  if the button was working correctly, a character $$$c$$$ appeared at the end of the string Polycarp was typing;  if the button was malfunctioning, two characters $$$c$$$ appeared at the end of the string. For example, suppose the buttons corresponding to characters a and c are working correctly, and the button corresponding to b is malfunctioning. If Polycarp presses the buttons in the order a, b, a, c, a, b, a, then the string he is typing changes as follows: a $$$\rightarrow$$$ abb $$$\rightarrow$$$ abba $$$\rightarrow$$$ abbac $$$\rightarrow$$$ abbaca $$$\rightarrow$$$ abbacabb $$$\rightarrow$$$ abbacabba.You are given a string $$$s$$$ which appeared on the screen after Polycarp pressed some buttons. Help Polycarp to determine which buttons are working correctly for sure (that is, this string could not appear on the screen if any of these buttons was malfunctioning).You may assume that the buttons don't start malfunctioning when Polycarp types the string: each button either works correctly throughout the whole process, or malfunctions throughout the whole process.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then the test cases follow. Each test case is represented by one line containing a string $$$s$$$ consisting of no less than $$$1$$$ and no more than $$$500$$$ lowercase Latin letters.

For each test case, print one line containing a string $$$res$$$. The string $$$res$$$ should contain all characters which correspond to buttons that work correctly in alphabetical order, without any separators or repetitions. If all buttons may malfunction, $$$res$$$ should be empty.

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 t = RD!int;
	auto ans = new int[][](t, 26);
	foreach (i; 0..t)
	{
		auto s = RD!string;
		long cnt = 1;
		char last = s[0];
		foreach (j; 1..s.length)
		{
			if (s[j] == last)
			{
				++cnt;
			}
			else
			{
				if (cnt % 2 == 1)
				{
					ans[i][last-'a'] = 1;
				}
				cnt = 1;
				last = s[j];
			}
		}
		if (cnt % 2 == 1)
		{
			ans[i][last-'a'] = 1;
		}
	}

	foreach (e; ans)
	{
		foreach (i; 0..e.length)
		{
			if (e[i] == 1)
				write(cast(char)('a'+i));
		}
		writeln();
	}
	stdout.flush();
	debug readln();
}


A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define:  $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column.  $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \le i \le n$$$).  $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \le j \le n$$$).  In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$.  For the grid $$$A$$$ let's define the value $$$f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\max(X)$$$ as the maximum value in $$$X$$$ and $$$\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case the only line contains two integers $$$n$$$, $$$k$$$ $$$(1 \le n \le 300, 0 \le k \le n^2)$$$. It is guaranteed that the sum of $$$n^2$$$ for all test cases does not exceed $$$10^5$$$.

For each test case, firstly print the minimum possible value of $$$f(A)$$$ among all tables, for which the condition is satisfied. After that, print $$$n$$$ lines contain $$$n$$$ characters each. The $$$j$$$-th character in the $$$i$$$-th line should be equal to $$$A_{i,j}$$$. If there are multiple answers you can print any.

NoteIn the first test case, the sum of all elements in the grid is equal to $$$2$$$, so the condition is satisfied. $$$R_1 = 1, R_2 = 1$$$ and $$$C_1 = 1, C_2 = 1$$$. Then, $$$f(A) = (1-1)^2 + (1-1)^2 = 0$$$, which is the minimum possible value of $$$f(A)$$$.In the second test case, the sum of all elements in the grid is equal to $$$8$$$, so the condition is satisfied. $$$R_1 = 3, R_2 = 3, R_3 = 2$$$ and $$$C_1 = 3, C_2 = 2, C_3 = 3$$$. Then, $$$f(A) = (3-2)^2 + (3-2)^2 = 2$$$. It can be proven, that it is the minimum possible value of $$$f(A)$$$.

import std.algorithm, std.range, std.stdio;
void main() {
	readln;
	int n, k;
	while (readf!" %s %s"(n, k) > 0)
		writefln!"%s\n%(%(%d%)\n%)"(!!(k % n) * 2,
			n.iota.map!(r => n.iota.map!(c => ((r + c) % n * n + r < k))));
}

import std.algorithm, std.range, std.stdio;
void main () {
	readln;
	int n, k;
	while (readf !(" %s %s") (n, k) > 0)
		writefln !("%s\n%(%(%d%)\n%)") (!!(k % n) * 2,
			n.iota.map !(r => n.iota.map !(c => ((r + c) % n * n + r < k))));
}

import std.algorithm, std.range, std.stdio, std.string;
void main () {
	readln;
	int n, k;
	while (readf !(" %s %s") (n, k) > 0) {
		writeln (!!(k % n) * 2);
		writefln !("%(%(%d%)\n%)") (n.iota.map !(r =>
		    n.iota.map !(c => ((r + c) % n * n + r < k))));
	}
}

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

DList!string _words;
void read(T)(out T t)
{
  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;
  t = to!T(word);
}

void main()
{
  int t;
  read(t);
  while(t--)
    {
      int n, k;
      read(n), read(k);
      auto qperrow = new int[cast(size_t)n];
      foreach(i; 0 .. k % n)
        qperrow[i] = k / n + 1;
      foreach(i; k % n .. n)
        qperrow[i] = k / n;
      auto res = new int[][cast(size_t)n];
      foreach(ref row; res)
        {
          row = new int[cast(size_t)n];
          row[] = 0;
        }
      int cnt = 0;
      int rcnt = 0;
      int i = 0;
      int j = 0;
      while(cnt < k)
        {
          if (rcnt == qperrow[i])
            {
              i++;
              rcnt = 0;
            }
          res[cast(size_t)i][cast(size_t)j] = 1;
          j++; j %= n;
          rcnt++;
          cnt++;
        }
      if (k % n == 0)
        {
          writeln(0);
        }
      else
        {
          writeln(2);
        }
      foreach(row; res)
        {
          foreach(cell; row)
            write(cell);
          writeln;
        }
    }
}

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);
	auto a = new char[][][](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto k = RD!int;

		a[ti] = new char[][](n, n);
		ans[ti] = k % n == 0 ? 0 : 2;

		foreach (i; 0..n)
		{
			foreach (j; 0..n)
				a[ti][i][j] = '0';
		}

		(){
		foreach (i; 0..n)
		{
			foreach (j; 0..n)
			{
				if (k == 0) return;
				a[ti][j][(i+j)%n] = '1';
				--k;
			}
		}}();
	}

	foreach (ti, e; ans)
	{
		writeln(e);
		foreach (ee; a[ti])
			writeln(ee);
	}

	stdout.flush;
	debug readln;
}

import std.algorithm, std.range, std.stdio, std.string;
void main () {
	readln;
	int n, k;
	while (readf !(" %s %s") (n, k) > 0) {
		writefln !("%(%(%d%)\n%)") (n.iota.map !(r =>
		    n.iota.map !(c => ((r + c) % n * n + r < k))));
	}
}


Two integers x and y are compatible, if the result of their bitwise "AND" equals zero, that is, a & b = 0. For example, numbers 90 (10110102) and 36 (1001002) are compatible, as 10110102 & 1001002 = 02, and numbers 3 (112) and 6 (1102) are not compatible, as 112 & 1102 = 102.You are given an array of integers a1, a2, ..., an. Your task is to find the following for each array element: is this element compatible with some other element from the given array? If the answer to this question is positive, then you also should find any suitable element.

The first line contains an integer n (1 ≤ n ≤ 106) — the number of elements in the given array. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 4·106) — the elements of the given array. The numbers in the array can coincide.

Print n integers ansi. If ai isn't compatible with any other element of the given array a1, a2, ..., an, then ansi should be equal to -1. Otherwise ansi is any such number, that ai & ansi = 0, and also ansi occurs in the array a1, a2, ..., an.

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

int countBits(T)(T num)
{
    auto left = 0, right = (cast(int)num.sizeof << 3) - 1;
    auto res = -1;
    while (left <= right)
    {
        auto mid = (left + right) >> 1;
        if (num >= (1 << mid))
        {
            res = mid;
            left = mid + 1;
        }
        else
        {
            right = mid - 1;
        }
    }
    return res + 1;
}

int flip(int num, int cnt)
{
    return num ^ ((1 << cnt) - 1);
}

void store(int mask, int val, int[] cand)
{
    if (cand[mask] != -1) return;
    cand[mask] = val;
    foreach (i; 0 .. 32)
    {
        if (mask < (1 << i)) return;
        if (mask & (1 << i))
        {
            store(mask ^ (1 << i), val, cand);
        }
    }
}

void solve(int[] a)
{
    auto m = reduce!(max)(a);
    auto cnt = countBits!int(m);
    auto cand = new int[1 << cnt];
    fill(cand, -1);
    foreach (v; a) store(flip(v, cnt), v, cand);
    foreach (v; a) writef("%d ", cand[v]);
    writeln();
}

int main(string[] args)
{
    int n;
    while (readf("%d\n", &n) == 1)
    {
        auto a = new int[n];
        foreach (ref v; a) readf(" %d", &v);
        readln();
        solve(a);
    }
    return 0;
}


You have a string $$$s$$$ of length $$$n$$$ consisting of only characters > and <. You may do some operations with this string, for each operation you have to choose some character that still remains in the string. If you choose a character >, the character that comes right after it is deleted (if the character you chose was the last one, nothing happens). If you choose a character <, the character that comes right before it is deleted (if the character you chose was the first one, nothing happens).For example, if we choose character > in string > > < >, the string will become to > > >. And if we choose character < in string > <, the string will become to <.The string is good if there is a sequence of operations such that after performing it only one character will remain in the string. For example, the strings >, > > are good. Before applying the operations, you may remove any number of characters from the given string (possibly none, possibly up to $$$n - 1$$$, but not the whole string). You need to calculate the minimum number of characters to be deleted from string $$$s$$$ so that it becomes good.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) – the number of test cases. Each test case is represented by two lines. The first line of $$$i$$$-th test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) – the length of string $$$s$$$. The second line of $$$i$$$-th test case contains string $$$s$$$, consisting of only characters > and <.

For each test case print one line. For $$$i$$$-th test case print the minimum number of characters to be deleted from string $$$s$$$ so that it becomes good.

NoteIn the first test case we can delete any character in string <>.In the second test case we don't need to delete any characters. The string > < < is good, because we can perform the following sequence of operations: > < < $$$\rightarrow$$$ < < $$$\rightarrow$$$ <.

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, core.stdc.string;

immutable long MOD = 10^^9 + 7;

void solve() {
    auto N = readln.chomp.to!int;
    auto S = readln.chomp;
    int ans = 1 << 29;
    foreach (i; 0..N) {
        if (S[i] == '>' || S[N - i - 1] == '<') {
            ans = i;
            break;
        }
    }
    ans.writeln;
}

void main() {
    auto T = readln.chomp.to!int;
    while (T--) solve;
}

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

void solve()
{
    auto n = readln.chomp.to!int;
    auto S = readln.chomp.to!(char[]);
    int r, s;
    foreach (c; S) {
        if (c == '<') r = 0;
        else ++r;
    }
    foreach_reverse (c; S) {
        if (c == '>') s = 0;
        else ++s;
    }
    writeln(min(r, s));
}

void main()
{
    auto N = readln.chomp.to!int;
    foreach (_; 0..N) solve();
}

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

void solve()
{
    auto n = readln.chomp.to!int;
    auto S = readln.chomp.to!(char[]);
    foreach (i, c; S) {
        if (c == '>') {
            writeln(min(i, n-i));
            return;
        }
    }
    writeln("0");
    return;
}

void main()
{
    auto N = readln.chomp.to!int;
    foreach (_; 0..N) solve();
}


As meticulous Gerald sets the table, Alexander finished another post on Codeforces and begins to respond to New Year greetings from friends. Alexander has n friends, and each of them sends to Alexander exactly one e-card. Let us number his friends by numbers from 1 to n in the order in which they send the cards. Let's introduce the same numbering for the cards, that is, according to the numbering the i-th friend sent to Alexander a card number i.Alexander also sends cards to friends, but he doesn't look for the new cards on the Net. He simply uses the cards previously sent to him (sometimes, however, he does need to add some crucial details). Initially Alexander doesn't have any cards. Alexander always follows the two rules:  He will never send to a firend a card that this friend has sent to him.  Among the other cards available to him at the moment, Alexander always chooses one that Alexander himself likes most. Alexander plans to send to each friend exactly one card. Of course, Alexander can send the same card multiple times.Alexander and each his friend has the list of preferences, which is a permutation of integers from 1 to n. The first number in the list is the number of the favorite card, the second number shows the second favorite, and so on, the last number shows the least favorite card.Your task is to find a schedule of sending cards for Alexander. Determine at which moments of time Alexander must send cards to his friends, to please each of them as much as possible. In other words, so that as a result of applying two Alexander's rules, each friend receives the card that is preferred for him as much as possible.Note that Alexander doesn't choose freely what card to send, but he always strictly follows the two rules.

The first line contains an integer n (2 ≤ n ≤ 300) — the number of Alexander's friends, equal to the number of cards. Next n lines contain his friends' preference lists. Each list consists of n different integers from 1 to n. The last line contains Alexander's preference list in the same format.

Print n space-separated numbers: the i-th number should be the number of the friend, whose card Alexander receives right before he should send a card to the i-th friend. If there are several solutions, print any of them.

NoteIn the sample, the algorithm of actions Alexander and his friends perform is as follows:   Alexander receives card 1 from the first friend.  Alexander sends the card he has received (at the moment he only has one card, and therefore it is the most preferable for him) to friends with the numbers 2 and 3.  Alexander receives card 2 from the second friend, now he has two cards — 1 and 2.  Alexander sends a card to the first friend. Despite the fact that Alexander likes card 1 more, he sends card 2 as he cannot send a friend the card sent by that very friend.  Alexander receives card 3 from the third friend.  Alexander receives card 4 from the fourth friend.  Among the cards Alexander has number 3 is his favorite and he sends it to the fourth friend. Note that Alexander can send cards to multiple friends at a time (in this case the second and the third one). Alexander can send card 3 to the fourth friend after he receives the third card or after he receives the fourth card (both variants are correct).

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;

immutable int INF = 10 ^^ 8;

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

    auto friends = new int[][] (n+1, n+1);
    friends ~= [];
    foreach (i; 1 .. n+1) {
        auto arr = readln.chomp.split.map!(to!int).array;
        foreach (j; 0 .. n) {
            friends[i][arr[j]] = j+1;
        }
    }

    auto arr = readln.chomp.split.map!(to!int).array;
    auto alex = new int[] (n+1);
    foreach (i; 0 .. n) { alex[arr[i]] = i+1; }

    int[] ans;
    foreach (f; 1 .. n+1) {
        ans ~= 0;
        int fav = 0;
        foreach (e; 1 .. n+1) {
            if (f == e) { continue; }

            if (fav == 0 || alex[e] < alex[fav]) {
                fav = e;
                if (ans.back == 0
                        || friends[f][fav] < friends[f][ans.back]) {
                    ans.back = fav;
                }
            }

        }
    }

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

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;

immutable int INF = 10 ^^ 8;

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

    auto friends = new int[][] (n+1, n+1);
    friends ~= [];
    foreach (i; 1 .. n+1) {
        auto arr = readln.chomp.split.map!(to!int).array;
        foreach (j; 0 .. n) {
            friends[i][arr[j]] = j+1;
        }
    }

    auto arr = readln.chomp.split.map!(to!int).array;
    auto alex = new int[] (n+1);
    foreach (i; 0 .. n) { alex[arr[i]] = i+1; }

    auto ans = new int[] (n+1);
    ans[] = 1;
    ans[1] = 2;

    foreach (i; 2 .. n+1) {
        foreach (f; 1 .. n+1) {
            if (i == f) { continue; }
            if (alex[ans[f]] < alex[i]) { continue; }

            if (friends[f][i] < friends[f][ans[f]]) { ans[f] = i; }
        }
    }

    ans.dropOne.writefln!"%(%s %)";
}

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;

immutable int INF = 10 ^^ 8;

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

    auto friends = new int[][] (n+1, n+1);
    friends ~= [];
    foreach (i; 1 .. n+1) {
        auto arr = readln.chomp.split.map!(to!int).array;
        foreach (j; 0 .. n) {
            friends[i][arr[j]] = j+1;
        }
    }

    auto arr = readln.chomp.split.map!(to!int).array;
    auto alex = new int[] (n+1);
    foreach (i; 0 .. n) { alex[arr[i]] = i+1; }

    auto ans = new int[] (n+1);
    ans[] = 1;
    ans[1] = 2;

    int best = 1;
    foreach (i; 2 .. n+1) {
        if (alex[i] > alex[best]) { continue; }

        best = i;

        foreach (f; 1 .. n+1) {
            if (i == f) { continue; }
            if (alex[ans[f]] < alex[i]) { continue; }

            if (friends[f][i] < friends[f][ans[f]]) { ans[f] = i; }
        }
    }

    ans.dropOne.writefln!"%(%s %)";
}


Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game.The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, and so on, the m-th face contains m dots. Twilight Sparkle is sure that when the dice is tossed, each face appears with probability . Also she knows that each toss is independent from others. Help her to calculate the expected maximum number of dots she could get after tossing the dice n times.

A single line contains two integers m and n (1 ≤ m, n ≤ 105).

Output a single real number corresponding to the expected maximum. The answer will be considered correct if its relative or absolute error doesn't exceed 10  - 4.

NoteConsider the third test example. If you've made two tosses:  You can get 1 in the first toss, and 2 in the second. Maximum equals to 2.  You can get 1 in the first toss, and 1 in the second. Maximum equals to 1.  You can get 2 in the first toss, and 1 in the second. Maximum equals to 2.  You can get 2 in the first toss, and 2 in the second. Maximum equals to 2. The probability of each outcome is 0.25, that is expectation equals to: You can read about expectation using the following link: http://en.wikipedia.org/wiki/Expected_value

import std.stdio;
import std.math;

/// Template for power function. Returns a^n.
pure T pow(T)(const T a, uint n) {
	T res = 1;
	T x = a;
	while (0 != n) {
		if (1 == n % 2) {
			res *= x;
		}
		x *= x;
		n /= 2;
	}
	return res;
}

bool eq(const double a, const double b,  const double EPS = 1E-7) {
	return abs(a - b) <= EPS;
}

unittest {
	assert(243 == pow!int(3, 5));
	assert(1 == pow!uint(234, 0));
	assert(4 == pow!ulong(2, 2));
	assert(256 == pow!long(2, 8));
	assert(161051 == pow!ulong(11, 5));
}

pure double solve(const uint m, const uint n) {
	double res = 0.0;
	foreach(i; 0 .. m) {
		res += (i + 1) * (pow!double(cast(double)(i + 1) / m, n) - pow!double(cast(double)i / m, n));
	}
	return res;
}

unittest {
	assert(eq(3.5, solve(6, 1)));
	assert(eq(4.958333333333, solve(6, 3)));
	assert(eq(1.75, solve(2, 2)));
}

int main(string[] argv) {
	uint m = 0;
	uint n = 0;
	readf(" %s %s", &m, &n);
	writefln("%.7f", solve(m, n));
    return 0;
}

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 m;
	int n;
	while (readf (" %s %s", &m, &n) > 0)
	{
		real res = 0.0;
		real p = 1.0;
		for (int i = m; i >= 1; i--)
		{
			real temp = (i - 1.0L) / i;
			temp = 1.0L - pow (temp, n);
			res += temp * p * i;
			p *= 1.0L - temp;
		}
		writefln ("%.20f", res);
	}
}

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

//	Input
class EOFException : Throwable { this() { super("EOF"); } }
string[] tokens;
string readToken() { for (; tokens.empty; ) { tokens = readln.split; if (stdin.eof) throw new EOFException; } auto token = tokens[0]; tokens.popFront; return token; }
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, const T f) { if (t > f) t = f; }
void chmax(T)(ref T t, const T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(ref const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	string toString() const { return "(" ~ to!string(x) ~ ", " ~ to!string(y) ~ ")"; }
}
auto pair(S, T)(S x, T y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(T[] as, bool delegate(T) test) { int low = -1, upp = as.length; for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; }
int lowerBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(T[] as, T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

int M, N;

void main(string[] args) {
	try {
	for (; ; ) {
		M = readInt;
		N = readInt;
		real ans = 0.0;
		foreach (x; 0 .. M) {
			ans += 1.0 - (x / cast(real)(M)) ^^ N;
		}
		writefln("%.10f", ans);
	}
	} catch (EOFException) {}
}


You are given a tree with n vertices and you are allowed to perform no more than 2n transformations on it. Transformation is defined by three vertices x, y, y' and consists of deleting edge (x, y) and adding edge (x, y'). Transformation x, y, y' could be performed if all the following conditions are satisfied:  There is an edge (x, y) in the current tree.  After the transformation the graph remains a tree.  After the deletion of edge (x, y) the tree would consist of two connected components. Let's denote the set of nodes in the component containing vertex x by Vx, and the set of nodes in the component containing vertex y by Vy. Then condition |Vx| > |Vy| should be satisfied, i.e. the size of the component with x should be strictly larger than the size of the component with y. You should minimize the sum of squared distances between all pairs of vertices in a tree, which you could get after no more than 2n transformations and output any sequence of transformations leading initial tree to such state.Note that you don't need to minimize the number of operations. It is necessary to minimize only the sum of the squared distances.

The first line of input contains integer n (1 ≤ n ≤ 2·105) — number of vertices in tree. The next n - 1 lines of input contains integers a and b (1 ≤ a, b ≤ n, a ≠ b) — the descriptions of edges. It is guaranteed that the given edges form a tree.

In the first line output integer k (0 ≤ k ≤ 2n) — the number of transformations from your example, minimizing sum of squared distances between all pairs of vertices. In each of the next k lines output three integers x, y, y' — indices of vertices from the corresponding transformation. Transformations with y = y' are allowed (even though they don't change tree) if transformation conditions are satisfied. If there are several possible answers, print any of them.

NoteThis is a picture for the second sample. Added edges are dark, deleted edges are dotted.

/+ dub.sdl:
    name "C"
    dependency "dcomp" version=">=0.6.0"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dcomp.foundation, dcomp.scanner;

int main() {
    auto sc = new Scanner(stdin);
    int n;
    sc.read(n);
    int[][] g = new int[][](n);
    foreach (i; 0..n-1) {
        int a, b;
        sc.read(a, b); a--; b--;
        g[a] ~= b;
        g[b] ~= a;
    }
    bool[] isCent = new bool[n];
    int[] sz = new int[n];
    void dfs(int p, int b) {
        sz[p] = 1; isCent[p] = true;
        foreach (d; g[p]) {
            if (d == b) continue;
            dfs(d, p);
            sz[p] += sz[d];
            if (sz[d] > n/2) isCent[p] = false;
        }
        if (n - sz[p] > n/2) isCent[p] = false;
    }
    dfs(0, -1);

//    writeln(isCent);

    Appender!(int[]) ap;
    int[] par = new int[n];
    void sea(int p, int b) {
        par[p] = b;
        ap ~= p;
        foreach (d; g[p]) {
            if (d == b) continue;
            sea(d, p);
        }
    }
    int[3][] res;
    foreach (i; 0..n) {
        if (!isCent[i]) continue;
        foreach (j; g[i]) {
            if (isCent[j]) continue;
//            writeln(i, " -> ", j);
            ap.clear();
            sea(j, i);
            int p = j;
            foreach (d; ap.data) {
                if (d == j) continue;
                res ~= [i, p, d]; p = d;
                res ~= [d, par[d], j];
            }
            res ~= [i, p, j];
        }
    }

    writeln(res.length);
    foreach (v; res) {
        writeln(v[].map!(x => (x+1).to!string).join(" "));
    }
    return 0;
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/foundation.d */
// module dcomp.foundation;

static if (__VERSION__ <= 2070) {
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
version (X86) static if (__VERSION__ < 2071) {
    import core.bitop : bsf, bsr, popcnt;
    int bsf(ulong v) {
        foreach (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int bsr(ulong v) {
        foreach_reverse (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int popcnt(ulong v) {
        int c = 0;
        foreach (i; 0..64) {
            if (v & (1UL << i)) c++;
        }
        return c;
    }
}
/* IMPORT /home/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            if (f.eof) return false;
            line = lineBuf[];
            f.readln(line);
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else {
                auto buf = line.split.map!(to!E).array;
                static if (isStaticArray!T) {

                    assert(buf.length == T.length);
                }
                x = buf;
                line.length = 0;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }
    int read(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
}

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

int N;
int[] A, B;

int[][] G;
int[] sz;

void dfsSz(int u, int p) {
  sz[u] = 1;
  foreach (i; G[u]) {
    const v = A[i] ^ B[i] ^ u;
    if (v != p) {
      dfsSz(v, u);
      sz[u] += sz[v];
    }
  }
}

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

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      sz = new int[N];
      dfsSz(0, -1);

      int[] rs;
      for (int u = 0; ; ) {
        int vm = -1;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (vm == -1 || sz[vm] < sz[v]) {
            vm = v;
          }
        }
        if (vm == -1 || sz[u] >= 2 * sz[vm]) {
          rs ~= u;
          if (sz[u] == 2 * sz[vm]) {
            rs ~= vm;
          }
          break;
        } else {
          sz[u] -= sz[vm];
          sz[vm] += sz[u];
          u = vm;
        }
      }
      debug {
        writeln("rs = ", rs);
      }

      int[][] ans;
      auto par = new int[N];
      foreach (r; rs) {
        foreach (j; G[r]) {
          const s = A[j] ^ B[j] ^ r;
          if (rs.count(s) == 0) {
            int[] us;
            void dfs(int u, int p) {
              us ~= u;
              par[u] = p;
              foreach (i; G[u]) {
                const v = A[i] ^ B[i] ^ u;
                if (v != p) {
                  dfs(v, u);
                }
              }
            }
            dfs(s, r);
            debug {
              writeln(r, " ", s, " ", us);
            }
            int now = s;
            foreach (u; us) {
              if (par[u] != r) {
                ans ~= [r, now, u];
                now = u;
                ans ~= [u, par[u], s];
              }
            }
            ans ~= [r, now, s];
          }
        }
      }

      ans = ans.filter!(row => (row[1] != row[2])).array;

      writeln(ans.length);
      foreach (row; ans) {
        writeln(row[0] + 1, " ", row[1] + 1, " ", row[2] + 1);
      }
    }
  } catch (EOFException e) {
  }
}

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

int N;
int[] A, B;

int[][] G;
int[][] ans;

void solveCentroidDecomp() {
  auto sz = new int[N];
  auto del = new bool[N];
  void dfsSz(int u, int p) {
    sz[u] = 1;
    foreach (i; G[u]) {
      const v = A[i] ^ B[i] ^ u;
      if (v != p) {
        dfsSz(v, u);
        sz[u] += sz[v];
      }
    }
  }
  dfsSz(0, -1);

  // r: centroid
  void solveSubtree(int r) {
    debug {
      string dfsDebug(int u, int p) {
        string ret = u.to!string;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v] && v != p) {
            ret ~= "(" ~ dfsDebug(v, u) ~ ")";
          }
        }
        return ret;
      }
      writeln("solveSubtree ", dfsDebug(r, -1));
    }
    //
    void dfs(int u, int p, int d) {
      //
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v] && v != p) {
          dfs(v, u, d + 1);
        }
      }
    }
    foreach (i; G[r]) {
      const v = A[i] ^ B[i] ^ r;
      if (!del[v]) {
        dfs(v, r, 1);
        //
      }
    }
    //
  }

  long calc(int u) {
    long ret;
    void dfs(int u, int p, long d) {
      ret += d;
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v] && v != p) {
          dfs(v, u, d + 1);
        }
      }
    }
    dfs(u, -1, 0);
    debug {
      writeln("calc ", u, " = ", ret);
    }
    return ret;
  }

  // void solveRec(int u) {
  int solveRec(int u) {
    for (; ; ) {
      int vm = -1;
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v]) {
          if (vm == -1 || sz[vm] < sz[v]) {
            vm = v;
          }
        }
      }
      if (vm == -1 || sz[u] >= 2 * sz[vm]) {
        solveSubtree(u);
        /*
        del[u] = true;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v]) {
            solveRec(v);
          }
        }
        */
        ////
        int same = -1;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v]) {
            if (sz[u] - sz[v] == sz[v]) {
              same = v;
            }
          }
        }
        debug {
          writefln("u = %s, same = %s", u, same);
        }
        del[u] = true;
        int ret = u;
        if (same != -1) {
          del[same] = true;
          const resU = calc(u);
          const resSame = calc(same);
          if (resU < resSame) {
            ret = same;
          }
        }
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v]) {
            if (v != same) {
              const res = solveRec(v);
              if (v != res) {
                ans ~= [u, v, res];
              }
            }
          }
        }
        if (same != -1) {
          foreach (i; G[same]) {
            const v = A[i] ^ B[i] ^ same;
            if (!del[v]) {
              const res = solveRec(v);
              if (v != res) {
                ans ~= [same, v, res];
              }
            }
          }
        }
        return ret;
        ////
        break;
      } else {
        sz[u] -= sz[vm];
        sz[vm] += sz[u];
        u = vm;
      }
    }
  }
  solveRec(0);
}

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

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      ans = [];
      solveCentroidDecomp;
      writeln(ans.length);
      foreach_reverse (op; ans) {
        writeln(op[0] + 1, " ", op[1] + 1, " ", op[2] + 1);
      }
    }
  } catch (EOFException e) {
  }
}

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

int N;
int[] A, B;

int[][] G;
int[][] ans;

void solveCentroidDecomp() {
  auto sz = new int[N];
  auto del = new bool[N];
  void dfsSz(int u, int p) {
    sz[u] = 1;
    foreach (i; G[u]) {
      const v = A[i] ^ B[i] ^ u;
      if (v != p) {
        dfsSz(v, u);
        sz[u] += sz[v];
      }
    }
  }
  dfsSz(0, -1);

  // r: centroid
  void solveSubtree(int r) {
    debug {
      string dfsDebug(int u, int p) {
        string ret = u.to!string;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v] && v != p) {
            ret ~= "(" ~ dfsDebug(v, u) ~ ")";
          }
        }
        return ret;
      }
      writeln("solveSubtree ", dfsDebug(r, -1));
    }
    //
    void dfs(int u, int p, int d) {
      //
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v] && v != p) {
          dfs(v, u, d + 1);
        }
      }
    }
    foreach (i; G[r]) {
      const v = A[i] ^ B[i] ^ r;
      if (!del[v]) {
        dfs(v, r, 1);
        //
      }
    }
    //
  }

  long calc(int u) {
    long ret;
    void dfs(int u, int p, long d) {
      ret += d;
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v] && v != p) {
          dfs(v, u, d + 1);
        }
      }
    }
    dfs(u, -1, 0);
    debug {
      writeln("calc ", u, " = ", ret);
    }
    return ret;
  }

  // void solveRec(int u) {
  int solveRec(int u) {
    for (; ; ) {
      int vm = -1;
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v]) {
          if (vm == -1 || sz[vm] < sz[v]) {
            vm = v;
          }
        }
      }
      if (vm == -1 || sz[u] >= 2 * sz[vm]) {
        solveSubtree(u);
        /*
        del[u] = true;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v]) {
            solveRec(v);
          }
        }
        */
        ////
        int same = -1;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v]) {
            if (sz[u] - sz[v] == sz[v]) {
              same = v;
            }
          }
        }
        debug {
          writefln("u = %s, same = %s", u, same);
        }
        del[u] = true;
        int ret = u;
        if (same != -1) {
          del[same] = true;
          const resU = calc(u);
          const resSame = calc(same);
          if (resU < resSame) {
            ret = same;
          }
        }
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v]) {
            if (v != same) {
              const res = solveRec(v);
              if (v != res) {
                ans ~= [u, v, res];
              }
            }
          }
        }
        if (same != -1) {
          foreach (i; G[same]) {
            const v = A[i] ^ B[i] ^ same;
            if (!del[v]) {
              const res = solveRec(v);
              if (v != res) {
                ans ~= [same, v, res];
              }
            }
          }
        }
        return ret;
        ////
        break;
      } else {
        sz[u] -= sz[vm];
        sz[vm] += sz[u];
        u = vm;
      }
    }
  }
  solveRec(0);
}

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

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      ans = [];
      solveCentroidDecomp;
      writeln(ans.length);
      foreach (op; ans) {
        writeln(op[0] + 1, " ", op[1] + 1, " ", op[2] + 1);
      }
    }
  } catch (EOFException e) {
  }
}

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

int N;
int[] A, B;

int[][] G;
int[][] ans;

void solveCentroidDecomp() {
  auto sz = new int[N];
  auto del = new bool[N];
  void dfsSz(int u, int p) {
    sz[u] = 1;
    foreach (i; G[u]) {
      const v = A[i] ^ B[i] ^ u;
      if (v != p) {
        dfsSz(v, u);
        sz[u] += sz[v];
      }
    }
  }
  dfsSz(0, -1);

  // r: centroid
  void solveSubtree(int r) {
    debug {
      string dfsDebug(int u, int p) {
        string ret = u.to!string;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v] && v != p) {
            ret ~= "(" ~ dfsDebug(v, u) ~ ")";
          }
        }
        return ret;
      }
      writeln("solveSubtree ", dfsDebug(r, -1));
    }
    //
    void dfs(int u, int p, int d) {
      //
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v] && v != p) {
          dfs(v, u, d + 1);
        }
      }
    }
    foreach (i; G[r]) {
      const v = A[i] ^ B[i] ^ r;
      if (!del[v]) {
        dfs(v, r, 1);
        //
      }
    }
    //
  }

  // void solveRec(int u) {
  int solveRec(int u) {
    for (; ; ) {
      int vm = -1;
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v]) {
          if (vm == -1 || sz[vm] < sz[v]) {
            vm = v;
          }
        }
      }
      if (vm == -1 || sz[u] >= 2 * sz[vm]) {
        solveSubtree(u);
        del[u] = true;
        /*
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v]) {
            solveRec(v);
          }
        }
        */
        ////
        int same = -1;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v]) {
            if (sz[u] - sz[v] == sz[v]) {
              same = v;
            }
          }
        }
        debug {
          writefln("u = %s, same = %s", u, same);
        }
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v]) {
            if (v != same) {
              const res = solveRec(v);
              if (v != res) {
                ans ~= [u, v, res];
              }
            }
          }
        }
        if (same != -1) {
          del[same] = true;
          foreach (i; G[same]) {
            const v = A[i] ^ B[i] ^ same;
            if (!del[v]) {
              const res = solveRec(v);
              if (v != res) {
                ans ~= [same, v, res];
              }
            }
          }
        }
        return u;
        ////
        break;
      } else {
        sz[u] -= sz[vm];
        sz[vm] += sz[u];
        u = vm;
      }
    }
  }
  solveRec(0);
}

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

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      ans = [];
      solveCentroidDecomp;
      writeln(ans.length);
      foreach (op; ans) {
        writeln(op[0] + 1, " ", op[1] + 1, " ", op[2] + 1);
      }
    }
  } catch (EOFException e) {
  }
}

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

int N;
int[] A, B;

int[][] G;
int[][] ans;

void solveCentroidDecomp() {
  auto sz = new int[N];
  auto del = new bool[N];
  void dfsSz(int u, int p) {
    sz[u] = 1;
    foreach (i; G[u]) {
      const v = A[i] ^ B[i] ^ u;
      if (v != p) {
        dfsSz(v, u);
        sz[u] += sz[v];
      }
    }
  }
  dfsSz(0, -1);

  // r: centroid
  void solveSubtree(int r) {
    debug {
      string dfsDebug(int u, int p) {
        string ret = u.to!string;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v] && v != p) {
            ret ~= "(" ~ dfsDebug(v, u) ~ ")";
          }
        }
        return ret;
      }
      writeln("solveSubtree ", dfsDebug(r, -1));
    }
    //
    void dfs(int u, int p, int d) {
      //
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v] && v != p) {
          dfs(v, u, d + 1);
        }
      }
    }
    foreach (i; G[r]) {
      const v = A[i] ^ B[i] ^ r;
      if (!del[v]) {
        dfs(v, r, 1);
        //
      }
    }
    //
  }

  // void solveRec(int u) {
  int solveRec(int u) {
    for (; ; ) {
      int vm = -1;
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v]) {
          if (vm == -1 || sz[vm] < sz[v]) {
            vm = v;
          }
        }
      }
      if (vm == -1 || sz[u] >= 2 * sz[vm]) {
        solveSubtree(u);
        del[u] = true;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v]) {
            // solveRec(v);
            const res = solveRec(v);
            if (sz[u] - sz[v] > sz[v] && v != res) {
              ans ~= [u, v, res];
            }
          }
        }
        // break;
        return u;
      } else {
        sz[u] -= sz[vm];
        sz[vm] += sz[u];
        u = vm;
      }
    }
  }
  solveRec(0);
}

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

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      ans = [];
      solveCentroidDecomp;
      writeln(ans.length);
      foreach (op; ans) {
        writeln(op[0] + 1, " ", op[1] + 1, " ", op[2] + 1);
      }
    }
  } catch (EOFException e) {
  }
}

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

int N;
int[] A, B;

int[][] G;
int[][] ans;

void solveCentroidDecomp() {
  auto sz = new int[N];
  auto del = new bool[N];
  void dfsSz(int u, int p) {
    sz[u] = 1;
    foreach (i; G[u]) {
      const v = A[i] ^ B[i] ^ u;
      if (v != p) {
        dfsSz(v, u);
        sz[u] += sz[v];
      }
    }
  }
  dfsSz(0, -1);

  // r: centroid
  void solveSubtree(int r) {
    debug {
      string dfsDebug(int u, int p) {
        string ret = u.to!string;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v] && v != p) {
            ret ~= "(" ~ dfsDebug(v, u) ~ ")";
          }
        }
        return ret;
      }
      writeln("solveSubtree ", dfsDebug(r, -1));
    }
    //
    void dfs(int u, int p, int d) {
      //
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v] && v != p) {
          dfs(v, u, d + 1);
        }
      }
    }
    foreach (i; G[r]) {
      const v = A[i] ^ B[i] ^ r;
      if (!del[v]) {
        dfs(v, r, 1);
        //
      }
    }
    //
  }

  // void solveRec(int u) {
  int solveRec(int u) {
    for (; ; ) {
      int vm = -1;
      foreach (i; G[u]) {
        const v = A[i] ^ B[i] ^ u;
        if (!del[v]) {
          if (vm == -1 || sz[vm] < sz[v]) {
            vm = v;
          }
        }
      }
      if (vm == -1 || sz[u] >= 2 * sz[vm]) {
        solveSubtree(u);
        del[u] = true;
        /*
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v]) {
            solveRec(v);
          }
        }
        */
        ////
        int same = -1;
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v]) {
            if (sz[u] - sz[v] == sz[v]) {
              same = v;
            }
          }
        }
        foreach (i; G[u]) {
          const v = A[i] ^ B[i] ^ u;
          if (!del[v]) {
            if (v != same) {
              const res = solveRec(v);
              if (v != res) {
                ans ~= [u, v, res];
              }
            }
          }
        }
        if (same != -1) {
          foreach (i; G[same]) {
            const v = A[i] ^ B[i] ^ same;
            if (!del[v]) {
              const res = solveRec(v);
              if (v != res) {
                ans ~= [same, v, res];
              }
            }
          }
        }
        return u;
        ////
        break;
      } else {
        sz[u] -= sz[vm];
        sz[vm] += sz[u];
        u = vm;
      }
    }
  }
  solveRec(0);
}

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

      G = new int[][N];
      foreach (i; 0 .. N - 1) {
        G[A[i]] ~= i;
        G[B[i]] ~= i;
      }
      ans = [];
      solveCentroidDecomp;
      writeln(ans.length);
      foreach (op; ans) {
        writeln(op[0] + 1, " ", op[1] + 1, " ", op[2] + 1);
      }
    }
  } catch (EOFException e) {
  }
}


One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of lines in the description. Then follow n lines — for each goal the names of the teams that scored it. The names are non-empty lines consisting of uppercase Latin letters whose lengths do not exceed 10 symbols. It is guaranteed that the match did not end in a tie and the description contains no more than two different teams.

Print the name of the winning team. We remind you that in football the team that scores more goals is considered the winner.

import std.stdio;

void main() {
    int i;
    readf("%d\n", &i);
    string winner = "";
    int most = 0;
    int[string] m;
   // writeln("Entering loop");
    for (int j = 0; j < i; ++j) {
        //writeln("Reading");
        string t = readln();
        m[t] = m.get(t, 0) + 1;
        //writef("%s has %d\n", t, m[t]);
        if (m[t] > most) {
            most = m[t];
            winner = t;
        }
    }
    write(winner);
}

//ahmat
import core.stdc.stdio:scanf,printf,puts;
import core.bitop;
import std.stdio;
import std.string;
import std.algorithm;
import std.functional;
import std.array;
import std.container;
import std.conv;
import std.container;
import std.typecons;
import std.math;
import std.numeric;
pragma(inline,true);

void main(){
    int n=readln.strip.to!int;
    string s,w;
    int[string] aa;
    int ans=0;
    while(n--){
        s=readln.strip;
        aa[s]++;
        if(aa[s]>ans){
            w=s;
            ans=aa[s];
        }
    }
    writeln(w);
}

module cf_43A;

import std.stdio;

void main() {
    int n, maxGoals = 0;
    int[string] teamGoals;
    string teamName, winTeam;

    readf("%d", &n);
    for (int i = 0; i < n; ++i) {
        readf(" %s\n", &teamName);

        if (++teamGoals[teamName] > maxGoals) {
            winTeam = teamName;
            maxGoals = teamGoals[teamName];
        }
    }

    writeln(winTeam);
}


Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated.For example, Zookeeper can use two such operations: AABABBA $$$\to$$$ AABBA $$$\to$$$ AAA.Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string?

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 20000)$$$  — the number of test cases. The description of the test cases follows. Each of the next $$$t$$$ lines contains a single test case each, consisting of a non-empty string $$$s$$$: the string that Zookeeper needs to bomb. It is guaranteed that all symbols of $$$s$$$ are either 'A' or 'B'. It is guaranteed that the sum of $$$|s|$$$ (length of $$$s$$$) among all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer: the length of the shortest string that Zookeeper can make.

NoteFor the first test case, you can't make any moves, so the answer is $$$3$$$.For the second test case, one optimal sequence of moves is BABA $$$\to$$$ BA. So, the answer is $$$2$$$.For the third test case, one optimal sequence of moves is AABBBABBBB $$$\to$$$ AABBBABB $$$\to$$$ AABBBB $$$\to$$$ ABBB $$$\to$$$ AB $$$\to$$$ (empty string). So, the answer is $$$0$$$.

import std.stdio;
import std.string;
import std.array;

void main() {
	int t;
	readf("%d\n", &t);
	while(t--) {
		auto str = readln.strip;
		char[] stack;
		stack.reserve(str.length);
		foreach(c; str) {
			stack ~= c;
			if(stack.length >= 2) {
				if((stack[$-2] == 'A' || stack[$-2] == 'B') && stack[$-1] == 'B') {
					stack.popBack();
					stack.popBack();
				}
			}
		}

		writeln(stack.length);
	}
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		int res = s.length.to !(int);
		int a = 0, b = 0;
		foreach (c; s)
		{
			if (c == 'A')
			{
				a += 1;
			}
			else
			{
				b += 1;
				if (a > 0 && b > 0)
				{
					a -= 1;
					b -= 1;
					res -= 2;
				}
				else if (b >= 2)
				{
					b -= 2;
					res -= 2;
				}
			}
		}
		writeln (res);
	}
}

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 s = RD!string;

		int cnt, cnt_b;
		foreach_reverse (i; 0..s.length)
		{
			if (s[i] == 'B')
				++cnt_b;
			else if (cnt_b >= 1)
			{
				--cnt_b;
				cnt += 2;
			}
		}
		cnt += cnt_b - (cnt_b % 2);
		ans[ti] = cast(int)s.length - cnt;
	}

	foreach (e; ans)
		writeln(e);

	stdout.flush;
	debug readln;
}


Daniel is organizing a football tournament. He has come up with the following tournament format:   In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even.  Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be  games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games.Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers.

The first line contains a single integer n (1 ≤ n ≤ 1018), the number of games that should be played. 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 all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1.

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()
{
    ulong n;
    readf("%s", &n);
    readln;

    auto pows = [0].chain(recurrence!("a[n-1] * 2")(1L).until!(x => x > n));

    debug { pows.writeln; }

    ulong val(ulong n, ulong x, ulong sm) {
        if (2*n / x < x-1) { return n+1; }
        if (n / x < sm) { return n+1; }

        ulong opts = x * (x-1) / 2;
        ulong res = sm * x + x * (x-1) / 2;
        return res;
    }

    ulong[] ans;
    ulong sm = 0;
    foreach (i, e; pows.enumerate) {
        sm += e;
        ulong le = 1, r = n;
        while (le < r) {
            ulong md = (le + r) / 2;
            if (val(n, md, sm) < n) { le = md + 1; }
            else { r = md; }
        }

        if (val(n, le, sm) == n && le % 2 != 0) {
            debug { writeln(i, ' ', le, ' ', le * (1L << i)); }
            ans ~= le * (1L << i);
        }
    }

    if (ans.empty()) {
        writeln(-1);
        return;
    }

    ans.each!writeln;
}

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()
{
    ulong n;
    readf("%s", &n);
    readln;

    auto pows = [0].chain(recurrence!("a[n-1] * 2")(1L).until!(x => x > n));

    debug { pows.writeln; }

    ulong val(ulong n, ulong x, ulong sm) {
        if (2*n / x < x-1) { return n+1; }
        if (n / x < sm) { return n+1; }

        ulong opts = x * (x-1) / 2;
        ulong res = sm * x + x * (x-1) / 2;
        return res;
    }

    ulong[] ans;
    ulong sm = 0;
    foreach (i, e; pows.enumerate) {
        sm += e;
        ulong le = 1, r = n;
        while (le < r) {
            ulong md = (le + r) / 2;
            if (val(n, md, sm) < n) { le = md + 1; }
            else { r = md; }
        }

        if (val(n, le, sm) == n && le % 2 != 0) {
            debug { writeln(i, ' ', le, ' ', le * (1L << i)); }
            ans ~= le * (1L << i);
        }
    }

    if (ans.empty()) {
        writeln(-1);
        return;
    }

    ans.length.writeln;
    ans.each!writeln;
}


In fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.A permutation $$$p$$$ of size $$$n$$$ is given. A permutation of size $$$n$$$ is an array of size $$$n$$$ in which each integer from $$$1$$$ to $$$n$$$ occurs exactly once. For example, $$$[1, 4, 3, 2]$$$ and $$$[4, 2, 1, 3]$$$ are correct permutations while $$$[1, 2, 4]$$$ and $$$[1, 2, 2]$$$ are not.Let us consider an empty deque (double-ended queue). A deque is a data structure that supports adding elements to both the beginning and the end. So, if there are elements $$$[1, 5, 2]$$$ currently in the deque, adding an element $$$4$$$ to the beginning will produce the sequence $$$[\color{red}{4}, 1, 5, 2]$$$, and adding same element to the end will produce $$$[1, 5, 2, \color{red}{4}]$$$.The elements of the permutation are sequentially added to the initially empty deque, starting with $$$p_1$$$ and finishing with $$$p_n$$$. Before adding each element to the deque, you may choose whether to add it to the beginning or the end.For example, if we consider a permutation $$$p = [3, 1, 2, 4]$$$, one of the possible sequences of actions looks like this: $$$\quad$$$ 1.add $$$3$$$ to the end of the deque:deque has a sequence $$$[\color{red}{3}]$$$ in it;$$$\quad$$$ 2.add $$$1$$$ to the beginning of the deque:deque has a sequence $$$[\color{red}{1}, 3]$$$ in it;$$$\quad$$$ 3.add $$$2$$$ to the end of the deque:deque has a sequence $$$[1, 3, \color{red}{2}]$$$ in it;$$$\quad$$$ 4.add $$$4$$$ to the end of the deque:deque has a sequence $$$[1, 3, 2, \color{red}{4}]$$$ in it;Find the lexicographically smallest possible sequence of elements in the deque after the entire permutation has been processed. A sequence $$$[x_1, x_2, \ldots, x_n]$$$ is lexicographically smaller than the sequence $$$[y_1, y_2, \ldots, y_n]$$$ if there exists such $$$i \leq n$$$ that $$$x_1 = y_1$$$, $$$x_2 = y_2$$$, $$$\ldots$$$, $$$x_{i - 1} = y_{i - 1}$$$ and $$$x_i < y_i$$$. In other words, if the sequences $$$x$$$ and $$$y$$$ have some (possibly empty) matching prefix, and the next element of the sequence $$$x$$$ is strictly smaller than the corresponding element of the sequence $$$y$$$. For example, the sequence $$$[1, 3, 2, 4]$$$ is smaller than the sequence $$$[1, 3, 4, 2]$$$ because after the two matching elements $$$[1, 3]$$$ in the start the first sequence has an element $$$2$$$ which is smaller than the corresponding element $$$4$$$ in the second sequence.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases.  The first line of each test case description contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — permutation size. The second line of the description contains $$$n$$$ space-separated integers $$$p_i$$$ ($$$1 \le p_i \le n$$$; all $$$p_i$$$ are all unique) — elements of the permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should contain $$$n$$$ space-separated integer numbers — the elements of the lexicographically smallest permutation that is possible to find in the deque after executing the described algorithm.

NoteOne of the ways to get a lexicographically smallest permutation $$$[1, 3, 2, 4]$$$ from the permutation $$$[3, 1, 2, 4]$$$ (the first sample test case) is described in the problem statement.

immutable multi = true;

void solve(int tc)
{
	auto n = readInt!int;
	auto p = [0] ~ ma(n, readInt!int);
	auto position = new int[](n+1);
	foreach(i, pi; p)
	{
		position[pi] = cast(int)i;
	}
	auto len = n;
	auto insertFront = new bool[](n+1);
	foreach(v; 1 .. n + 1)
	{
		if (position[v] > len) continue;
		insertFront[position[v]] = true;
		len = position[v] - 1;
	}
	auto deque = DList!int();
	foreach(i; 1 .. n + 1)
	{
		if (insertFront[i])
		{
			deque.insertFront(p[i]);
		}
		else
		{
			deque.insertBack(p[i]);
		}
	}
	foreach(v; deque) write(v, " ");
	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;
// }}}


New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.

The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.

If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".

NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.

import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

void main() {
    int N, T; scanf("%d %d\n", &N, &T);
    auto as = readln.chomp.split(" ").map!(to!int).array;

    auto bs = new int[N];
    foreach (int i, a; as) {
        bs[i] = i + a;
    }

    bool dfs(int index) {
        if (index == T - 1) return true;
        if (bs[index] == 0) return false;
        return dfs(bs[index]);
    }

    writeln(dfs(0) ? "YES" : "NO");
}

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

void main(string[] args){
	int n, t;
	readf(" %s %s\n", &n, &t);
	--t;
	int[] line = to!(int[])(readln.strip.split) ~ 0;
	int point = 0;
	while(point < t)
		point += line[point];

	writeln(point == t ? "YES" : "NO");
}

import std.stdio;

int[] a;

void main() {

	int n, t;

	scanf("%d%d", &n, &t);
	--t;

	int c;
	foreach (i; 0 .. n - 1) {
		scanf("%d", &c);
		a ~= c;
	}

	int x = 0;
	while (x < t)
		x += a[x];

	puts((x == t) ? "YES" : "NO");
}

import std.stdio: writeln, stdin;
import std.regex: split, regex;
import std.string: strip;
import std.conv: to;
import std.algorithm.iteration: map;

void main()
{
  auto nt = stdin.readln.strip.split(regex(` +`)).map!(to!int);
  auto as = stdin.readln.strip.split(regex(` +`)).map!(to!int);
  auto n = nt[0], t = nt[1]-1;
  int i=0;
  while(i<t) i+=as[i];
  writeln(i==t ? "YES" : "NO");
}

import std.stdio;
import std.uni;
import std.string;
import core.stdc.stdio;
import std.array;
import std.algorithm;
import std.string;
import std.math;

int main(string[] argv)
{
	int n, k;
	scanf("%d %d", &n, &k);
	int ts = 0;
	foreach (int i; 0..(n-1))
	{
		if (ts == (k-1))
		{
			write("YES");
			return 0;
		}
		int l;
		scanf("%d", &l);
		if (ts == i)
		{
			ts += l;
		}
	}
	if (ts == (k-1))
	{
		write("YES");
		return 0;
	}
	write("NO");
	return 0;
}

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.container;

void main()
{
	auto x = readln.split.map!(to!int);
	auto t = x[1] - 1;
	auto tp = readln.split.map!(to!int);
	int i;
	while (i < tp.length) {
		if (i == t) break;
		i += tp[i];
	}

	if (i == t) writeln("YES");
	else writeln("NO");
}

import std.stdio;

int[] a;

void main() {

	int n, t;

	scanf("%s %s", &n, &t);
	--t;

	int c;
	foreach (i; 0 .. n - 1) {
		readf(" %s", &c);
		a ~= c;
	}

	int x = 0;
	while (x < t)
		x += a[x];

	puts(x == t ? "YES" : "NO");
}

import std.stdio;
import std.uni;
import std.string;
import core.stdc.stdio;
import std.array;
import std.algorithm;
import std.string;
import std.math;

int main(string[] argv)
{
	int n, k;
	scanf("%d %d", &n, &k);
	int ts = 0;
	foreach (int i; 0..(n-1))
	{
		if (ts == (k-1))
		{
			write("YES");
			return 0;
		}
		int l;
		scanf("%d", &l);
		if (ts == i)
		{
			ts += l;
		}
	}
	write("NO");
	return 0;
}

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.container;

void main()
{
	auto x = readln.split.map!(to!int);
	auto t = x[1] - 1;
	auto tp = readln.split.map!(to!int);
	int i;
	while (i < tp.length) {
		writeln(i+1);
		if (i == t) {
			break;
		}
		i += tp[i];
	}

	if (i == t) {
		writeln("YES");
	} else {
		writeln("NO");
	}
}