Gargari got bored to play with the bishops and now, after solving the problem about them, he is trying to do math homework. In a math book he have found k permutations. Each of them consists of numbers 1, 2, ..., n in some order. Now he should find the length of the longest common subsequence of these permutations. Can you help Gargari?You can read about longest common subsequence there: https://en.wikipedia.org/wiki/Longest_common_subsequence_problem

The first line contains two integers n and k (1 ≤ n ≤ 1000; 2 ≤ k ≤ 5). Each of the next k lines contains integers 1, 2, ..., n in some order — description of the current permutation.

Print the length of the longest common subsequence.

NoteThe answer for the first test sample is subsequence [1, 2, 3].

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

int saiki(int num, int k, int[] dp, int[][] pos)
{
    if (dp[num] != -1)
    {
        return dp[num];
    }
    auto n = cast(int)dp.length - 1;
    dp[num] = 0;
    auto p = new int[k];
    foreach (i; 0 .. k)
    {
        p[i] = pos[i][num];
    }
    foreach (i; 1 .. n + 1)
    {
        if (i != num)
        {
            int j;
            for (j = 0; j < k; ++ j)
            {
                if (pos[j][i] < pos[j][num])
                {
                    break;
                }
            }
            if (j == k)
            {
                auto ret = saiki(i, k, dp, pos);
                dp[num] = max(dp[num], ret + 1);
            }
        }
    }
    return dp[num];
}

void solve(int[][] p)
{
    auto k = cast(int)p.length;
    auto n = cast(int)p[0].length;
    auto pos = new int[][](k, n + 1);
    foreach (i; 0 .. k)
    {
        pos[i][0] = -1;
        foreach (j; 0 .. n)
        {
            pos[i][p[i][j]] = j;
        }
    }
    auto dp = new int[n + 1];
    fill(dp, -1);
    auto ans = saiki(0, k, dp, pos);
    writeln(ans);
}

int main(string[] args)
{
    int n, k;
    while (readf("%d %d\n", &n, &k) == 2)
    {
        auto p = new int[][](k, n);
        foreach (i; 0 .. k)
        {
            foreach (j; 0 .. n)
            {
                readf(" %d", &p[i][j]);
            }
            readln();
        }
        solve(p);
    }
    return 0;
}

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

int saiki(int num, int k, int[] dp, int[][] pos)
{
    if (dp[num] != -1)
    {
        return dp[num];
    }
    auto n = cast(int)dp.length - 1;
    dp[num] = 0;
    foreach (i; 1 .. n + 1)
    {
        if (i != num)
        {
            int j;
            for (j = 0; j < k; ++ j)
            {
                if (pos[j][i] < pos[j][num])
                {
                    break;
                }
            }
            if (j == k)
            {
                auto ret = saiki(i, k, dp, pos);
                dp[num] = max(dp[num], ret + 1);
            }
        }
    }
    return dp[num];
}

void solve(int[][] p)
{
    auto k = cast(int)p.length;
    auto n = cast(int)p[0].length;
    auto pos = new int[][](k, n + 1);
    foreach (i; 0 .. k)
    {
        pos[i][0] = -1;
        foreach (j; 0 .. n)
        {
            pos[i][p[i][j]] = j;
        }
    }
    auto dp = new int[n + 1];
    fill(dp, -1);
    auto ans = saiki(0, k, dp, pos);
    writeln(ans);
}

int main(string[] args)
{
    int n, k;
    while (readf("%d %d\n", &n, &k) == 2)
    {
        auto p = new int[][](k, n);
        foreach (i; 0 .. k)
        {
            foreach (j; 0 .. n)
            {
                readf(" %d", &p[i][j]);
            }
            readln();
        }
        solve(p);
    }
    return 0;
}

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

int saiki(int num, int n, int k, int[] dp, int[][] pos)
{
    if (dp[num] != -1)
    {
        return dp[num];
    }
    dp[num] = 0;
    foreach (i; 1 .. n + 1)
    {
        if (i != num)
        {
            int j;
            for (j = 0; j < k; ++ j)
            {
                if (pos[j][i] < pos[j][num])
                {
                    break;
                }
            }
            if (j == k)
            {
                auto ret = saiki(i, n, k, dp, pos);
                dp[num] = max(dp[num], ret + 1);
            }
        }
    }
    return dp[num];
}

void solve(int[][] p)
{
    auto k = cast(int)p.length;
    auto n = cast(int)p[0].length;
    auto pos = new int[][](k, n + 1);
    foreach (i; 0 .. k)
    {
        pos[i][0] = -1;
        foreach (j; 0 .. n)
        {
            pos[i][p[i][j]] = j;
        }
    }
    auto dp = new int[n + 1];
    fill(dp, -1);
    auto ans = saiki(0, n, k, dp, pos);
    writeln(ans);
}

int main(string[] args)
{
    int n, k;
    while (readf("%d %d\n", &n, &k) == 2)
    {
        auto p = new int[][](k, n);
        foreach (i; 0 .. k)
        {
            foreach (j; 0 .. n)
            {
                readf(" %d", &p[i][j]);
            }
            readln();
        }
        solve(p);
    }
    return 0;
}

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!int;
  auto adj = new int[][](n, n);
  foreach(ref row; adj) row[] = 1;
  foreach(permutation; 0 .. k)
    {
      auto currentPermutation = next!int(n);
      currentPermutation[] -= 1;
      foreach(i; 0 .. n)
	{
	  auto ci = currentPermutation[i];
	  foreach(j; i .. n)
	    {
	      auto cj = currentPermutation[j];
	      adj[ci][cj] &= 1;
	      adj[cj][ci] &= 0;
	    }
	}
    }
  int longestSequenceFrom(int v)
  {
    int longestContinuation = 0;
    foreach(w; 0 .. n)
      if (adj[v][w])
	{
	  longestContinuation =
	    max(longestContinuation,
		memoize!longestSequenceFrom(w));
	}
    return 1 + longestContinuation;
  }
  iota(0, n).map!(memoize!longestSequenceFrom).fold!max.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;
	}
    }
}


Utkarsh is forced to play yet another one of Ashish's games. The game progresses turn by turn and as usual, Ashish moves first.Consider the 2D plane. There is a token which is initially at $$$(0,0)$$$. In one move a player must increase either the $$$x$$$ coordinate or the $$$y$$$ coordinate of the token by exactly $$$k$$$. In doing so, the player must ensure that the token stays within a (Euclidean) distance $$$d$$$ from $$$(0,0)$$$.In other words, if after a move the coordinates of the token are $$$(p,q)$$$, then $$$p^2 + q^2 \leq d^2$$$ must hold.The game ends when a player is unable to make a move. It can be shown that the game will end in a finite number of moves. If both players play optimally, determine who will win.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The only line of each test case contains two space separated integers $$$d$$$ ($$$1 \leq d \leq 10^5$$$) and $$$k$$$ ($$$1 \leq k \leq d$$$).

For each test case, if Ashish wins the game, print "Ashish", otherwise print "Utkarsh" (without the quotes).

NoteIn the first test case, one possible sequence of moves can be$$$(0, 0) \xrightarrow{\text{Ashish }} (0, 1) \xrightarrow{\text{Utkarsh }} (0, 2)$$$.Ashish has no moves left, so Utkarsh wins.

// Cheese-Cracker: cheese-cracker.github.io

ll dist(ll x, ll y){
    return x*x + y*y;
}

// Main Logic Here
void play(){
    ll d, k;
    d = rd; k = rd;
    ll up = 0;
    ll down = 0;
    bool side = 0;
    while(1){
        ll dis1 = dist(up+k, down);
        ll dis2 = dist(up, down+k);
        if(dis1 < dis2){
            up += k;
        }else{
            down += k;
        }
        if(min(dis1, dis2) > d*d){
            if(side){
                writeln("Ashish");
                return;
            }else{
                writeln("Utkarsh");
                return;
            }
        }
        side = !side;
    }
}

int main(){
    long t = 1;
    t = rd;        // Toggle for testcases!
    while(t--) play();  // Let's play!
    return 0;
}

/**********That's All Folks!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
static string[] inp;    // Read input
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(){ auto r = readln.chomp.split.to!(T[]); return r; }
alias ll = long;
alias tup = Tuple!(long, "x",  long, "y");
void show(A...)(A a) { debug{ foreach(t; a){ stderr.write(t, "| "); } stderr.writeln; } } // Debug
/* Add if TLE, T max(T = long)(T a, T b){ return (a > b) ? a : b; } */

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

string FMT_F = "%.10f";

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

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

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

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

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

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

		bool f(long x)
		{
			return ((x*k)^^2)*2 <= d^^2;
		}
		auto r = binarySearch!(f)(0, d/k+1);
		debug writeln("r:", r);
		if (r == 0)
			ans[ti] = true;
		else if ((r*k)^^2 + ((r+1)*k)^^2 <= d^^2)
		{
			ans[ti] = true;
		}
	}

	foreach (e; ans)
	{
		writeln(e ? "Ashish" : "Utkarsh");
	}
	stdout.flush;
	debug readln;
}


One fine October day a mathematics teacher Vasily Petrov went to a class and saw there n pupils who sat at the  desks, two people at each desk. Vasily quickly realized that number n is even. Like all true mathematicians, Vasily has all students numbered from 1 to n.But Vasily Petrov did not like the way the children were seated at the desks. According to him, the students whose numbers differ by 1, can not sit together, as they talk to each other all the time, distract others and misbehave.On the other hand, if a righthanded student sits at the left end of the desk and a lefthanded student sits at the right end of the desk, they hit elbows all the time and distract each other. In other cases, the students who sit at the same desk, do not interfere with each other.Vasily knows very well which students are lefthanders and which ones are righthanders, and he asks you to come up with any order that meets these two uncomplicated conditions (students do not talk to each other and do not bump their elbows). It is guaranteed that the input is such that at least one way to seat the students always exists.

The first input line contains a single even integer n (4 ≤ n ≤ 100) — the number of students in the class. The second line contains exactly n capital English letters "L" and "R". If the i-th letter at the second line equals "L", then the student number i is a lefthander, otherwise he is a righthander.

Print  integer pairs, one pair per line. In the i-th line print the numbers of students that will sit at the i-th desk. The first number in the pair stands for the student who is sitting to the left, and the second number stands for the student who is sitting to the right. Separate the numbers in the pairs by spaces. If there are multiple solutions, print any of them.

import std.stdio : readln, writeln, chomp, File;
import std.conv : to;

void solve()
{
	auto ifp = File("input.txt", "r");
	auto ofp = File("output.txt", "w");
	int n = ifp.readln.chomp.to!int;
	string str = ifp.readln.chomp;
	int h = n>>1;
	for(int i=0; i<h; ++i){
		// 右手左手ダメ絶対
		if(str[i]=='R' && str[i+h]=='L'){
			ofp.writeln(i+h+1, " ",  i+1);
		}else{	// 他はそのまんま
			ofp.writeln(i+1, " ", i+h+1);
		}
	}
}

void main()
{
	solve();
}

import std.stdio : File, readln, writeln, chomp;
import std.string : split;
import std.conv : to;

int[][] solve(int N, char[] list)
{
	int[][] ans;
	foreach(i; 0 .. N/2){
		ans ~= [0, 0];
	}
	foreach(ptr, ite; list){
		bool flag = true;
		if(ite=='R'){
			for(int x=1; 0<=x && flag; --x){
				for(int y=N/2-1; 0<=y && flag; --y){
					if(ans[y][x] == 0){
						ans[y][x] = ptr+1;
						flag = false;
					}
				}
			}
		}else{
			for(int x=0; x<2 && flag; ++x){
				for(int y=0; y<N/2 && flag; ++y){
					if(ans[y][x] == 0){
						ans[y][x] = ptr + 1;
						flag = false;
					}
				}
			}
		}
	}
	return ans.dup;
}

void io()
{
	auto input = File("input.txt", "r");
	auto output = File("output.txt", "w");
	int N = input.readln().chomp().to!int;
	char[] list = input.readln().chomp().dup;
	int[][] ans = solve(N, list);
	foreach(ite; ans){
		output.writeln(ite[0], " ", ite[1]);
	}
}

void main()
{
	io();
}


You work in the quality control department of technical support for a large company. Your job is to make sure all client issues have been resolved.Today you need to check a copy of a dialog between a client and a technical support manager. According to the rules of work, each message of the client must be followed by one or several messages, which are the answer of a support manager. However, sometimes clients ask questions so quickly that some of the manager's answers to old questions appear after the client has asked some new questions.Due to the privacy policy, the full text of messages is not available to you, only the order of messages is visible, as well as the type of each message: a customer question or a response from the technical support manager. It is guaranteed that the dialog begins with the question of the client.You have to determine, if this dialog may correspond to the rules of work described above, or the rules are certainly breached.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 500$$$). Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the total number of messages in the dialog. The second line of each test case consists of $$$n$$$ characters "Q" and "A", describing types of messages in the dialog in chronological order. Character "Q" denotes the message with client question, and character "A" — the message with technical support manager answer. It is guaranteed that the first character in the line equals to "Q".

For each test case print "Yes" (without quotes) if dialog may correspond to the rules of work, or "No" (without quotes) otherwise.

5

4

QQAA

4

QQAQ

3

QAA

1

Q

14

QAQQAQAAQQQAAA

NoteIn the first test case the two questions from the client are followed with two specialist's answers. So this dialog may correspond to the rules of work.In the second test case one of the first two questions was not answered.In the third test case the technical support manager sent two messaged as the answer to the only message of the client.

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    long n;
    readf!" %d "(n);
    auto s = readln.strip;
    int q = 0;
    bool good = true;
    foreach (ch ; s) {
      if (ch == 'Q') {
        q++;
      } else {
        q--;
        if (q < 0)
          q = 0;
      }
    }
    writeln(q > 0 ? "No" : "Yes");
  }
}


We call a string good, if after merging all the consecutive equal characters, the resulting string is palindrome. For example, "aabba" is good, because after the merging step it will become "aba".Given a string, you have to find two values:  the number of good substrings of even length;  the number of good substrings of odd length.

The first line of the input contains a single string of length n (1 ≤ n ≤ 105). Each character of the string will be either 'a' or 'b'.

Print two space-separated integers: the number of good substrings of even length and the number of good substrings of odd length.

NoteIn example 1, there are three good substrings ("b", "b", and "bb"). One of them has even length and two of them have odd length.In example 2, there are six good substrings (i.e. "b", "a", "a", "b", "aa", "baab"). Two of them have even length and four of them have odd length.In example 3, there are seven good substrings (i.e. "b", "a", "b", "b", "bb", "bab", "babb"). Two of them have even length and five of them have odd length.DefinitionsA substring s[l, r] (1 ≤ l ≤ r ≤ n) of string s = s1s2... sn is string slsl + 1... sr.A string s = s1s2... sn is a palindrome if it is equal to string snsn - 1... s1.

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

string S;

void main(string[] args) {
	try {
	for (; ; ) {
		S = readToken;
		long[2] ans;
		long[2][2] cnt;
		foreach (i, c; S) {
			++cnt[i & 1][c - 'a'];
			foreach (j; 0 .. 2) {
				ans[j] += cnt[(i ^ j ^ 1) & 1][c - 'a'];
			}
		}
		writeln(ans[0], " ", ans[1]);
	}
	} catch (EOFException) {}
}


You are given $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. Is it possible to arrange them on a circle so that each number is strictly greater than both its neighbors or strictly smaller than both its neighbors?In other words, check if there exists a rearrangement $$$b_1, b_2, \ldots, b_n$$$ of the integers $$$a_1, a_2, \ldots, a_n$$$ such that for each $$$i$$$ from $$$1$$$ to $$$n$$$ at least one of the following conditions holds: $$$b_{i-1} < b_i > b_{i+1}$$$ $$$b_{i-1} > b_i < b_{i+1}$$$To make sense of the previous formulas for $$$i=1$$$ and $$$i=n$$$, one shall define $$$b_0=b_n$$$ and $$$b_{n+1}=b_1$$$.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 3\cdot 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 10^5$$$)  — the number of integers. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$2\cdot 10^5$$$.

For each test case, if it is not possible to arrange the numbers on the circle satisfying the conditions from the statement, output $$$\texttt{NO}$$$. You can output each letter in any case. Otherwise, output $$$\texttt{YES}$$$. In the second line, output $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$, which are a rearrangement of $$$a_1, a_2, \ldots, a_n$$$ and satisfy the conditions from the statement. If there are multiple valid ways to arrange the numbers, you can output any of them.

NoteIt can be shown that there are no valid arrangements for the first and the third test cases.In the second test case, the arrangement $$$[1, 8, 4, 9]$$$ works. In this arrangement, $$$1$$$ and $$$4$$$ are both smaller than their neighbors, and $$$8, 9$$$ are larger.In the fourth test case, the arrangement $$$[1, 11, 1, 111, 1, 1111]$$$ works. In this arrangement, the three elements equal to $$$1$$$ are smaller than their neighbors, while all other elements are larger than their neighbors.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		bool ok = (n % 2 == 0);
		if (ok)
		{
			sort (a);
			int [] c;
			foreach (i; 0..n / 2)
			{
				c ~= a[i];
				c ~= a[i + $ / 2];
			}
			a = c;
			auto b = a.cycle;
			ok &= n.iota.all !(i =>
			    (b[i] < b[i + 1] && b[i + 1] > b[i + 2]) ||
			    (b[i] > b[i + 1] && b[i + 1] < b[i + 2]));
		}
		if (ok)
		{
			writeln ("YES");
			writefln !("%(%s %)") (a);
		}
		else
		{
			writeln ("NO");
		}
	}
}

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

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

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

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

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

        int[] ans;
        if (N % 2 == 0) {
          foreach (i; 0 .. N / 2) {
            ans ~= A[i];
            ans ~= A[i + N / 2];
          }
          debug {
            writeln(ans);
          }
          bool ok = true;
          foreach (i; 0 .. N) {
            const a0 = ans[i];
            const a1 = ans[(i + 1 == N) ? 0 : (i + 1)];
            ok = ok && ((i % 2 == 0) ? (a0 < a1) : (a0 > a1));
          }
          if (!ok) {
            ans = null;
          }
        }

        if (ans) {
          writeln("YES");
          foreach (i; 0 .. N) {
            if (i) write(" ");
            write(ans[i]);
          }
          writeln;
        } else {
          writeln("NO");
        }
      }
    }
  } catch (EOFException e) {
  }
}


Alica and Bob are playing a game.Initially they have a binary string $$$s$$$ consisting of only characters 0 and 1.Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent characters of string $$$s$$$ and delete them. For example, if $$$s = 1011001$$$ then the following moves are possible:   delete $$$s_1$$$ and $$$s_2$$$: $$$\textbf{10}11001 \rightarrow 11001$$$;  delete $$$s_2$$$ and $$$s_3$$$: $$$1\textbf{01}1001 \rightarrow 11001$$$;  delete $$$s_4$$$ and $$$s_5$$$: $$$101\textbf{10}01 \rightarrow 10101$$$;  delete $$$s_6$$$ and $$$s_7$$$: $$$10110\textbf{01} \rightarrow 10110$$$. If a player can't make any move, they lose. Both players play optimally. You have to determine if Alice can win.

First line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Only line of each test case contains one string $$$s$$$ ($$$1 \le |s| \le 100$$$), consisting of only characters 0 and 1.

For each test case print answer in the single line. If Alice can win print DA (YES in Russian) in any register. Otherwise print NET (NO in Russian) in any register.

NoteIn the first test case after Alice's move string $$$s$$$ become empty and Bob can not make any move.In the second test case Alice can not make any move initially.In the third test case after Alice's move string $$$s$$$ turn into $$$01$$$. Then, after Bob's move string $$$s$$$ become empty and Alice can not make any move.

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;
		auto balance = abs (s.count ('0').to !(int) -
		    s.count ('1').to !(int));
		auto moves = (s.length - balance) / 2;
		writeln ((moves & 1) ? "DA" : "NET");
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		long cnt0, cnt1;
		foreach (c; s)
		{
			if (c == '0')
				++cnt0;
			else
				++cnt1;
		}

		ans[ti] = min(cnt0, cnt1) % 2 == 1;
	}

	foreach (e; ans)
	{
		writeln(e ? "DA" : "NET");
	}
	stdout.flush;
	debug readln;
}

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;
		auto balance = abs (s.count ('0') - s.count ('1'));
		auto moves = (s.length - balance) / 2;
		writeln ((moves & 1) ? "DA" : "NET");
	}
}


You are given an array $$$a_1, a_2, \dots, a_n$$$ where all $$$a_i$$$ are integers and greater than $$$0$$$. In one operation, you can choose two different indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$). If $$$gcd(a_i, a_j)$$$ is equal to the minimum element of the whole array $$$a$$$, you can swap $$$a_i$$$ and $$$a_j$$$. $$$gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Now you'd like to make $$$a$$$ non-decreasing using the operation any number of times (possibly zero). Determine if you can do this. An array $$$a$$$ is non-decreasing if and only if $$$a_1 \le a_2 \le \ldots \le a_n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases.  The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of array $$$a$$$.  The second line of each test case contains $$$n$$$ positive integers $$$a_1, a_2, \ldots a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array itself.  It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, output "YES" if it is possible to make the array $$$a$$$ non-decreasing using the described operation, or "NO" if it is impossible to do so.

Note In the first and third sample, the array is already non-decreasing. In the second sample, we can swap $$$a_1$$$ and $$$a_3$$$ first, and swap $$$a_1$$$ and $$$a_5$$$ second to make the array non-decreasing. In the forth sample, we cannot the array non-decreasing using the operation.

module _template;
import std.stdio;
import std.string;
import std.algorithm;
import std.container;
import std.range;
import std.math;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

struct IO {
        string[] tk;
        string readString() {
                while (tk.empty)
                        tk = readln.split;
                auto tkt = tk.front;
                tk.popFront;
                return tkt;
        }
        int readInt() {
                return readString.to!int;
        }
        double readDouble() {
                return readString.to!double;
        }
}

void main() {
        IO cin;
        int t = 1;
        t = cin.readInt;
        while (t--) {
                int n = cin.readInt;
                int[] arr = new int[n];
                foreach (ref i; arr) i = cin.readInt;
                bool flag = false;
                if (isSorted(arr)) writeln("YES");
                else {
                        int[] arr2 = arr.dup;
                        sort(arr);
                        for (int i = 0; i < n; i++) {
                                if (arr[i] != arr2[i]) {
                                        if (gcd(arr[i], arr2[i]) && arr2[i] % arr[0] != 0) {
                                                flag = true;
                                                break;
                                        }
                                }
                        }
                        if (flag) writeln("NO");
                        else writeln("YES");
                }
        }
}

// Vicfred
// https://codeforces.com/contest/1401/problem/C
// math
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

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

    while(t--) {
        long n = readln.chomp.to!long;
        long[] a = readln.split.map!(to!long).array;
        long[] b;
        b ~= a;

        b.sort;

        long m = b[0];

        bool flag = true;
        for(int i = 0; i < n; i++)
            if(a[i] != b[i] && a[i]%m != 0)
                flag = false;

        if(flag)
            "YES".writeln;
        else
            "NO".writeln;
    }

}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto m = a.minElement;
		auto p = a.filter !(x => x % m == 0).array;
		sort (p);
		foreach (ref c; a)
		{
			if (c % m == 0)
			{
				c = p.front;
				p.popFront ();
			}
		}
		writeln (a.isSorted ? "YES" : "NO");
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		long[] arr0, arr1;
		auto zero = new bool[](n);
		foreach (i; 0..n)
		{
			if (a[i] % x)
			{
				arr1 ~= a[i];
			}
			else
			{
				arr0 ~= a[i];
				zero[i] = true;
			}
		}
		arr0.sort();
		long last;
		bool ok = true;
		foreach (i; 0..n)
		{
			long y;
			if (zero[i])
			{
				y = arr0.front; arr0.popFront;
			}
			else
			{
				y = arr1.front; arr1.popFront;
			}
			if (y < last)
			{
				ok = false;
				break;
			}
			last = y;
		}
		ans[ti] = ok;
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

		long[] arr;
		foreach (i; 0..n)
		{
			if (a[i] % x)
			{
				arr ~= a[i];
			}
		}
		if (arr.empty)
		{
			ans[ti] = true;
			continue;
		}

		bool ok = true;
		foreach (i; 0..arr.length-1)
		{
			if (arr[i+1] < arr[i])
			{
				ok = false;
			}
		}
		ans[ti] = ok;
	}

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


People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:  every integer from 1 to n2 appears in the table exactly once;  in each row numbers are situated in increasing order;  the sum of numbers in the k-th column is maximum possible. Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.

The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.

First print the sum of the integers in the k-th column of the required table. Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on. If there are multiple suitable table, you are allowed to print any.

import std.stdio, std.string, std.conv;
import std.typecons;
import std.algorithm;
void main(){
    auto nk = readln.chomp.split.map!(to!int);
    int n = nk[0];
    int k = nk[1];

    int l = 1;
    int r = n*n - n*(n-k+1) + 1;

    int sum = 0;
    for(int x = r; x <= n*n; x += n-k+1){
        sum += x;
    }

    writeln(sum);

    foreach(x; 0..n){
        foreach(i; 0..(k-1)){
            write(l);
            l++;
            write(" ");
        }
        foreach(i; k..(n+1)){
            write(r);
            r++;
            if(i!=n)write(" ");
        }
        writeln();
    }
}

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

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

    int[][] ktable = new int[][](n, n);

    int p = 1;
    foreach (i; 0..n) {
        foreach (j; 0..(k - 1)) {
            ktable[i][j] = p;
            p++;
        }
    }

    int answer = 0;
    foreach (i; 0..n) {
        foreach (j; (k - 1)..n) {
            ktable[i][j] = p;
            if (j == (k - 1)) {
                answer += p;
            }
            p++;
        }
    }

    answer.writeln;
    foreach (row; ktable)
        row.map!(to!string).join(" ").writeln;
}

import std.stdio, std.string, std.conv;
import std.typecons;
import std.algorithm;
void main(){
    auto nk = readln.chomp.split.map!(to!int);
    int n = nk[0];
    int k = nk[1];

    int l = 1;
    int r = n*n - n*(n-k+1) + 1;

    int sum = 0;
    for(int x = r; x < n*n; x += n-k+1){
        sum += x;
    }

    writeln(sum);

    foreach(x; 0..n){
        foreach(i; 0..(k-1)){
            write(l);
            l++;
            write(" ");
        }
        foreach(i; k..(n+1)){
            write(r);
            r++;
            if(i!=n)write(" ");
        }
        writeln();
    }
}


You are given two integers $$$a$$$ and $$$b$$$, and $$$q$$$ queries. The $$$i$$$-th query consists of two numbers $$$l_i$$$ and $$$r_i$$$, and the answer to it is the number of integers $$$x$$$ such that $$$l_i \le x \le r_i$$$, and $$$((x \bmod a) \bmod b) \ne ((x \bmod b) \bmod a)$$$. Calculate the answer for each query.Recall that $$$y \bmod z$$$ is the remainder of the division of $$$y$$$ by $$$z$$$. For example, $$$5 \bmod 3 = 2$$$, $$$7 \bmod 8 = 7$$$, $$$9 \bmod 4 = 1$$$, $$$9 \bmod 9 = 0$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow. The first line of each test case contains three integers $$$a$$$, $$$b$$$ and $$$q$$$ ($$$1 \le a, b \le 200$$$; $$$1 \le q \le 500$$$). Then $$$q$$$ lines follow, each containing two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^{18}$$$) for the corresponding query.

For each test case, print $$$q$$$ integers — the answers to the queries of this test case in the order they appear.

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm, std.array, std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
int inz(long t){ return to!int(t); }
static string[] tempstr;
T rd(T = long)() { while(!tempstr.length) tempstr = readln.chomp.split; string res = tempstr[0]; tempstr.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }

ll getcnt(ll x, ll[] cnts){
    ll mod = to!ll(cnts.length) - 1;
    ll tim = (x / mod) * cnts[inz(mod)];
    tim += cnts[inz(x % mod)];
    return tim;
}

void play(){
    ll a, b;
    a = rd!int; b = rd!int;
    int q = rd!int;
    int lcmab = a * b / gcd(a, b);
    auto tills = new ll[](lcmab+1);
    ll cnt = 0;
    foreach(i; 1..lcmab+1){
        if((i % a) % b != (i % b) % a){
            ++cnt;
        }
        tills[i] = cnt;
    }
    foreach(i; 0..q){
        ll x, y;
        x = rd; y = rd;
        ll cntx = getcnt(x-1, tills);
        ll cnty = getcnt(y, tills);
        write(cnty - cntx, " ");
    }
    writeln;
}

int main(){
    ll t = 1;
    t = rd;        // Toggle!
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto abq = readln.split.to!(int[]);
        long A = abq[0];
        long B = abq[1];
        if (A > B) swap(A, B);

        long solve(long n) {
            if (n < B) return n;

            auto lcm = A * B / gcd(A, B);
            long r = min(n, B-1) + (n / lcm - 1) * B;
            auto m = n / lcm * lcm;
            r += min(m + B, n+1) - m;
            return r;
        }

        auto Q = abq[2];
        long[] res;
        foreach (_q; 0..Q) {
            auto lr = readln.split.to!(long[]);
            auto l = lr[0];
            auto r = lr[1];
            res ~= r - l + 1 - solve(r) + solve(l-1);
        }
        writeln(res.to!(string[]).join(" "));
    }
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int a, b, q;
		readf !(" %s %s %s") (a, b, q);
		auto total = a * b;
		int [] s;
		s ~= 0;
		foreach (i; 1..total + 1)
		{
			s ~= s.back + ((i % a) % b != (i % b) % a);
		}

		long go (long limit)
		{
			return limit / total * s[total] +
			    s[cast (int) (limit % total)];
		}

		long [] answer;
		foreach (w; 0..q)
		{
			long l, r;
			readf !(" %s %s") (l, r);
			answer ~= go (r) - go (l - 1);
		}
		writefln !("%(%s %)") (answer);
	}
}

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

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

void main() {
  auto r = new InputReader ();
  immutable nt = r.next!uint ();
  foreach (tid; 0 .. nt) {
    const int a = r.next!int;
    const int b = r.next!int;
    const int q = r.next!int;
    const int m = a * b;
    auto x = new int[m];
    foreach (i; 0 .. m) {
      if (((i % a) % b) != ((i % b) % a)) x[i] = 1;
    }
    auto y = x.cumulativeFold!"a+b".array;
    int s = y.back;
    long cntLess (long t) {
      long u1 = t / m;
      int u2 = (t % m).to!int;
      long res = u1 * s;
      if (u2 > 0) res += y[u2-1];
      return res;
    }
    auto res = new long[q];
    foreach (qid; 0 .. q) {
      long L = r.next!long;
      long R = r.next!long;
      res[qid] = cntLess (R + 1) - cntLess (L);
    }
    writefln!("%(%s %)")(res);
  }
}

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto abq = readln.split.to!(int[]);
        long A = abq[0];
        long B = abq[1];
        if (A > B) swap(A, B);

        long solve(long n) {
            if (n <= B) return n;

            auto lcm = A * B / gcd(A, B);
            long r = min(n, B-1) + (n / lcm - 1) * B;
            auto m = n / lcm * lcm;
            r += min(m + B, n) - m;
            return r;
        }

        auto Q = abq[2];
        long[] res;
        foreach (_q; 0..Q) {
            auto lr = readln.split.to!(long[]);
            auto l = lr[0];
            auto r = lr[1];
            res ~= r - l + 1 - solve(r) + solve(l-1);
        }
        writeln(res.to!(string[]).join(" "));
    }
}

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

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto abq = readln.split.to!(int[]);
        long A = abq[0];
        long B = abq[1];
        if (A > B) swap(A, B);

        long solve(long n) {
            if (n <= B) return n+1;

            auto lcm = A * B / gcd(A, B);
            long r = min(n, B) + (n / lcm - 1) * B;
            auto m = n / lcm * lcm;
            r += min(m + B, n+1) - m;
            return r;
        }

        auto Q = abq[2];
        long[] res;
        foreach (_q; 0..Q) {
            auto lr = readln.split.to!(long[]);
            auto l = lr[0];
            auto r = lr[1];
            res ~= r - l + 1 - solve(r) + solve(l-1);
        }
        writeln(res.to!(string[]).join(" "));
    }
}


In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another.Note that in this problem you do not have to minimize the number of swaps — your task is to find any sequence that is no longer than n.

The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of array elements. The second line contains elements of array: a0, a1, ..., an - 1 ( - 109 ≤ ai ≤ 109), where ai is the i-th element of the array. The elements are numerated from 0 to n - 1 from left to right. Some integers may appear in the array more than once.

In the first line print k (0 ≤ k ≤ n) — the number of swaps. Next k lines must contain the descriptions of the k swaps, one per line. Each swap should be printed as a pair of integers i, j (0 ≤ i, j ≤ n - 1), representing the swap of elements ai and aj. You can print indices in the pairs in any order. The swaps are performed in the order they appear in the output, from the first to the last. It is allowed to print i = j and swap the same pair of elements multiple times. If there are multiple answers, print any of them. It is guaranteed that at least one answer exists.

import std.stdio;
import std.algorithm;

const int MAX = 3005;
int n;
int[MAX] a;

void main() {
    readf(" %s", n);
    foreach(i; 0..n) readf(" %s", a[i]);

    writeln(n);
    foreach(i; 0..n) {
        auto k = i;
        foreach(j; i+1..n)
            if (a[j] < a[k]) k = j;
        auto tmp = a[i];
        a[i] = a[k];
        a[k] = tmp;
        writeln(i, " ", k);
    }
}

import std.stdio;
import std.algorithm;

const int MAX = 3005;
int n;
int[MAX] a;

void main() {
    readf(" %s", n);
    foreach(i; 0..n) readf(" %s", a[i]);

    writeln(n);
    foreach(i; 0..n) {
        auto k = i;
        foreach(j; i+1..n)
            if (a[j] < a[k]) k = j;
        auto tmp = a[i];
        a[i] = a[k];
        a[k] = tmp;
        writeln(i, " ", k);
    }
    writeln(a[0..n]);
}


By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher:You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type:  For given numbers xi and vi assign value vi to element axi.  For given numbers li and ri you've got to calculate sum , where f0 = f1 = 1 and at i ≥ 2: fi = fi - 1 + fi - 2.  For a group of three numbers li ri di you should increase value ax by di for all x (li ≤ x ≤ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem.

The first line contains two integers n and m (1 ≤ n, m ≤ 2·105) — the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≤ ti ≤ 3) — the operation type:    if ti = 1, then next follow two integers xi vi (1 ≤ xi ≤ n, 0 ≤ vi ≤ 105);  if ti = 2, then next follow two integers li ri (1 ≤ li ≤ ri ≤ n);  if ti = 3, then next follow three integers li ri di (1 ≤ li ≤ ri ≤ n, 0 ≤ di ≤ 105).  The input limits for scoring 30 points are (subproblem E1):    It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type.  The input limits for scoring 70 points are (subproblems E1+E2):    It is guaranteed that there will be queries of the 1-st and 2-nd type only.  The input limits for scoring 100 points are (subproblems E1+E2+E3):    No extra limitations.

For each query print the calculated sum modulo 1000000000 (109).

module main;

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

auto immutable mod = 1000000000;

int calc(int[] a, int[] f, int left, int right)
{
    int ans = 0;
    for (int i = left - 1; i < right; ++ i)
    {
        int cur = (to!long(a[i]) * f[i - left + 1]) % mod;
        ans = (ans + cur) % mod;
    }
    return ans;
}

int main(string[] args)
{
    int n, m;
    auto f = new int[100];
    f[0] = f[1] = 1;
    for (int i = 2; i < 100; ++ i) f[i] = (f[i - 1] + f[i - 2]) % mod;
    while (scanf("%d%d", &n, &m) == 2)
    {
        auto a = new int[n];
        foreach (i; 0 .. n) scanf("%d", &a[i]);
        foreach (i; 0 .. m)
        {
            int type, left, right, idx, val, inc;
            scanf("%d", &type);
            if (type == 1)
            {
                scanf("%d%d", &idx, &val);
                a[idx - 1] = val;
            }
            else if (type == 2)
            {
                scanf("%d%d", &left, &right);
                writeln(calc(a, f, left, right));
            }
            else
            {
                scanf("%d%d%d", &left, &right, &inc);
                for (int j = left - 1; j < right; ++ j) a[j] = (a[j] + inc) % mod;
            }
        }
    }
	return 0;
}

module main;

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

auto immutable mod = 1000000000;

int calc(int[] a, int[] f, int left, int right)
{
    int ans = 0;
    for (int i = left - 1; i < right; ++ i)
    {
        int cur = (to!long(a[i]) * f[i - left + 1]) % mod;
        ans += cur;
    }
    return ans;
}

int main(string[] args)
{
    int n, m;
    auto f = new int[100];
    f[0] = f[1] = 1;
    for (int i = 2; i < 100; ++ i) f[i] = (f[i - 1] + f[i - 2]) % mod;
    while (scanf("%d%d", &n, &m) == 2)
    {
        auto a = new int[n];
        foreach (i; 0 .. n) scanf("%d", &a[i]);
        foreach (i; 0 .. m)
        {
            int type, left, right, idx, val, inc;
            scanf("%d", &type);
            if (type == 1)
            {
                scanf("%d%d", &idx, &val);
                a[idx - 1] = val;
            }
            else if (type == 2)
            {
                scanf("%d%d", &left, &right);
                writeln(calc(a, f, left, right));
            }
            else
            {
                scanf("%d%d%d", &left, &right, &inc);
                for (int j = left - 1; j < right; ++ j) a[j] = (a[j] + inc) % mod;
            }
        }
    }
	return 0;
}

module main;

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

auto immutable mod = 1000000000;

int calc(int[] a, int[] f, int left, int right)
{
    int ans = 0;
    for (int i = left - 1; i < right; ++ i)
    {
        int cur = (to!long(a[i]) * f[i - left + 1]) % mod;
        ans += cur;
    }
    return ans;
}

int main(string[] args)
{
    int n, m;
    auto f = new int[100];
    f[0] = f[1] = 1;
    for (int i = 2; i < 100; ++ i) f[i] = (f[i - 1] + f[i - 2]) % mod;
    while (scanf("%d%d", &n, &m) == 2)
    {
        auto a = new int[n];
        foreach (i; 0 .. n) scanf("%d", &a[i]);
        foreach (i; 0 .. m)
        {
            int type, left, right, idx, val, inc;
            scanf("%d", &type);
            if (type == 1)
            {
                scanf("%d%d", &idx, &val);
                a[idx - 1] = val;
            }
            else if (type == 2)
            {
                scanf("%d%d", &left, &right);
                writeln(calc(a, f, left, right));
            }
            else
            {
                scanf("%d%d%d", &left, &right, &inc);
                for (int j = left - 1; j < right; ++ j) a[j] += inc;
            }
        }
    }
	return 0;
}


The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[1, 2, 4, 3, 2]$$$ the answer is $$$4$$$ (you take $$$1$$$ and the sequence becomes $$$[2, 4, 3, 2]$$$, then you take the rightmost element $$$2$$$ and the sequence becomes $$$[2, 4, 3]$$$, then you take $$$3$$$ and the sequence becomes $$$[2, 4]$$$ and then you take $$$4$$$ and the sequence becomes $$$[2]$$$, the obtained increasing sequence is $$$[1, 2, 3, 4]$$$).

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

In the first line of the output print $$$k$$$ — the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.

NoteThe first example is described in the problem statement.

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

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

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

    void gole(int p, int lm, int lst, ref dchar[] ans) {
        while (p <= lm && a[p] > lst) {
            ans ~= 'L';
            lst = a[p];
            ++p;
        }

        debug { writeln(ans.length); }
    }
    void gor(int p, int lm, int lst, ref dchar[] ans) {
        while (p >= lm && a[p] > lst) {
            ans ~= 'R';
            lst = a[p];
            --p;
        }

        debug { writeln(ans.length); }
    }
    int lst = 0;
    int le = 0, r = n-1;
    dchar[] ans;
    while (le <= r) {
        int leok = lst < a[le];
        int rok = lst < a[r];
        if (!leok && !rok) {
            break;
        }
        if (!leok) {
            gor(r, le, lst, ans);
            break;
        }
        if (!rok) {
            gole(le, r, lst, ans);
            break;
        }

        if (a[le] < a[r]) {
            ans ~= 'L';
            lst = a[le];
            ++le;
        } else if (a[r] < a[le]) {
            ans ~= 'R';
            lst = a[r];
            --r;
        } else {
            dchar[] ansle;
            dchar[] ansr;
            gole(le, r, lst, ansle);
            gor(r, le, lst, ansr);

            if (ansle.length > ansr.length) { ans ~= ansle; }
            else { ans ~= ansr; }
            break;
        }
    }

    ans.length.writeln;
    ans.writeln;
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto p = a.length - a.findAdjacent !(q{a >= b}).length;
		auto q = a.length - a.retro.findAdjacent !(q{a >= b}).length;
		auto lo = a.take (min (p + 1, n)).array;
		auto hi = a.retro.take (min (q + 1, n)).array;
		debug {writeln (lo, " ", hi);}

		string res;
		while (true)
		{
			if (lo.empty)
			{
				res ~= 'R'.repeat (hi.length).text;
				break;
			}

			if (hi.empty)
			{
				res ~= 'L'.repeat (lo.length).text;
				break;
			}

			if (lo.front < hi.front)
			{
				res ~= 'L';
				lo.popFront ();
			}
			else if (lo.front > hi.front)
			{
				res ~= 'R';
				hi.popFront ();
			}
			else if (lo.length < hi.length)
			{
				res ~= 'R'.repeat (hi.length).text;
				break;
			}
			else
			{
				res ~= 'L'.repeat (lo.length).text;
				break;
			}
		}

		res.length = min (res.length, n);
		writeln (res.length);
		writeln (res);
	}
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T read(T)(){ return read.to!T; }
T[] read(T)(long n){ return n.iota.map!(_ => read!T).array; }
T[][] read(T)(long m, long n){ return m.iota.map!(_ => read!T(n)).array; }
// ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- ----- //

void solve(){

	int n = read.to!int;
	long[] as;
	foreach(i; 0 .. n) as ~= read.to!long;

	string ans;
	int i = 0, j = n - 1;
	long x = -1;
	while(i <= j){
		if(as[i] < as[j]){
			if(x < as[i]) x = as[i], ans ~= "L", i += 1;
			else if(x < as[j]) x = as[j], ans ~= "R", j -= 1;
			else break;
		}
		else if(as[j] < as[i]){
			if(x < as[j]) x = as[j], ans ~= "R", j -= 1;
			else if(x < as[i]) x = as[i], ans ~= "L", i += 1;
			else break;
		}
		else{
			if(x >= as[i]) break;
			int c1 = i;
			while(c1 < j && as[c1] < as[c1 + 1]) c1 += 1;
			int c2 = j;
			while(i < c2 && as[c2] < as[c2 - 1]) c2 -= 1;
			if(c1 - i < j - c2) x = as[j], ans ~= "R", j -= 1;
			else x = as[i], ans ~= "L", i += 1;
		}
	}

	ans.length.writeln;
	ans.writeln;
}

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

string FMT_F = "%.10f";

static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
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; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

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

void main()
{
	auto N = RD!uint;
	auto a = RDR.ARR;

	auto cnt_l = new long[](N+1);
	{
		long last;
		foreach_reverse (i; 0..N)
		{
			if (a[i] < last)
				cnt_l[i] = cnt_l[i+1] + 1;

			last = a[i];
		}
	}
	auto cnt_r = new long[](N+1);
	{
		long last;
		foreach (i; 0..N)
		{
			if (a[i] < last)
				cnt_r[i+1] = cnt_r[i] + 1;

			last = a[i];
		}
	}

	debug writeln(cnt_l);
	debug writeln(cnt_r);

	string ans;
	long last;
	uint l, r = cast(uint)(a.length);

	void popL()
	{
		last = a.front;
		a.popFront;
		ans ~= "L";
		++l;
	}
	void popR()
	{
		last = a.back;
		a.popBack;
		ans ~= "R";
		--r;
	}

	while (!a.empty)
	{
		if (a.front > last && a.front == a.back)
		{
			debug writeln(cnt_l[l], " ", cnt_r[r]);
			if (cnt_l[l] >= cnt_r[r])
			{
				popL();
			}
			else
			{
				popR;
			}
		}
		else if (a.front > last && a.front < a.back)
		{
			popL();
		}
		else if (a.back > last && a.back < a.front)
		{
			popR();
		}
		else if (a.front > last)
		{
			popL();
		}
		else if (a.back > last)
		{
			popR();
		}
		else
		{
			break;
		}
	}

	writeln(ans.length);
	writeln(ans);
	stdout.flush();
	debug readln();
}

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

string FMT_F = "%.10f";

static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
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; }
bool minimize(T)(ref T x, T y) { if (x > y) { x = y; return true; } else { return false; } }
bool maximize(T)(ref T x, T y) { if (x < y) { x = y; return true; } else { return false; } }

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

void main()
{
	auto N = RD;
	auto a = RDR.ARR;

	string ans;
	long last;
	while (!a.empty)
	{
		if (a.front > last && a.front == a.back)
		{
			uint l, r = cast(uint)(a.length - 1);
			while (abs(l - r) >= 0)
			{
				if (abs(l - r) <= 1)
				{
					if (a[l] <= a[r])
					{
						last = a.front;
						a.popFront;
						ans ~= "L";
						break;
					}
					else
					{
						last = a.back;
						a.popBack;
						ans ~= "R";
						break;
					}
				}
				else if (a[l] == a[r])
				{
					++l;
					--r;
				}
				else if (a[l] <= a[r])
				{
					last = a.front;
					a.popFront;
					ans ~= "L";
					break;
				}
				else
				{
					last = a.back;
					a.popBack;
					ans ~= "R";
					break;
				}
			}
		}
		else if (a.front > last && a.front < a.back)
		{
			last = a.front;
			a.popFront;
			ans ~= "L";
		}
		else if (a.back > last && a.back < a.front)
		{
			last = a.back;
			a.popBack;
			ans ~= "R";
		}
		else if (a.front > last)
		{
			last = a.front;
			a.popFront;
			ans ~= "L";
		}
		else if (a.back > last)
		{
			last = a.back;
			a.popBack;
			ans ~= "R";
		}
		else
		{
			break;
		}
	}

	writeln(ans.length);
	writeln(ans);
	stdout.flush();
	debug readln();
}


One day, early in the morning, you decided to buy yourself a bag of chips in the nearby store. The store has chips of $$$n$$$ different flavors. A bag of the $$$i$$$-th flavor costs $$$a_i$$$ burles.The store may run out of some flavors, so you'll decide which one to buy after arriving there. But there are two major flaws in this plan:   you have only coins of $$$1$$$, $$$2$$$ and $$$3$$$ burles;  since it's morning, the store will ask you to pay in exact change, i. e. if you choose the $$$i$$$-th flavor, you'll have to pay exactly $$$a_i$$$ burles. Coins are heavy, so you'd like to take the least possible number of coins in total. That's why you are wondering: what is the minimum total number of coins you should take with you, so you can buy a bag of chips of any flavor in exact change?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of flavors in the store. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the cost of one bag of each flavor.

For each test case, print one integer — the minimum number of coins you need to buy one bag of any flavor you'll choose in exact change.

NoteIn the first test case, you should, for example, take with you $$$445$$$ coins of value $$$3$$$ and $$$1$$$ coin of value $$$2$$$. So, $$$1337 = 445 \cdot 3 + 1 \cdot 2$$$.In the second test case, you should, for example, take $$$2$$$ coins of value $$$3$$$ and $$$2$$$ coins of value $$$2$$$. So you can pay either exactly $$$8 = 2 \cdot 3 + 1 \cdot 2$$$ or $$$10 = 2 \cdot 3 + 2 \cdot 2$$$.In the third test case, it's enough to take $$$1$$$ coin of value $$$3$$$ and $$$2$$$ coins of value $$$1$$$.

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

int canpay(int[] a, int mcnt1, int mcnt2)
{
  int mcnt3 = 0;
  foreach (x ; a) {
    bool good = false;
    int opt_mcnt3 = int.max;
    foreach (cnt1 ; 0 .. mcnt1 + 1) {
      foreach (cnt2 ; 0 .. mcnt2 + 1) {
        int y = x - cnt1 - 2 * cnt2;
        if (y < 0 || y % 3 != 0)
          continue;
        opt_mcnt3 = min(opt_mcnt3, y / 3);
        good = true;
      }
    }
    if (!good)
      return -1;
    mcnt3 = max(mcnt3, opt_mcnt3);
  }
  return mcnt3;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!int).array;
    int best = int.max;
    foreach (mcnt1 ; 0 .. 3 + 1) {
      foreach (mcnt2 ; 0 .. 3 + 1) {
        int mcnt3 = canpay(a, mcnt1, mcnt2);
        if (mcnt3 < 0)
          continue;
        int coins = mcnt1 + mcnt2 + mcnt3;
        best = min(best, coins);
      }
    }
    writeln(best);
  }
}


Two integer sequences existed initially, one of them was strictly increasing, and another one — strictly decreasing.Strictly increasing sequence is a sequence of integers $$$[x_1 < x_2 < \dots < x_k]$$$. And strictly decreasing sequence is a sequence of integers $$$[y_1 > y_2 > \dots > y_l]$$$. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.Elements of increasing sequence were inserted between elements of the decreasing one (and, possibly, before its first element and after its last element) without changing the order. For example, sequences $$$[1, 3, 4]$$$ and $$$[10, 4, 2]$$$ can produce the following resulting sequences: $$$[10, \textbf{1}, \textbf{3}, 4, 2, \textbf{4}]$$$, $$$[\textbf{1}, \textbf{3}, \textbf{4}, 10, 4, 2]$$$. The following sequence cannot be the result of these insertions: $$$[\textbf{1}, 10, \textbf{4}, 4, \textbf{3}, 2]$$$ because the order of elements in the increasing sequence was changed.Let the obtained sequence be $$$a$$$. This sequence $$$a$$$ is given in the input. Your task is to find any two suitable initial sequences. One of them should be strictly increasing, and another one — strictly decreasing. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.If there is a contradiction in the input and it is impossible to split the given sequence $$$a$$$ into one increasing sequence and one decreasing sequence, print "NO".

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

If there is a contradiction in the input and it is impossible to split the given sequence $$$a$$$ into one increasing sequence and one decreasing sequence, print "NO" in the first line. Otherwise print "YES" in the first line. In the second line, print a sequence of $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ should be either $$$0$$$ or $$$1$$$ for each $$$i$$$ from $$$1$$$ to $$$n$$$. The $$$i$$$-th element of this sequence should be $$$0$$$ if the $$$i$$$-th element of $$$a$$$ belongs to the increasing sequence, and $$$1$$$ otherwise. Note that the empty sequence and the sequence consisting of one element can be considered as increasing or decreasing.

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 INF = 1L << 59;

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

    auto dp = new long[][](N, 2);
    foreach (i; 0..N) dp[i][0] = -INF, dp[i][1] = INF;

    auto par = new int[][](N, 2);
    foreach (i; 0..N) par[i][] = -1;

    dp[0][0] = INF;
    dp[0][1] = -INF;
    par[0][] = 0;

    foreach (i; 1..N) {
        if (par[i-1][0] != -1 && A[i-1] < A[i]) {
            if (dp[i][0] <= dp[i-1][0]) {
                dp[i][0] = dp[i-1][0];
                par[i][0] = 0;
            }
        }
        if (par[i-1][1] != -1 && dp[i-1][1] < A[i]) {
            if (dp[i][0] <= A[i-1]) {
                dp[i][0] = A[i-1];
                par[i][0] = 1;
            }
        }
        if (par[i-1][1] != -1 && A[i-1] > A[i]) {
            if (dp[i][1] >= dp[i-1][1]) {
                dp[i][1] = dp[i-1][1];
                par[i][1] = 1;
            }
        }
        if (par[i-1][0] != -1 && dp[i-1][0] > A[i]) {
            if (dp[i][1] >= A[i-1]) {
                dp[i][1] = A[i-1];
                par[i][1] = 0;
            }
        }
    }

    auto ans = new int[](N);

    bool ok = true;
    int p = 0;

    foreach_reverse (i; 0..N) {
        if (par[i][p] == -1) {
            ok = false;
            break;
        }
        ans[i] = p;
        p = par[i][p];
    }

    if (ok) {
        writeln("YES");
        ans.map!(to!string).join(" ").writeln;
        return;
    }

    ok = true;
    p = 1;

    foreach_reverse (i; 0..N) {
        if (par[i][p] == -1) {
            ok = false;
            break;
        }
        ans[i] = p;
        p = par[i][p];
    }

    if (ok) {
        writeln("YES");
        ans.map!(to!string).join(" ").writeln;
        return;
    }

    writeln("NO");
}


The prison of your city has n prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer c of the prisoners to a prison located in another city.For this reason, he made the n prisoners to stand in a line, with a number written on their chests. The number is the severity of the crime he/she has committed. The greater the number, the more severe his/her crime was.Then, the mayor told you to choose the c prisoners, who will be transferred to the other prison. He also imposed two conditions. They are,  The chosen c prisoners has to form a contiguous segment of prisoners.  Any of the chosen prisoner's crime level should not be greater then t. Because, that will make the prisoner a severe criminal and the mayor doesn't want to take the risk of his running away during the transfer. Find the number of ways you can choose the c prisoners.

The first line of input will contain three space separated integers n (1 ≤ n ≤ 2·105), t (0 ≤ t ≤ 109) and c (1 ≤ c ≤ n). The next line will contain n space separated integers, the ith integer is the severity ith prisoner's crime. The value of crime severities will be non-negative and will not exceed 109.

Print a single integer — the number of ways you can choose the c prisoners.

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

int n, c, t;

void main() {
  scanf("%d%d%d\n", &n, &t, &c);
  auto a = readln.split.map!(to!int).array;
  size_t p = 0;
  int r = 0;
  foreach (i, v; a) {
    if (v > t) {
      p = i + 1;
    }
    if (i - p + 1 >= c) {
      r++;
    }
  }
  writeln(r);
}

import std.stdio;

void main() {
    auto pline = new ulong[](2*100_000);

    long n, t, c;

    readf("%s %s %s\n", &n, &t, &c);

    for(int i; i < n; ++i) {
        readf("%s ", &pline[i]);
    }

    int acc;

    auto tline = new long[](1);
    tline[0] = 0;

    for(int i; i < n; ++i) {
        if(pline[i] > t)
            tline ~= i + 1;
        //writeln(tline[$ - 1]);
    }
    tline ~= n + 1;

    for( int i = 1; i < tline.length; ++i ) {
        if( tline[i] - tline[i - 1] - 1 >= c ) {
            acc += (tline[i] - tline[i - 1]) - c;
        }
    }

    writeln(acc);
}

import std.stdio;

void main() {
	auto pline = new ulong[](2*100_000);

	long n, t, c;

	readf("%s %s %s\n", &n, &t, &c);

	for(int i; i < n; ++i) {
		readf("%s ", &pline[i]);
	}

	int acc;

	auto tline = new ulong[](1);
	tline[0] = 0;

	for(int i; i < n; ++i) {
		if(pline[i] > t)
			tline ~= i;
	}
	tline ~= n + 1;
	//writeln("last n: ", tline[$ - 1]);
	for( int i = 1; i < tline.length; ++i ) {
		if( tline[i] - tline[i - 1] - 1 >= c ) {
			//writeln(acc);
			acc += (tline[i] - tline[i - 1]) - c;
		}
	}

	writeln(acc);
}

import std.stdio;

void main() {
    auto pline = new ulong[](2*100_000);

    long n, t, c;

    readf("%s %s %s\n", &n, &t, &c);

    for(int i; i < n; ++i) {
        readf("%s ", &pline[i]);
    }

    int acc;

    auto tline = new long[](1);
    tline[0] = 0;

    for(int i; i < n; ++i) {
        if(pline[i] > t)
            tline ~= i;
    }
    tline ~= n + 1;

    for( int i = 1; i < tline.length; ++i ) {
        if( tline[i] - tline[i - 1] - 1 >= c ) {
            acc += (tline[i] - tline[i - 1]) - c;
        }
    }

    writeln(acc);
}


Michael and Joe are playing a game. The game is played on a grid with $$$n$$$ rows and $$$m$$$ columns, filled with distinct integers. We denote the square on the $$$i$$$-th ($$$1\le i\le n$$$) row and $$$j$$$-th ($$$1\le j\le m$$$) column by $$$(i, j)$$$ and the number there by $$$a_{ij}$$$.Michael starts by saying two numbers $$$h$$$ ($$$1\le h \le n$$$) and $$$w$$$ ($$$1\le w \le m$$$). Then Joe picks any $$$h\times w$$$ subrectangle of the board (without Michael seeing).Formally, an $$$h\times w$$$ subrectangle starts at some square $$$(a,b)$$$ where $$$1 \le a \le n-h+1$$$ and $$$1 \le b \le m-w+1$$$. It contains all squares $$$(i,j)$$$ for $$$a \le i \le a+h-1$$$ and $$$b \le j \le b+w-1$$$.    Possible move by Joe if Michael says $$$3\times 2$$$ (with maximum of $$$15$$$). Finally, Michael has to guess the maximum number in the subrectangle. He wins if he gets it right.Because Michael doesn't like big numbers, he wants the area of the chosen subrectangle (that is, $$$h \cdot w$$$), to be as small as possible, while still ensuring that he wins, not depending on Joe's choice. Help Michael out by finding this minimum possible area. It can be shown that Michael can always choose $$$h, w$$$ for which he can ensure that he wins.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 20$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 40$$$)  — the size of the grid. Each of the following $$$n$$$ lines contains $$$m$$$ integers. The $$$j$$$-th integer on the $$$i$$$-th line is $$$a_{ij}$$$ ($$$-10^9 \le a_{ij} \le 10^9$$$)  — the element in the cell $$$(i, j)$$$. It is guaranteed that all the numbers are distinct (that is, if $$$a_{i_1j_1} = a_{i_2j_2}$$$, then $$$i_1 = i_2, j_1 = j_2$$$).

For each test case print a single positive integer  — the minimum possible area the subrectangle can have while still ensuring that Michael can guarantee the victory.

NoteIn the first test case, the grid is $$$1\times 1$$$, so the only possible choice for $$$h, w$$$ is $$$h = 1, w = 1$$$, giving an area of $$$h\cdot w = 1$$$.The grid from the second test case is drawn in the statement. It can be shown that with $$$h = 3, w = 3$$$ Michael can guarantee the victory and that any choice with $$$h\cdot w \le 8$$$ doesn't.

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

void solve(){
    int n = scan!int;
    int m = scan!int;
    long maxx = -1000_000_000;
    long mw = 1;
    long mh = 1;
    for(int i = 0; i < n; ++i){
        for(int j = 0; j < m; ++j){
            long num = scan;
            if(num > maxx){
                maxx = num;
                mh = max(i + 1, n - i);
                mw = max(j + 1, m - j);
            }
        }
    }
    writeln(mh * mw);
}

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

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


Berland has n cities connected by m bidirectional roads. No road connects a city to itself, and each pair of cities is connected by no more than one road. It is not guaranteed that you can get from any city to any other one, using only the existing roads.The President of Berland decided to make changes to the road system and instructed the Ministry of Transport to make this reform. Now, each road should be unidirectional (only lead from one city to another).In order not to cause great resentment among residents, the reform needs to be conducted so that there can be as few separate cities as possible. A city is considered separate, if no road leads into it, while it is allowed to have roads leading from this city.Help the Ministry of Transport to find the minimum possible number of separate cities after the reform.

The first line of the input contains two positive integers, n and m — the number of the cities and the number of roads in Berland (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000).  Next m lines contain the descriptions of the roads: the i-th road is determined by two distinct integers xi, yi (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the numbers of the cities connected by the i-th road. It is guaranteed that there is no more than one road between each pair of cities, but it is not guaranteed that from any city you can get to any other one, using only roads.

Print a single integer — the minimum number of separated cities after the reform.

NoteIn the first sample the following road orientation is allowed: , , .The second sample: , , , , .The third sample: , , , , .

import std.stdio;
import std.typecons;

int n, m;
Tuple!(int, int)[] roads;
int[] nOutgoing;
int[][] outgoing;
bool[] visited;

bool isTree(int u, int v = -1)
{
    visited[u] = true;

    for (int i = 0; i < outgoing[u].length; i++) {
        int w = outgoing[u][i];
        if (w != v && (visited[w] || !isTree(w, u))) {
            return false;
        }

    }
    return true;
}

void main()
{
    readf("%d %d", &n, &m);
    nOutgoing = new int[n];
    outgoing = new int[][n];
    roads = new Tuple!(int, int)[m];
    visited = new bool[n];
    for (int i = 0; i < m; i++) {
        readf(" %d %d", &roads[i][0], &roads[i][1]);

        roads[i][0]--;
        roads[i][1]--;

        nOutgoing[roads[i][0]]++;
        nOutgoing[roads[i][1]]++;
    }
    for (int i = 0; i < n; i++) {
        outgoing[i] = new int[nOutgoing[i]];
    }
    for (int i = 0; i < m; i++) {
        int x = roads[i][0];
        int y = roads[i][1];

        outgoing[x][--nOutgoing[x]] = y;
        outgoing[y][--nOutgoing[y]] = x;
    }

    int result = 0;
    for (int i = 0; i < n; i++) {
        if (!visited[i] && isTree(i)) {
            result++;
        }
    }

    writef("%d\n", result);
}

import std.stdio;
import std.typecons;

int n, m;
Tuple!(int, int)[] roads;
int[] nOutgoing;
int[][] outgoing;
bool[] visited;

bool isTree(int u, int v = -1)
{
    visited[u] = true;

    for (int i = 0; i < outgoing[u].length; i++) {
        int w = outgoing[u][i];
        if (w != v && (visited[w] || !isTree(w, u))) {
            return false;
        }

    }
    return v != -1 || outgoing[u].length > 0;
}

void main()
{
    readf("%d %d", &n, &m);
    nOutgoing = new int[n];
    outgoing = new int[][n];
    roads = new Tuple!(int, int)[m];
    visited = new bool[n];
    for (int i = 0; i < m; i++) {
        readf(" %d %d", &roads[i][0], &roads[i][1]);

        roads[i][0]--;
        roads[i][1]--;

        nOutgoing[roads[i][0]]++;
        nOutgoing[roads[i][1]]++;
    }
    for (int i = 0; i < n; i++) {
        outgoing[i] = new int[nOutgoing[i]];
    }
    for (int i = 0; i < m; i++) {
        int x = roads[i][0];
        int y = roads[i][1];

        outgoing[x][--nOutgoing[x]] = y;
        outgoing[y][--nOutgoing[y]] = x;
    }

    int result = 0;
    for (int i = 0; i < n; i++) {
        if (!visited[i] && isTree(i)) {
            result++;
        }
    }

    writef("%d\n", result);
}