Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.

The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'.

For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes).

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;

class StrTreeNode
{
  StrTreeNode[3] children;
  bool isTerminal = false;
}

void insert(StrTreeNode strTree, string str)
{
  if (str.empty) {strTree.isTerminal = true; return;}
  int ch = str[0] - 'a';
  if (strTree.children[ch] is null) strTree.children[ch] = new StrTreeNode;
  insert(strTree.children[ch], str[1 .. $]);
}

bool contains(StrTreeNode strTree, string str, bool usedBad = false)
{
  if (str.empty) return usedBad && strTree.isTerminal;
  int ch = str[0] - 'a';
  if (usedBad)
    {
      if (strTree.children[ch] is null) return false;
      return contains(strTree.children[ch], str[1 .. $], true);
    }
  else
    {
      bool result = false;
      foreach(usedChar; 0 .. 3)
	if (strTree.children[usedChar] !is null)
	  result |= contains(strTree.children[usedChar], str[1 .. $], usedChar != ch);
      return result;
    }
}

void main(string[] args)
{
  inputFile = stdin;
  auto n = next!int;
  auto m = next!int;
  auto inputStrings = next!string(n);
  auto queryStrings = next!string(m);
  auto root = new StrTreeNode;
  foreach(inputString; inputStrings)
    root.insert(inputString);
  foreach(queryString; queryStrings)
    writeln(root.contains(queryString)? "YES" : "NO");
}
ulong bitCnt(long x)
{
  ulong cnt = 0;
  while(x) {cnt += x & 1; x>>=1;}
  return cnt;
}
alias Arr(T) = Mat!(T, 1);
struct Mat(T, size_t dimension)
{
  T[] _baseArray;
  T[] _slice;
  size_t[dimension] _sizes; size_t dim(size_t i) {return _sizes[i];}
  size_t[dimension] _indexer;
  this(T[] baseArray, size_t[dimension] sizes)
  {
    _baseArray = baseArray;
    _sizes = sizes;
    _indexer[dimension - 1] = 1;
    static foreach_reverse(i; 0 .. dimension - 1)
      _indexer[i] = _indexer[i + 1] * _sizes[i + 1];
    auto requiredSize = _indexer[0] * _sizes[0];
    debug assert(_baseArray.length >= requiredSize);
    _slice = _baseArray[0 .. requiredSize];
  }
  this(size_t[dimension] sizes)
  {
    size_t reqSize = 1;
    static foreach(i; 0 .. dimension)
      reqSize *= sizes[i];
    this(new T[](reqSize), sizes);
  }
  ref auto opIndex()
  {
    pragma(inline, true);
    return _slice[];
  }
  ref auto opIndex(I...)(I i)
  {
    pragma(inline, true);
    debug assert(i.length <= dimension);
    size_t index = mixin(iota(0, i.length).map!(j => text("i[", j, "]*_indexer[", j, "]")).join("+"));
    static if (i.length == dimension)
      {
	return _slice[index];
      }
    else
      {
	enum sliceDimension = dimension - i.length;
	size_t[sliceDimension] remSizes = _sizes[i.length .. $];
	auto basePortion = _slice[index .. index + _indexer[i.length - 1]];
 	return Mat!(T, sliceDimension)(basePortion, remSizes);
      }
  }
  static if (dimension == 2)
    {
      auto identity()
      {
	debug assert(dim(0) == dim(1));
	auto n = dim(0);
	auto id = Mat!(T, 2)([n, n]);
	foreach(k; 0 .. n)
	  id[k, k] = T(1);
	return id;
      }
      bool canMultiply(Mat!(T, 2) b)
      {
	return this.dim(1) == b.dim(0);
      }
      auto opBinary(string op)(Mat!(T, 2) b)
	if (op == "*")
	  {
	    debug assert(canMultiply(b));
	    auto res = Mat!(T, 2)([this.dim(0), b.dim(1)]);
	    foreach(i; 0 .. res.dim(0))
	      foreach(k; 0 .. this.dim(1))
		foreach(j; 0 .. res.dim(1))
		  res[i, j] = res[i, j] + this[i, k] * b[k, j];
	    return res;
	  }
      auto opBinary(string op)(ulong exp)
	if (op == "^^")
	  {
	    return this.pow(identity, exp);
	  }
      mixin interiorBinPow;
    }
}

struct Mod(T, ulong mod)
{
  alias This = Mod!(T, mod);
  T _rep; T rep() {return _rep;}
  this(W)(W w)
  {
    _rep = ((cast(T) w)%mod + mod) % mod;
  }
  static auto plainConstruct(T t)
  {
    pragma(inline, true);
    debug assert(t >= 0 && t < mod);
    auto res = Mod!(T, mod).init;
    res._rep = t;
    return res;
  }
  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.plainConstruct(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plainConstruct(resrep);
      }
    else static if (op == "*")
      {
	return This(_rep * b._rep);
      }
  }
}

mixin template interiorBinPow()
{
  alias ThisType = typeof(this);
  auto pow(ThisType res, ulong exp)
    {
      if (exp < 0) debug assert(0);
      auto pow = this;
      while(exp)
	{
	  if (exp & 1)
	    res = res * pow;
	  pow = pow * pow;
	  exp >>= 1;
	}
      return res;
    }
}

// INPUT
File inputFile;
DList!string _words;
void _wordsFill()
{
  while (_words.empty) _words.insertBack(inputFile.readln.split);
}
string popWord()
{
  _wordsFill;
  auto word = _words.front;
  _words.removeFront;
  return word;
}
string peekWord()
{
  _wordsFill;
  return _words.front;
}
T next(T)()
{
  return to!T(popWord);
}
T peek(T)()
{
  return to!T(peekWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}

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;

class StrTreeNode
{
  StrTreeNode[3] children;
  bool isTerminal = false;
}

void insert(StrTreeNode strTree, string str)
{
  if (str.empty) {strTree.isTerminal = true; return;}
  int ch = str[0] - 'a';
  if (strTree.children[ch] is null) strTree.children[ch] = new StrTreeNode;
  insert(strTree.children[ch], str[1 .. $]);
}

bool contains(StrTreeNode strTree, string str, bool usedBad = false)
{
  if (str.empty) return strTree.isTerminal;
  int ch = str[0] - 'a';
  if (usedBad)
    {
      if (strTree.children[ch] is null) return false;
      return contains(strTree.children[ch], str[1 .. $], true);
    }
  else
    {
      bool result = false;
      foreach(usedChar; 0 .. 3)
	if (strTree.children[usedChar] !is null)
	  result |= contains(strTree.children[usedChar], str[1 .. $], usedChar != ch);
      return result;
    }
}

void main(string[] args)
{
  inputFile = stdin;
  auto n = next!int;
  auto m = next!int;
  auto inputStrings = next!string(n);
  auto queryStrings = next!string(m);
  auto root = new StrTreeNode;
  foreach(inputString; inputStrings)
    root.insert(inputString);
  foreach(queryString; queryStrings)
    writeln(root.contains(queryString)? "YES" : "NO");
}
ulong bitCnt(long x)
{
  ulong cnt = 0;
  while(x) {cnt += x & 1; x>>=1;}
  return cnt;
}
alias Arr(T) = Mat!(T, 1);
struct Mat(T, size_t dimension)
{
  T[] _baseArray;
  T[] _slice;
  size_t[dimension] _sizes; size_t dim(size_t i) {return _sizes[i];}
  size_t[dimension] _indexer;
  this(T[] baseArray, size_t[dimension] sizes)
  {
    _baseArray = baseArray;
    _sizes = sizes;
    _indexer[dimension - 1] = 1;
    static foreach_reverse(i; 0 .. dimension - 1)
      _indexer[i] = _indexer[i + 1] * _sizes[i + 1];
    auto requiredSize = _indexer[0] * _sizes[0];
    debug assert(_baseArray.length >= requiredSize);
    _slice = _baseArray[0 .. requiredSize];
  }
  this(size_t[dimension] sizes)
  {
    size_t reqSize = 1;
    static foreach(i; 0 .. dimension)
      reqSize *= sizes[i];
    this(new T[](reqSize), sizes);
  }
  ref auto opIndex()
  {
    pragma(inline, true);
    return _slice[];
  }
  ref auto opIndex(I...)(I i)
  {
    pragma(inline, true);
    debug assert(i.length <= dimension);
    size_t index = mixin(iota(0, i.length).map!(j => text("i[", j, "]*_indexer[", j, "]")).join("+"));
    static if (i.length == dimension)
      {
	return _slice[index];
      }
    else
      {
	enum sliceDimension = dimension - i.length;
	size_t[sliceDimension] remSizes = _sizes[i.length .. $];
	auto basePortion = _slice[index .. index + _indexer[i.length - 1]];
 	return Mat!(T, sliceDimension)(basePortion, remSizes);
      }
  }
  static if (dimension == 2)
    {
      auto identity()
      {
	debug assert(dim(0) == dim(1));
	auto n = dim(0);
	auto id = Mat!(T, 2)([n, n]);
	foreach(k; 0 .. n)
	  id[k, k] = T(1);
	return id;
      }
      bool canMultiply(Mat!(T, 2) b)
      {
	return this.dim(1) == b.dim(0);
      }
      auto opBinary(string op)(Mat!(T, 2) b)
	if (op == "*")
	  {
	    debug assert(canMultiply(b));
	    auto res = Mat!(T, 2)([this.dim(0), b.dim(1)]);
	    foreach(i; 0 .. res.dim(0))
	      foreach(k; 0 .. this.dim(1))
		foreach(j; 0 .. res.dim(1))
		  res[i, j] = res[i, j] + this[i, k] * b[k, j];
	    return res;
	  }
      auto opBinary(string op)(ulong exp)
	if (op == "^^")
	  {
	    return this.pow(identity, exp);
	  }
      mixin interiorBinPow;
    }
}

struct Mod(T, ulong mod)
{
  alias This = Mod!(T, mod);
  T _rep; T rep() {return _rep;}
  this(W)(W w)
  {
    _rep = ((cast(T) w)%mod + mod) % mod;
  }
  static auto plainConstruct(T t)
  {
    pragma(inline, true);
    debug assert(t >= 0 && t < mod);
    auto res = Mod!(T, mod).init;
    res._rep = t;
    return res;
  }
  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.plainConstruct(resrep);
      }
    else static if (op == "-")
      {
	T resrep = _rep - b._rep;
	if (resrep < 0) resrep += mod;
	return This.plainConstruct(resrep);
      }
    else static if (op == "*")
      {
	return This(_rep * b._rep);
      }
  }
}

mixin template interiorBinPow()
{
  alias ThisType = typeof(this);
  auto pow(ThisType res, ulong exp)
    {
      if (exp < 0) debug assert(0);
      auto pow = this;
      while(exp)
	{
	  if (exp & 1)
	    res = res * pow;
	  pow = pow * pow;
	  exp >>= 1;
	}
      return res;
    }
}

// INPUT
File inputFile;
DList!string _words;
void _wordsFill()
{
  while (_words.empty) _words.insertBack(inputFile.readln.split);
}
string popWord()
{
  _wordsFill;
  auto word = _words.front;
  _words.removeFront;
  return word;
}
string peekWord()
{
  _wordsFill;
  return _words.front;
}
T next(T)()
{
  return to!T(popWord);
}
T peek(T)()
{
  return to!T(peekWord);
}
auto next(T, S...)(S s)
{
  static if (S.length == 0)
    {
      return to!T(popWord);
    }
  else
    {
      auto res = new typeof(next!T(s[1 .. $]))[](cast(size_t)s[0]);
      foreach(ref elem; res)
        elem = next!T(s[1 .. $]);
      return res;
    }
}


Lunar New Year is approaching, and Bob is struggling with his homework – a number division problem.There are $$$n$$$ positive integers $$$a_1, a_2, \ldots, a_n$$$ on Bob's homework paper, where $$$n$$$ is always an even number. Bob is asked to divide those numbers into groups, where each group must contain at least $$$2$$$ numbers. Suppose the numbers are divided into $$$m$$$ groups, and the sum of the numbers in the $$$j$$$-th group is $$$s_j$$$. Bob's aim is to minimize the sum of the square of $$$s_j$$$, that is $$$$$$\sum_{j = 1}^{m} s_j^2.$$$$$$Bob is puzzled by this hard problem. Could you please help him solve it?

The first line contains an even integer $$$n$$$ ($$$2 \leq n \leq 3 \cdot 10^5$$$), denoting that there are $$$n$$$ integers on Bob's homework paper. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^4$$$), describing the numbers you need to deal with.

A single line containing one integer, denoting the minimum of the sum of the square of $$$s_j$$$, which is $$$$$$\sum_{i = j}^{m} s_j^2,$$$$$$ where $$$m$$$ is the number of groups.

NoteIn the first sample, one of the optimal solutions is to divide those $$$4$$$ numbers into $$$2$$$ groups $$$\{2, 8\}, \{5, 3\}$$$. Thus the answer is $$$(2 + 8)^2 + (5 + 3)^2 = 164$$$.In the second sample, one of the optimal solutions is to divide those $$$6$$$ numbers into $$$3$$$ groups $$$\{1, 2\}, \{1, 2\}, \{1, 2\}$$$. Thus the answer is $$$(1 + 2)^2 + (1 + 2)^2 + (1 + 2)^2 = 27$$$.

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

immutable long MOD = 998244353;

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

    A.sort();
    long ans = 0;

    foreach (i; 0..N/2) {
        ans += (A[i] + A[N-i-1]) * (A[i] + A[N-i-1]);
    }

    ans.writeln;
}

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

enum inf3 = 1_001_001_001;
enum inf6 = 1_001_001_001_001_001_001L;
enum mod = 1_000_000_007L;

void main() {
    int n;
    scan(n);
    auto a = readln.split.to!(long[]);

    a.sort();

    long ans;

    foreach (i ; 0 .. n / 2) {
        ans += a[i]^^2 + a[n - 1 - i]^^2 + 2L * a[i] * a[n - 1 - i];
    }

    writeln(ans);
}

void scan(T...)(ref T args) {
    import std.stdio : readln;
    import std.algorithm : splitter;
    import std.conv : to;
    import std.range.primitives;

    auto line = readln().splitter();
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}


It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days!When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day.The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is .You should write a program which will calculate average sleep times of Polycarp over all weeks.

The first line contains two integer numbers n and k (1 ≤ k ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).

Output average sleeping time over all weeks.  The answer is considered to be correct if its absolute or relative error does not exceed 10 - 6. In particular, it is enough to output real number with at least 6 digits after the decimal point.

NoteIn the third example there are n - k + 1 = 7 weeks, so the answer is sums of all weeks divided by 7.

module main;
import std.bigint,std.container,std.array,std.algorithm,std.conv,std.parallelism,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,std.bitmanip,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.stdio,std.variant,core.bitop,
	std.meta,core.stdc.stdio : freopen;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;
alias pair(X,Y)=Tuple!(X,"fi",Y,"se");alias long lint;const int mod=1000000007;
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	int sz(T)(T a) if(hasLength!T){return cast(int)a.length;}
	size_t lowb(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' ') if(isInputRange!X)
{foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a) if(isInputRange!X && isInputRange!(typeof(a.front)))
{
	foreach(ref const i;a)
	{
		foreach(ref const j;i)write(j,' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	return s==ptrs.length;
}
bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	readln;
	return s==ptrs.length;
}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int n,k;
loop:while(read(n,k))
	{
		auto a=arread!long;
		auto b=new int[a.length];
		foreach(i;0..n)
		{
			b[i]=min(k,i+1,n-k+1);
		}
		foreach(i;0..n)
		{
			b[n-i-1]=min(k,i+1,b[n-i-1],n-k+1);
		}
		debug writeln(b);
		debug
		{
			long ss=0;
			foreach(i;0..n-k+1)
			{
				ss+=a[i..i+k].sum;
			}
			writef("%.10f ",1.0L*ss/(n-k+1));
		}
		long s;
		foreach(i;0..n)s+=1L*a[i]*b[i];
		writefln("%.10f",1.0L*s/(n-k+1));

	}
}

module main;
import std.bigint,std.container,std.array,std.algorithm,std.conv,std.parallelism,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,std.bitmanip,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.stdio,std.variant,core.bitop,
	std.meta,core.stdc.stdio : freopen;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;
alias pair(X,Y)=Tuple!(X,"fi",Y,"se");alias long lint;const int mod=1000000007;
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	int sz(T)(T a) if(hasLength!T){return cast(int)a.length;}
	size_t lowb(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' ') if(isInputRange!X)
{foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a) if(isInputRange!X && isInputRange!(typeof(a.front)))
{
	foreach(ref const i;a)
	{
		foreach(ref const j;i)write(j,' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	return s==ptrs.length;
}
bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	readln;
	return s==ptrs.length;
}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int n,k;
loop:while(read(n,k))
	{
		auto a=arread!long;
		long s;
		foreach(i;0..k-1)
		{
			s+=(a[i])*(i+1);
		}
		for(int i=n-1;i>max(k-1,n-k);i--)
		{
			s+=(a[i])*(n-i);
		}
		for(int i=k-1;i<=max(n-k,k-1);i++)s+=(a[i])*(k);
		writefln("%.10f",1.0L*s/(n-k+1));
	}
}

module main;
import std.bigint,std.container,std.array,std.algorithm,std.conv,std.parallelism,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,std.bitmanip,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.stdio,std.variant,core.bitop,
	std.meta,core.stdc.stdio : freopen;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;
alias pair(X,Y)=Tuple!(X,"fi",Y,"se");alias long lint;const int mod=1000000007;
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	int sz(T)(T a) if(hasLength!T){return cast(int)a.length;}
	size_t lowb(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' ') if(isInputRange!X)
{foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a) if(isInputRange!X && isInputRange!(typeof(a.front)))
{
	foreach(ref const i;a)
	{
		foreach(ref const j;i)write(j,' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	return s==ptrs.length;
}
bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	readln;
	return s==ptrs.length;
}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int n,k;
loop:while(read(n,k))
	{
		auto a=arread!long;
		long s;
		foreach(i;0..k-1)
		{
			s+=(a[i])*(i+1);
		}
		for(int i=n-1;i>max(k-1,n-k);i--)
		{
			s+=(a[i])*(n-i);
		}
		for(int i=k-1;i<=n-k;i++)s+=(a[i])*(k);
		writefln("%.10f",1.0L*s/(n-k+1));
	}
}

module main;
import std.bigint,std.container,std.array,std.algorithm,std.conv,std.parallelism,
	std.functional,std.math,std.numeric,std.string,std.range,std.complex,std.bitmanip,
	std.typecons,std.regex,std.random,std.uni,std.traits,std.stdio,std.variant,core.bitop,
	std.meta,core.stdc.stdio : freopen;
alias RedBlackTree Rbt;alias redBlackTree rbt;alias BigInt big;
alias pair(X,Y)=Tuple!(X,"fi",Y,"se");alias long lint;const int mod=1000000007;
alias pair!(int,int) pii;alias pair!(long,long) pll;alias BoyerMooreFinder strfind;
alias make_pair mp;alias binary_search bins;alias gcd=std.numeric.gcd;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b){return a/gcd(a,b)*b;}
	pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_){return tuple!(X,"fi",Y,"se")(x_,y_);}
	big gcd(big a,big b){while(b){a%=b;swap(a,b);}return a;}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	int sz(T)(T a) if(hasLength!T){return cast(int)a.length;}
	size_t lowb(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(!(a[m]<g))r=m;
			else l=m;
		}
		return (!(a[l]<g))?l:r;
	}
	size_t upb(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		if(pos==a.length)return pos;
		else return a[pos]==g?pos+1:pos;
	}
	size_t binf(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		auto pos=lowb(a,g);
		return (g==a[pos])?pos:a.length;
	}
	bool binary_search(T,X)(T a,auto ref X g)
	 if(isRandomAccessRange!T && hasLength!T && is(typeof(g<a[0])==bool))
	{
		return binf(a,g)!=a.length;
	}
}
void putarr(X)(in X a,in char ch=' ') if(isInputRange!X)
{foreach(const ref i;a)write(i,ch);}
void putarr(X)(in X a) if(isInputRange!X && isInputRange!(typeof(a.front)))
{
	foreach(ref const i;a)
	{
		foreach(ref const j;i)write(j,' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	return s==ptrs.length;
}
bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
{
	size_t s=0;
	foreach(ref e;ptrs)
	{
		if(isSomeChar!(Unqual!(typeof(e))))s+=readf(" %c",&e);
		else s+=readf(" %s",&e);
	}
	readln;
	return s==ptrs.length;
}
nothrow auto inf(in char* name) {return freopen(name,"r",core.stdc.stdio.stdin);}
nothrow auto ouf(in char* name) {return freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int n,k;
loop:while(read(n,k))
	{
		auto a=arread!int;
		auto b=new int[a.length];
		foreach(i;0..n)
		{
			b[i]=min(k,i+1);
		}
		foreach(i;0..n)
		{
			b[n-i-1]=min(k,i+1,b[n-i-1]);
		}
		long s;
		foreach(i;0..n)s+=1L*a[i]*b[i];
		writefln("%.10f",1.0L*s/(n-k+1));
	}
}


A plane is flying at a constant height of $$$h$$$ meters above the ground surface. Let's consider that it is flying from the point $$$(-10^9, h)$$$ to the point $$$(10^9, h)$$$ parallel with $$$Ox$$$ axis.A glider is inside the plane, ready to start his flight at any moment (for the sake of simplicity let's consider that he may start only when the plane's coordinates are integers). After jumping from the plane, he will fly in the same direction as the plane, parallel to $$$Ox$$$ axis, covering a unit of distance every second. Naturally, he will also descend; thus his second coordinate will decrease by one unit every second.There are ascending air flows on certain segments, each such segment is characterized by two numbers $$$x_1$$$ and $$$x_2$$$ ($$$x_1 < x_2$$$) representing its endpoints. No two segments share any common points. When the glider is inside one of such segments, he doesn't descend, so his second coordinate stays the same each second. The glider still flies along $$$Ox$$$ axis, covering one unit of distance every second.     If the glider jumps out at $$$1$$$, he will stop at $$$10$$$. Otherwise, if he jumps out at $$$2$$$, he will stop at $$$12$$$. Determine the maximum distance along $$$Ox$$$ axis from the point where the glider's flight starts to the point where his flight ends if the glider can choose any integer coordinate to jump from the plane and start his flight. After touching the ground the glider stops altogether, so he cannot glide through an ascending airflow segment if his second coordinate is $$$0$$$.

The first line contains two integers $$$n$$$ and $$$h$$$ $$$(1 \le n \le 2\cdot10^{5}, 1 \le h \le 10^{9})$$$ — the number of ascending air flow segments and the altitude at which the plane is flying, respectively. Each of the next $$$n$$$ lines contains two integers $$$x_{i1}$$$ and $$$x_{i2}$$$ $$$(1 \le x_{i1} < x_{i2} \le 10^{9})$$$ — the endpoints of the $$$i$$$-th ascending air flow segment. No two segments intersect, and they are given in ascending order.

Print one integer — the maximum distance along $$$Ox$$$ axis that the glider can fly from the point where he jumps off the plane to the point where he lands if he can start his flight at any integer coordinate.

NoteIn the first example if the glider can jump out at $$$(2, 4)$$$, then the landing point is $$$(12, 0)$$$, so the distance is $$$12-2 = 10$$$.In the second example the glider can fly from $$$(16,10)$$$ to $$$(34,0)$$$, and the distance is $$$34-16=18$$$.In the third example the glider can fly from $$$(-100,1000000000)$$$ to $$$(1999999899,0)$$$, so the distance is $$$1999999899-(-100)=1999999999$$$.

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

void main() {
    auto s = readln.split;
    auto N = s[0].to!int;
    auto H = s[1].to!long;
    auto A = N.iota.map!(_ => readln.split.map!(to!long).array).array;
    long ans = 0;
    long tmp = 0;
    long h = 0;

    for (int i = 0, j = 0; i < N; ++i) {
        if (j <= i) {
            tmp = A[i][1] - A[i][0];
            h = H;
            j = i;
        } else {
            tmp -= A[i][0] - A[i - 1][0];
            h += A[i][0] - A[i - 1][1];
        }
        while (j + 1 < N && h - (A[j + 1][0] - A[j][1]) > 0) {
            tmp += A[j + 1][1] - A[j][1];
            h -= A[j + 1][0] - A[j][1];
            ++j;
        }
        ans = max(ans, tmp + h);
    }

    ans.writeln;
}

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

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

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

    Tuple!(int, int)[] sg;
    foreach (_; 0 .. n) {
        int x1, x2;
        readf("%s %s", &x1, &x2);
        readln;

        sg ~= tuple(x1, x2);
    }

    debug { sg.writeln; }

    int lst = 0;
    int covered = 0;
    int cur = sg[0][1] - sg[0][0];
    int ans = cur;
    foreach (i; 1 .. n) {
        cur += sg[i][1] - sg[i][0];
        covered += sg[i][0] - sg[i-1][1];
        while (covered > h-1) {
            cur -= sg[lst][1] - sg[lst][0];
            covered -= sg[lst+1][0] - sg[lst][1];
            ++lst;
        }
        ans = max(ans, cur);
    }

    ans += h;

    ans.writeln;
}

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

  int n, h; rd(n, h);
  auto l=new int[](n), r=new int[](n);
  foreach(i; 0..n) rd(l[i], r[i]);

  int mx=0, len=0;
  for(int i=0, j=0, height=h; i<n; i++){
    while(j<n && height>0){
      mx=max(mx, len+(r[j]-l[j])+height);
      if((++j)<n){
        len+=l[j]-l[j-1];
        height-=l[j]-r[j-1];
      }
    }
    if(i+1<n){
      len-=l[i+1]-l[i];
      height+=l[i+1]-r[i];
    }
  }
  writeln(mx);

}

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

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

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

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

    Tuple!(int, int)[] sg;
    foreach (_; 0 .. n) {
        int x1, x2;
        readf("%s %s", &x1, &x2);
        readln;

        sg ~= tuple(x1, x2);
    }

    debug { sg.writeln; }

    int lst = 0;
    int covered = 0;
    int cur = sg[0][1] - sg[0][0];
    int ans = cur;
    foreach (i; 1 .. n) {
        cur += sg[i][1] - sg[i][0];
        covered += sg[i][0] - sg[i-1][1];
        while (covered > h) {
            cur -= sg[lst][1] - sg[lst][0];
            covered -= sg[lst+1][0] - sg[lst][1];
            ++lst;
        }
        ans = max(ans, cur);
    }

    ans += h;

    ans.writeln;
}


While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of n + 2 characters. She has written all the possible n three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password out. Each three-letter substring was written the number of times it occurred in the password. Thus, Tanya ended up with n pieces of paper.Then Tanya realized that dad will be upset to learn about her game and decided to restore the password or at least any string corresponding to the final set of three-letter strings. You have to help her in this difficult task. We know that dad's password consisted of lowercase and uppercase letters of the Latin alphabet and digits. Uppercase and lowercase letters of the Latin alphabet are considered distinct.

The first line contains integer n (1 ≤ n ≤ 2·105), the number of three-letter substrings Tanya got.  Next n lines contain three letters each, forming the substring of dad's password. Each character in the input is a lowercase or uppercase Latin letter or a digit.

If Tanya made a mistake somewhere during the game and the strings that correspond to the given set of substrings don't exist, print "NO".  If it is possible to restore the string that corresponds to given set of substrings, print "YES", and then print any suitable password option.

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

//	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, in T f) { if (t > f) t = f; }
void chmax(T)(ref T t, in T f) { if (t < f) t = f; }

//	Pair
struct Pair(S, T) {
	S x; T y;
	int opCmp(    const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; }
	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)(inout(S) x, inout(T) y) { return Pair!(S, T)(x, y); }

//	Array
int binarySearch(T)(in T[] as, in 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)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <  val); }); }
int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <= val); }); }
T[] unique(T)(in T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; }

int root(int[] uf, int u) {
	return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool conn(int[] uf, int u, int v) {
	u = uf.root(u);
	v = uf.root(v);
	if (u == v) return false;
	if (uf[u] > uf[v]) swap(u, v);
	uf[u] += uf[v];
	uf[v] = u;
	return true;
}

immutable V = 62 * 62;

int tr(char c) {
	return ('0' <= c && c <= '9') ? (0 + (c - '0')) : ('A' <= c && c <= 'Z') ? (10 + (c - 'A')) : (36 + (c - 'a'));
}
int tr(string s) {
	return tr(s[0]) * 62 + tr(s[1]);
}
char rt(int x) {
	return cast(char)((0 <= x && x < 10) ? ('0' + (x - 0)) : (10 <= x && x < 36) ? ('A' + (x - 10)) : ('a' + (x - 36)));
}

int E;
string[] S;

int[][] adj;
int[] path;

void dfs(int u) {
	foreach (v; 0 .. V) {
		if (adj[u][v]) {
			--adj[u][v];
			dfs(v);
		}
	}
	path ~= u;
}

bool solve() {
	adj = new int[][](V, V);
	foreach (s; S) {
		const u = tr(s[0 .. 2]);
		const v = tr(s[1 .. 3]);
		++adj[u][v];
	}

	int[] deg = new int[V];
	foreach (u; 0 .. V) foreach (v; 0 .. V) {
		deg[u] += adj[u][v];
		deg[v] -= adj[u][v];
	}
	int sum;
	foreach (u; 0 .. V) {
		if (deg[u] > 0) {
			sum += deg[u];
		}
	}
	if (sum > 1) {
		return false;
	}

	int[] uf = new int[V];
	uf[] = -1;
	foreach (u; 0 .. V) foreach (v; 0 .. V) {
		if (adj[u][v]) {
			uf.conn(u, v);
		}
	}
	int r = -1;
	foreach (u; 0 .. V) foreach (v; 0 .. V) {
		if (adj[u][v]) {
			if (r == -1) {
				r = uf.root(u);
			}
			if (r != uf.root(u)) {
				return false;
			}
		}
	}

	assert(r != -1);
	int src = r;
	foreach (u; 0 .. V) {
		if (deg[u] > 0) {
			src = u;
			break;
		}
	}
	path = new int[0];
	dfs(src);
	path.reverse;
	return true;
}

void main(string[] args) {
	try {
	for (; ; ) {
		E = readInt;
		S = new string[E];
		foreach (e; 0 .. E) {
			S[e] = readToken;
		}

		const res = solve;
		if (res) {
			writeln("YES");
debug{
writeln("path = ",path);
}
			string ans;
			ans ~= rt(path[0] / 62);
			foreach (u; path) {
				ans ~= rt(u % 62);
			}
			writeln(ans);
		} else {
			writeln("NO");
		}

	}
	} catch (EOFException) {}
}


The student council is preparing for the relay race at the sports festival.The council consists of $$$n$$$ members. They will run one after the other in the race, the speed of member $$$i$$$ is $$$s_i$$$. The discrepancy $$$d_i$$$ of the $$$i$$$-th stage is the difference between the maximum and the minimum running speed among the first $$$i$$$ members who ran. Formally, if $$$a_i$$$ denotes the speed of the $$$i$$$-th member who participated in the race, then $$$d_i = \max(a_1, a_2, \dots, a_i) - \min(a_1, a_2, \dots, a_i)$$$.You want to minimize the sum of the discrepancies $$$d_1 + d_2 + \dots + d_n$$$. To do this, you are allowed to change the order in which the members run. What is the minimum possible sum that can be achieved?

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2000$$$)  — the number of members of the student council. The second line contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$1 \le s_i \le 10^9$$$)  – the running speeds of the members.

Print a single integer  — the minimum possible value of $$$d_1 + d_2 + \dots + d_n$$$ after choosing the order of the members.

NoteIn the first test case, we may choose to make the third member run first, followed by the first member, and finally the second. Thus $$$a_1 = 2$$$, $$$a_2 = 3$$$, and $$$a_3 = 1$$$. We have:  $$$d_1 = \max(2) - \min(2) = 2 - 2 = 0$$$.  $$$d_2 = \max(2, 3) - \min(2, 3) = 3 - 2 = 1$$$.  $$$d_3 = \max(2, 3, 1) - \min(2, 3, 1) = 3 - 1 = 2$$$. The resulting sum is $$$d_1 + d_2 + d_3 = 0 + 1 + 2 = 3$$$. It can be shown that it is impossible to achieve a smaller value.In the second test case, the only possible rearrangement gives $$$d_1 = 0$$$, so the minimum possible result is $$$0$$$.

import std.stdio;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;
import core.bitop;
import core.stdc.stdio : scanf;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }
void chmin(T)(ref T a, in T b) { a = min(a, b); }
void chmax(T)(ref T a, in T b) { a = max(a, b); }

void main() {
    int N = read!int;
    auto S = readarray!long;
    S.sort;

    enum long INF = 1L<<57;

    auto cache = new long[][](N, N+1);
    foreach (ref L; cache) L[] = -1;
    long f(int l, int r) {
        if (l == 0 && r == N) return 0L;
        if (cache[l][r] >= 0) return cache[l][r];
        long ans = INF;
        if (l > 0) {
            ans.chmin(f(l-1, r) + (S[r-1] - S[l-1]));
        }
        if (r < N) {
            ans.chmin(f(l, r+1) + S[r] - S[l]);
        }
        return cache[l][r] = ans;
    }

    long ans = INF;
    foreach (i; 0 .. N) {
        ans.chmin(f(i, i+1));
    }
    writeln(ans);
}


Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it.In the beginning, uncle Bogdan wrote on a board a positive integer $$$x$$$ consisting of $$$n$$$ digits. After that, he wiped out $$$x$$$ and wrote integer $$$k$$$ instead, which was the concatenation of binary representations of digits $$$x$$$ consists of (without leading zeroes). For example, let $$$x = 729$$$, then $$$k = 111101001$$$ (since $$$7 = 111$$$, $$$2 = 10$$$, $$$9 = 1001$$$).After some time, uncle Bogdan understood that he doesn't know what to do with $$$k$$$ and asked Denis to help. Denis decided to wipe last $$$n$$$ digits of $$$k$$$ and named the new number as $$$r$$$.As a result, Denis proposed to find such integer $$$x$$$ of length $$$n$$$ that $$$r$$$ (as number) is maximum possible. If there are multiple valid $$$x$$$ then Denis is interested in the minimum one.All crew members, including captain Flint himself, easily solved the task. All, except cabin boy Kostya, who was too drunk to think straight. But what about you?Note: in this task, we compare integers ($$$x$$$ or $$$k$$$) as numbers (despite what representations they are written in), so $$$729 < 1999$$$ or $$$111 < 1000$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain test cases — one per test case. The one and only line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the integer $$$x$$$ you need to find. It's guaranteed that the sum of $$$n$$$ from all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print the minimum integer $$$x$$$ of length $$$n$$$ such that obtained by Denis number $$$r$$$ is maximum possible.

NoteIn the second test case (with $$$n = 3$$$), if uncle Bogdan had $$$x = 998$$$ then $$$k = 100110011000$$$. Denis (by wiping last $$$n = 3$$$ digits) will obtain $$$r = 100110011$$$.It can be proved that the $$$100110011$$$ is the maximum possible $$$r$$$ Denis can obtain and $$$998$$$ is the minimum $$$x$$$ to obtain it.

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 v = '9'.repeat (n).array;
		v[0..(n + 3) / 4] = '8';
		writeln (v.retro);
	}
}

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

DList!string _words;
void read(T)(out T t)
{
  import std.stdio: readln;
  while(_words.empty)
    {
      import std.array: split;
      foreach(word; readln.split)
        {
          _words.insertBack(word);
        }
    }
  import std.conv: to;
  string word = _words.front;
  _words.removeFront;
  t = to!T(word);
}

void main()
{
  int t;
  read(t);
  while(t--)
    {
      int n;
      read(n);
      int eights = (n + ((-n)%4+4)%4) / 4;
      foreach(i; 0 .. n - eights)
        write("9");
      foreach(i; 0 .. eights)
        write("8");
      writeln;
    }
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new string[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto m = (n+3) / 4;
		foreach (i; 0..n-m)
			ans[ti] ~= "9";
		foreach (i; 0..m)
			ans[ti] ~= "8";
	}

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


Nikita and Sasha play a computer game where you have to breed some magical creatures. Initially, they have k creatures numbered from 1 to k. Creatures have n different characteristics.Sasha has a spell that allows to create a new creature from two given creatures. Each of its characteristics will be equal to the maximum of the corresponding characteristics of used creatures. Nikita has a similar spell, but in his spell, each characteristic of the new creature is equal to the minimum of the corresponding characteristics of used creatures. A new creature gets the smallest unused number.They use their spells and are interested in some characteristics of their new creatures. Help them find out these characteristics.

The first line contains integers n, k and q (1 ≤ n ≤ 105, 1 ≤ k ≤ 12, 1 ≤ q ≤ 105) — number of characteristics, creatures and queries. Next k lines describe original creatures. The line i contains n numbers ai1, ai2, ..., ain (1 ≤ aij ≤ 109) — characteristics of the i-th creature. Each of the next q lines contains a query. The i-th of these lines contains numbers ti, xi and yi (1 ≤ ti ≤ 3). They denote a query:    ti = 1 means that Sasha used his spell to the creatures xi and yi.  ti = 2 means that Nikita used his spell to the creatures xi and yi.  ti = 3 means that they want to know the yi-th characteristic of the xi-th creature. In this case 1 ≤ yi ≤ n.  It's guaranteed that all creatures' numbers are valid, that means that they are created before any of the queries involving them.

For each query with ti = 3 output the corresponding characteristic.

NoteIn the first sample, Sasha makes a creature with number 3 and characteristics (2, 2). Nikita makes a creature with number 4 and characteristics (1, 1). After that they find out the first characteristic for the creature 3 and the second characteristic for the creature 4.

import core.bitop;
import core.checkedint;
import core.stdc.stdio;
import core.stdc.stdlib: alloca, malloc, calloc, realloc, _Exit;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
//import std.stdio;
import std.string;
import std.typecons;

__gshared:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

bool read(T...)(ref T vars) if (vars.length > 0) {
    return readf(' ' ~ replicate("%s ", vars.length), getAddrTuple(vars).expand) == vars.length;
}

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

void memSet(T, size_t n)(ref T[n] a, ubyte value) {
    memset(a.ptr, value, a.sizeof);
}

void memSet(T)(T[ ] a, ubyte value) {
    memset(a.ptr, value, a.length * T.sizeof);
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

int k;
Tuple!(int, int, bool)[100_000] parents;//[creature] => (fst, snd, isMax)
int[12][100_000] initial;//[geneId][creature] => value
int[int][100_000] born;//[geneId][creature] => value

int getGene(int geneId, int creature) {
    if (creature < k)
        return initial[geneId][creature];
    if (const p = creature in born[geneId])
        return *p;
    int a, b;
    bool isMax;
    AliasSeq!(a, b, isMax) = parents[creature];
    a = getGene(geneId, a);
    b = getGene(geneId, b);
    a = isMax ? max(a, b) : min(a, b);
    born[geneId][creature] = a;
    return a;
}

void main() {
    int n, q;
    while (~scanf("%d%d%d", &n, &k, &q)) {
        version (LocalProject)
            foreach (ref h; born[0 .. n])
                h.clear();
        foreach (i; 0 .. k)
            foreach (j; 0 .. n)
                scanf("%d", &initial[j][i]);
        int count = k;
        while (q--) {
            getchar();
            const action = cast(char)getchar();
            int x, y;
            scanf("%d%d", &x, &y);
            x--;
            y--;
            final switch (action) {
                case '1': parents[count++] = tuple(x, y, true); break;
                case '2': parents[count++] = tuple(x, y, false); break;
                case '3': printf("%d\n", getGene(y, x)); break;
            }
        }
    }

    fflush(stdout);
    _Exit(0);
}


You can perfectly predict the price of a certain stock for the next N days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you don't own any. At the end of the N days you would like to again own zero shares, but want to have as much money as possible.

Input begins with an integer N (2 ≤ N ≤ 3·105), the number of days. Following this is a line with exactly N integers p1, p2, ..., pN (1 ≤ pi ≤ 106). The price of one share of stock on the i-th day is given by pi.

Print the maximum amount of money you can end up with at the end of N days.

NoteIn the first example, buy a share at 5, buy another at 4, sell one at 9 and another at 12. Then buy at 2 and sell at 10. The total profit is  - 5 - 4 + 9 + 12 - 2 + 10 = 20.

/+ dub.sdl:
    name "D"
    dependency "dunkelheit" version=">=0.9.0"
+/

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

// import dkh.container.pairingheap;

int main() {
    Scanner sc = new Scanner(stdin);
    scope(exit) assert(!sc.hasNext);

    int n;
    long[] p;
    sc.read(n, p);

    PairingHeap!(long[2], "a>b") q;

    long ans = 0;
    foreach (d; p) {
        if (q.empty || q.front[0] >= d) {
            q.insert([d, 0]);
        } else {
            auto x = q.front; q.removeFront();
            ans += d - x[0];
            q.insert([d, 1]);
            if (x[1]) {
                q.insert([x[0], 0]);
            }
        }
    }
    writeln(ans);
    return 0;
}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/container/stackpayload.d */
// module dkh.container.stackpayload;

struct StackPayload(T, size_t MINCAP = 4) if (MINCAP >= 1) {
    import core.exception : RangeError;

    private T* _data;
    private uint len, cap;

    @property bool empty() const { return len == 0; }
    @property size_t length() const { return len; }
    alias opDollar = length;

    inout(T)[] data() inout { return (_data) ? _data[0..len] : null; }

    ref inout(T) opIndex(size_t i) inout {
        version(assert) if (len <= i) throw new RangeError();
        return _data[i];
    }
    ref inout(T) front() inout { return this[0]; }
    ref inout(T) back() inout { return this[$-1]; }

    void reserve(size_t newCap) {
        import core.memory : GC;
        import core.stdc.string : memcpy;
        import std.conv : to;
        if (newCap <= cap) return;
        void* newData = GC.malloc(newCap * T.sizeof);
        cap = newCap.to!uint;
        if (len) memcpy(newData, _data, len * T.sizeof);
        _data = cast(T*)(newData);
    }
    void free() {
        import core.memory : GC;
        GC.free(_data);
    }

    void clear() {
        len = 0;
    }

    void insertBack(T item) {
        import std.algorithm : max;
        if (len == cap) reserve(max(cap * 2, MINCAP));
        _data[len++] = item;
    }
    alias opOpAssign(string op : "~") = insertBack;
    void removeBack() {
        assert(!empty, "StackPayload.removeBack: Stack is empty");
        len--;
    }
}

/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/scanner.d */
// module dkh.scanner;

// import dkh.container.stackpayload;

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

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

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else static if (isStaticArray!T) {
                foreach (i; 0..T.length) {
                    bool f = succW();
                    assert(f);
                    x[i] = line.parse!E;
                }
            } else {
                StackPayload!E buf;
                while (succW()) {
                    buf ~= line.parse!E;
                }
                x = buf.data;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }

    int unsafeRead(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
    void read(Args...)(auto ref Args args) {
        import std.exception;
        static if (args.length != 0) {
            enforce(readSingle(args[0]));
            read(args[1..$]);
        }
    }
    bool hasNext() {
        return succ();
    }
}

/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/foundation.d */

// module dkh.foundation;

static if (__VERSION__ <= 2070) {
    /*
    Copied by https://github.com/dlang/phobos/blob/master/std/algorithm/iteration.d
    Copyright: Andrei Alexandrescu 2008-.
    License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
    */
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
/* IMPORT /home/yosupo/Program/dunkelheit/source/dkh/container/pairingheap.d */
// module dkh.container.pairingheap;

private NP meldPairingHeapNode(alias less, NP)(NP x, NP y) {
    import std.algorithm : swap;
    if (!x) return y;
    if (!y) return x;
    if (less(x._item, y._item)) swap(x, y);
    y.next = x.head;
    x.head = y;
    return x;
}

struct PairingHeap(T, alias less = "a < b") {
    import std.functional : binaryFun;
    private alias _less = binaryFun!less;

    private alias NP = Node*;
    private static struct Node {
        T _item;
        NP head, next;
        this(T item) {
            _item = item;
        }
    }

    private struct Payload {
        import std.algorithm : swap;
        private NP node;
        private uint len;

        void insert(T item) {
            len++;
            node = meldPairingHeapNode!_less(node, new Node(item));
        }
        inout(T) front() inout { return node._item; }
        void removeFront() {
            len--;

            NP s = node.head;
            NP t;

            while (s) {

                NP first, second;
                first = s; s = s.next; first.next = null;
                if (s) {
                    second = s; s = s.next; second.next = null;
                }

                auto v = meldPairingHeapNode!_less(first, second);
                v.next = t;
                t = v;
            }
            node = null;

            while (t) {
                NP first = t; t = t.next; first.next = null;
                node = meldPairingHeapNode!_less(first, node);
            }
        }
        void meld(Payload* r) {
            len += r.len; r.len = 0;
            node = meldPairingHeapNode!_less(node, r.node);
            r.node = null;
        }
    }
    private Payload* _p;

    @property bool empty() const { return !_p || _p.len == 0; }
    @property size_t length() const { return (!_p) ? 0 : _p.len; }

    void insert(T item) {
        if (!_p) _p = new Payload();
        _p.insert(item);
    }
    inout(T) front() inout {
        assert(!empty, "PairingHeap.front: heap is empty");
        return _p.front;
    }
    void removeFront() {
        assert(!empty, "PairingHeap.removeFront: heap is empty");
        _p.removeFront;
    }

    void meld(PairingHeap r) { _p.meld(r._p); }
}

/*
This source code generated by dunkelheit and include dunkelheit's source code.
dunkelheit's Copyright: Copyright (c) 2016- Kohei Morita. (https://github.com/yosupo06/dunkelheit)
dunkelheit's License: MIT License(https://github.com/yosupo06/dunkelheit/blob/master/LICENSE.txt)
*/

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

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

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

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

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

      long ans;
      auto set = new RedBlackTree!(long, "a < b", true);
      foreach (i; 0 .. N) {
        // +1, -P[i]
        set.insert(P[i]);
        // -1, +P[i]
        ans += P[i];
        set.insert(P[i]);
        ans -= set.front;
        set.removeFront;
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


You are given two integers $$$n$$$ and $$$m$$$. Calculate the number of pairs of arrays $$$(a, b)$$$ such that:  the length of both arrays is equal to $$$m$$$;  each element of each array is an integer between $$$1$$$ and $$$n$$$ (inclusive);  $$$a_i \le b_i$$$ for any index $$$i$$$ from $$$1$$$ to $$$m$$$;  array $$$a$$$ is sorted in non-descending order;  array $$$b$$$ is sorted in non-ascending order. As the result can be very large, you should print it modulo $$$10^9+7$$$.

The only line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 1000$$$, $$$1 \le m \le 10$$$).

Print one integer – the number of arrays $$$a$$$ and $$$b$$$ satisfying the conditions described above modulo $$$10^9+7$$$.

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

enum modulo = 1_000_000_007;
int add (int x, int y) {
  x += y;
  if (x >= modulo) x -= modulo;
  return x;
}

int test (const int n, const int m) {
  auto a = new int[n];
  a[0] = 1;
  foreach (k; 1 .. m + 1) {
    auto s = new int[n];
    s[0] = a[0];
    foreach (j; 1 .. n) {
      s[j] = add (s[j-1], a[j]);
    }
    a = s;
  }
  int r;
  foreach (j; 0 .. n) r = add (r, a[j]);
  return r;
}

void main() {
  int n, m;
  readf (" %d %d", &n, &m);
  writeln (test (n, 2 * m));
  //a[i] <= b[i]
  //a[i] <= a[i+1]
  //b[i] >= b[i+1]
}


You're given two arrays $$$a[1 \dots n]$$$ and $$$b[1 \dots n]$$$, both of the same length $$$n$$$.In order to perform a push operation, you have to choose three integers $$$l, r, k$$$ satisfying $$$1 \le l \le r \le n$$$ and $$$k > 0$$$. Then, you will add $$$k$$$ to elements $$$a_l, a_{l+1}, \ldots, a_r$$$.For example, if $$$a = [3, 7, 1, 4, 1, 2]$$$ and you choose $$$(l = 3, r = 5, k = 2)$$$, the array $$$a$$$ will become $$$[3, 7, \underline{3, 6, 3}, 2]$$$.You can do this operation at most once. Can you make array $$$a$$$ equal to array $$$b$$$?(We consider that $$$a = b$$$ if and only if, for every $$$1 \le i \le n$$$, $$$a_i = b_i$$$)

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 20$$$) — the number of test cases in the input. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100\ 000$$$) — the number of elements in each array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$). The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, output one line containing "YES" if it's possible to make arrays $$$a$$$ and $$$b$$$ equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower).

NoteThe first test case is described in the statement: we can perform a push operation with parameters $$$(l=3, r=5, k=2)$$$ to make $$$a$$$ equal to $$$b$$$.In the second test case, we would need at least two operations to make $$$a$$$ equal to $$$b$$$.In the third test case, arrays $$$a$$$ and $$$b$$$ are already equal.In the fourth test case, it's impossible to make $$$a$$$ equal to $$$b$$$, because the integer $$$k$$$ has to be positive.

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

void main() {
    auto T = readln.chomp.to!int;
    while (T--) {
        auto N = readln.chomp.to!int;
        auto A = readln.split.map!(to!int).array;
        auto B = readln.split.map!(to!int).array;
        B[] -= A[];
        B = B.uniq.array;
        if (B.map!(b => b < 0).any) {
            writeln("NO");
        } else if (B.length == 1) {
            writeln("YES");
        } else if (B.length == 2 && (B.front == 0 || B.back == 0)) {
            writeln("YES");
        } else if (B.length == 3 && (B.front == 0 && B.back == 0)) {
            writeln("YES");
        } else {
            writeln("NO");
        }
    }
}

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 rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;

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

void solve(){
	int t = rint;
	foreach(_; 0 .. t){
		int n = rint;
		long[] as = rlong(n);
		long[] bs = rlong(n);

		long[] us;
		foreach(i; 0 .. n) us ~= bs[i] - as[i];
		log("us:", us);

		int s = 0; // 0=まだない 1=今その途中 2=終わった -1=だめ
		long xu;
		foreach(u; us){
			if(u < 0) s = -1;
			else if(u == 0){
				if(s == 1) s = 2;
			}
			else{
				if(s == 0){
					s = 1;
					xu = u;
				}
				else if(s == 1){
					if(u != xu) s = -1;
				}
				else if(s == 2){
					s = -1;
				}
			}
		}

		if(s == -1) "NO".writeln;
		else "YES".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 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; }

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (i; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		auto b = RDA;
		auto c = new long[](n);
		foreach (j; 0..n)
		{
			c[j] = b[j] - a[j];
		}
		int l, r=1;
		foreach (j; 0..n)
		{
			if (c[j] != 0)
			{
				l = j;
				break;
			}
		}
		foreach_reverse (j; 0..n)
		{
			if (c[j] != 0)
			{
				r = j+1;
				break;
			}
		}
		debug writeln(l, ":", r);
		bool ok = c[l] >= 0;
		foreach (j; l+1..r)
		{
			if (c[j] < 0) ok = false;
			if (c[j] != c[j-1])
				ok = false;
		}
		ans[i] = 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.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; }

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (i; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		auto b = RDA;
		auto c = new long[](n);
		foreach (j; 0..n)
		{
			c[j] = b[j] - a[j];
		}
		int l, r;
		foreach (j; 0..n)
		{
			if (c[j] != 0)
			{
				l = j;
				break;
			}
		}
		foreach_reverse (j; 0..n)
		{
			if (c[j] != 0)
			{
				r = j;
				break;
			}
		}
		debug writeln(l, ":", r);
		bool ok = c[l] >= 0;
		foreach (j; l+1..r)
		{
			if (c[j] < 0) ok = false;
			if (c[j] != c[j-1])
				ok = false;
		}
		ans[i] = 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.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; }

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (i; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		auto b = RDA;
		auto c = new long[](n);
		foreach (j; 0..n)
		{
			c[j] = b[j] - a[j];
		}
		bool ok = true;
		long last;
		foreach (j; 0..n)
		{
			if (c[j] == 0) continue;
			else if (c[j] < 0)
				ok = false;

			if (last == 0)
				last = c[j];
			else if (c[j] != last)
				ok = false;
		}
		ans[i] = 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.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; }

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (i; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;
		auto b = RDA;
		auto c = new long[](n);
		foreach (j; 0..n)
		{
			c[j] = b[j] - a[j];
		}
		int l, r=1;
		foreach (j; 0..n)
		{
			if (c[j] != 0)
			{
				l = j;
				break;
			}
		}
		foreach_reverse (j; 0..n)
		{
			if (c[j] != 0)
			{
				r = j;
				break;
			}
		}
		debug writeln(l, ":", r);
		bool ok = c[l] >= 0;
		foreach (j; l+1..r)
		{
			if (c[j] < 0) ok = false;
			if (c[j] != c[j-1])
				ok = false;
		}
		ans[i] = ok;
	}

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


You are given a directed graph with $$$n$$$ vertices and $$$m$$$ directed edges without self-loops or multiple edges.Let's denote the $$$k$$$-coloring of a digraph as following: you color each edge in one of $$$k$$$ colors. The $$$k$$$-coloring is good if and only if there no cycle formed by edges of same color.Find a good $$$k$$$-coloring of given digraph with minimum possible $$$k$$$.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 5000$$$, $$$1 \le m \le 5000$$$) — the number of vertices and edges in the digraph, respectively. Next $$$m$$$ lines contain description of edges — one per line. Each edge is a pair of integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$) — there is directed edge from $$$u$$$ to $$$v$$$ in the graph. It is guaranteed that each ordered pair $$$(u, v)$$$ appears in the list of edges at most once.

In the first line print single integer $$$k$$$ — the number of used colors in a good $$$k$$$-coloring of given graph. In the second line print $$$m$$$ integers $$$c_1, c_2, \dots, c_m$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ is a color of the $$$i$$$-th edge (in order as they are given in the input). If there are multiple answers print any of them (you still have to minimize $$$k$$$).

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 rtype(T)(){ return read.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtype!real;

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

void solve(){
	int n = rint, m = rint;
	Node[] nodes;
	foreach(i; 0 .. n) nodes ~= new Node(i);

	Edge[] edges;
	foreach(j; 0 .. m){
		int u = rint - 1, v = rint - 1;
		edges ~= new Edge(nodes[u], nodes[v]);
		nodes[u].kids ~= nodes[v];
		nodes[v].parentcnt += 1;
	}

	foreach(nd; nodes){
		if(nd.parentcnt == 0) nd.go;
	}

	bool f;
	foreach(nd; nodes) if(nd.parentcnt > 0) f = 1;

	if(f){
		"2".writeln;
		m.iota.map!(i => (edges[i].node1.id < edges[i].node2.id? "1": "2")).array.join(" ").writeln;
	}
	else{
		"1".writeln;
		m.iota.map!(i => "1").array.join(" ").writeln;
	}

}
class Node{
	int id;
	int parentcnt;
	Node[] kids;
	this(int id){
		this.id = id;
	}
	void go(){
		foreach(nd; kids){
			nd.parentcnt -= 1;
			if(nd.parentcnt == 0) nd.go;
		}
	}
}
class Edge{
	Node node1, node2;
	int color;
	this(Node nd1, Node nd2){
		node1 = nd1, node2 = nd2;
	}
}

/*
If the graph has no loop, the answer is 1.

Otherwise, the answer is 2:
color 1 for i < j,
color 2 for i > j.
*/


Roy and Biv have a set of n points on the infinite number line.Each point has one of 3 colors: red, green, or blue.Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it connects.They want to do this in such a way that they will both see that all the points are connected (either directly or indirectly).However, there is a catch: Roy cannot see the color red and Biv cannot see the color blue.Therefore, they have to choose the edges in such a way that if all the red points are removed, the remaining blue and green points are connected (and similarly, if all the blue points are removed, the remaining red and green points are connected).Help them compute the minimum cost way to choose edges to satisfy the above constraints.

The first line will contain an integer n (1 ≤ n ≤ 300 000), the number of points. The next n lines will contain two tokens pi and ci (pi is an integer, 1 ≤ pi ≤ 109, ci is a uppercase English letter 'R', 'G' or 'B'), denoting the position of the i-th point and the color of the i-th point. 'R' means red, 'G' denotes green, and 'B' means blue. The positions will be in strictly increasing order.

Print a single integer, the minimum cost way to solve the problem.

NoteIn the first sample, it is optimal to draw edges between the points (1,2), (1,4), (3,4). These have costs 4, 14, 5, respectively.

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

enum INF = 10L^^18;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto P = new long[N];
      auto C = new char[N];
      foreach (u; 0 .. N) {
        P[u] = readLong();
        C[u] = readToken()[0];
      }

      int[] rs, gs, bs;
      foreach (u; 0 .. N) {
        switch (C[u]) {
          case 'R': rs ~= u; break;
          case 'G': gs ~= u; break;
          case 'B': bs ~= u; break;
          default: assert(false);
        }
      }

      long ans;
      if (rs.empty || bs.empty) {
        ans = P[N - 1] - P[0];
      } else if (gs.empty) {
        ans = (P[rs[$ - 1]] - P[rs[0]]) + (P[bs[$ - 1]] - P[bs[0]]);
        /*
        if (!rs.empty && !bs.empty) {
          long mn = INF;
          foreach (u; 0 .. N - 1) {
            if (C[u] != C[u + 1]) {
              chmin(mn, P[u + 1] - P[u]);
            }
          }
          ans += mn;
        }
        */
      } else {
        ans = P[gs[$ - 1]] - P[gs[0]];
        foreach (c; ['R', 'B']) {
          foreach (u; 0 .. gs[0]) {
            if (C[u] == c) {
              ans += P[gs[0]] - P[u];
              break;
            }
          }
          foreach_reverse (u; gs[$ - 1] + 1 .. N) {
            if (C[u] == c) {
              ans += P[u] - P[gs[$ - 1]];
              break;
            }
          }
        }
        foreach (j; 1 .. gs.length) {
          const a = gs[j - 1];
          const b = gs[j];
          long[] mxs;
          foreach (c; ['R', 'B']) {
            int[] us;
            us ~= a;
            foreach (u; a + 1 .. b) {
              if (C[u] == c) {
                us ~= u;
              }
            }
            us ~= b;
            long mx;
            foreach (k; 1 .. us.length) {
              chmax(mx, P[us[k]] - P[us[k - 1]]);
            }
            mxs ~= mx;
          }
          ans += min((P[b] - P[a]), ((P[b] - P[a]) - mxs[0]) + ((P[b] - P[a]) - mxs[1]));
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

enum INF = 10L^^18;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto P = new long[N];
      auto C = new char[N];
      foreach (u; 0 .. N) {
        P[u] = readLong();
        C[u] = readToken()[0];
      }

      int[] rs, gs, bs;
      foreach (u; 0 .. N) {
        switch (C[u]) {
          case 'R': rs ~= u; break;
          case 'G': gs ~= u; break;
          case 'B': bs ~= u; break;
          default: assert(false);
        }
      }

      long ans;
      if (rs.empty || bs.empty) {
        ans = P[N - 1] - P[0];
      } else if (gs.empty) {
        ans = (P[rs[$ - 1]] - P[rs[0]]) + (P[bs[$ - 1]] - P[bs[0]]);
      } else {
        void doIt(char c) {
          foreach (u; 0 .. gs[0]) {
            if (C[u] == c) {
              ans += P[gs[0]] - P[u];
              break;
            }
          }
          foreach_reverse (u; gs[$ - 1] + 1 .. N) {
            if (C[u] == c) {
              ans += P[u] - P[gs[$ - 1]];
              break;
            }
          }
          foreach (j; 1 .. gs.length) {
            const a = gs[j - 1];
            const b = gs[j];
            int[] us;
            us ~= a;
            foreach (u; a + 1 .. b) {
              if (C[u] == c) {
                us ~= u;
              }
            }
            us ~= b;
            long mx;
            foreach (k; 1 .. us.length) {
              chmax(mx, P[us[k]] - P[us[k - 1]]);
            }
            ans += (P[b] - P[a]) - mx;
          }
        }
        ans = P[gs[$ - 1]] - P[gs[0]];
        doIt('R');
        doIt('B');
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

enum INF = 10L^^18;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto P = new long[N];
      auto C = new char[N];
      foreach (u; 0 .. N) {
        P[u] = readLong();
        C[u] = readToken()[0];
      }

      int[] rs, gs, bs;
      foreach (u; 0 .. N) {
        switch (C[u]) {
          case 'R': rs ~= u; break;
          case 'G': gs ~= u; break;
          case 'B': bs ~= u; break;
          default: assert(false);
        }
      }

      long ans;
      if (gs.empty) {
        if (rs.empty || bs.empty) {
          ans = P[N - 1] - P[0];
        } else {
          ans = (P[rs[$ - 1]] - P[rs[0]]) + (P[bs[$ - 1]] - P[bs[0]]);
          long mn = INF;
          foreach (u; 0 .. N - 1) {
            if (C[u] != C[u + 1]) {
              chmin(mn, P[u + 1] - P[u]);
            }
          }
          ans += mn;
        }
      } else {
        void doIt(char c) {
          foreach (u; 0 .. gs[0]) {
            if (C[u] == c) {
              ans += P[gs[0]] - P[u];
              break;
            }
          }
          foreach_reverse (u; gs[$ - 1] + 1 .. N) {
            if (C[u] == c) {
              ans += P[u] - P[gs[$ - 1]];
              break;
            }
          }
          foreach (j; 1 .. gs.length) {
            const a = gs[j - 1];
            const b = gs[j];
            int[] us;
            us ~= a;
            foreach (u; a + 1 .. b) {
              if (C[u] == c) {
                us ~= u;
              }
            }
            us ~= b;
            long mx;
            foreach (k; 1 .. us.length) {
              chmax(mx, P[us[k]] - P[us[k - 1]]);
            }
            ans += (P[b] - P[a]) - mx;
          }
        }
        ans = P[gs[$ - 1]] - P[gs[0]];
        doIt('R');
        doIt('B');
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

enum INF = 10L^^18;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto P = new long[N];
      auto C = new char[N];
      foreach (u; 0 .. N) {
        P[u] = readLong();
        C[u] = readToken()[0];
      }

      int[] rs, gs, bs;
      foreach (u; 0 .. N) {
        switch (C[u]) {
          case 'R': rs ~= u; break;
          case 'G': gs ~= u; break;
          case 'B': bs ~= u; break;
          default: assert(false);
        }
      }

      long ans;
      if (gs.empty) {
        if (rs.empty || bs.empty) {
          ans = P[N - 1] - P[0];
        } else {
          ans = (P[rs[$ - 1]] - P[rs[0]]) + (P[bs[$ - 1]] - P[bs[0]]);
          /*
          long mn = INF;
          foreach (u; 0 .. N - 1) {
            if (C[u] != C[u + 1]) {
              chmin(mn, P[u + 1] - P[u]);
            }
          }
          ans += mn;
          */
        }
      } else {
        void doIt(char c) {
          foreach (u; 0 .. gs[0]) {
            if (C[u] == c) {
              ans += P[gs[0]] - P[u];
              break;
            }
          }
          foreach_reverse (u; gs[$ - 1] + 1 .. N) {
            if (C[u] == c) {
              ans += P[u] - P[gs[$ - 1]];
              break;
            }
          }
          foreach (j; 1 .. gs.length) {
            const a = gs[j - 1];
            const b = gs[j];
            int[] us;
            us ~= a;
            foreach (u; a + 1 .. b) {
              if (C[u] == c) {
                us ~= u;
              }
            }
            us ~= b;
            long mx;
            foreach (k; 1 .. us.length) {
              chmax(mx, P[us[k]] - P[us[k - 1]]);
            }
            ans += (P[b] - P[a]) - mx;
          }
        }
        ans = P[gs[$ - 1]] - P[gs[0]];
        doIt('R');
        doIt('B');
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

enum INF = 10L^^18;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      auto P = new long[N];
      auto C = new char[N];
      foreach (u; 0 .. N) {
        P[u] = readLong();
        C[u] = readToken()[0];
      }

      int[] rs, gs, bs;
      foreach (u; 0 .. N) {
        switch (C[u]) {
          case 'R': rs ~= u; break;
          case 'G': gs ~= u; break;
          case 'B': bs ~= u; break;
          default: assert(false);
        }
      }

      long ans;
      if (rs.empty || bs.empty) {
        ans = P[N - 1] - P[0];
      } else if (gs.empty) {
        ans = (P[rs[$ - 1]] - P[rs[0]]) + (P[bs[$ - 1]] - P[bs[0]]);
        if (!rs.empty && !bs.empty) {
          long mn = INF;
          foreach (u; 0 .. N - 1) {
            if (C[u] != C[u + 1]) {
              chmin(mn, P[u + 1] - P[u]);
            }
          }
          ans += mn;
        }
      } else {
        void doIt(char c) {
          foreach (u; 0 .. gs[0]) {
            if (C[u] == c) {
              ans += P[gs[0]] - P[u];
              break;
            }
          }
          foreach_reverse (u; gs[$ - 1] + 1 .. N) {
            if (C[u] == c) {
              ans += P[u] - P[gs[$ - 1]];
              break;
            }
          }
          foreach (j; 1 .. gs.length) {
            const a = gs[j - 1];
            const b = gs[j];
            int[] us;
            us ~= a;
            foreach (u; a + 1 .. b) {
              if (C[u] == c) {
                us ~= u;
              }
            }
            us ~= b;
            long mx;
            foreach (k; 1 .. us.length) {
              chmax(mx, P[us[k]] - P[us[k - 1]]);
            }
            ans += (P[b] - P[a]) - mx;
          }
        }
        ans = P[gs[$ - 1]] - P[gs[0]];
        doIt('R');
        doIt('B');
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}