We already know of the large corporation where Polycarpus works as a system administrator. The computer network there consists of n computers and m cables that connect some pairs of computers. In other words, the computer network can be represented as some non-directed graph with n nodes and m edges. Let's index the computers with integers from 1 to n, let's index the cables with integers from 1 to m.Polycarpus was given an important task — check the reliability of his company's network. For that Polycarpus decided to carry out a series of k experiments on the computer network, where the i-th experiment goes as follows:  Temporarily disconnect the cables with indexes from li to ri, inclusive (the other cables remain connected).  Count the number of connected components in the graph that is defining the computer network at that moment.  Re-connect the disconnected cables with indexes from li to ri (that is, restore the initial network). Help Polycarpus carry out all experiments and for each print the number of connected components in the graph that defines the computer network through the given experiment. Isolated vertex should be counted as single component.

The first line contains two space-separated integers n, m (2 ≤ n ≤ 500; 1 ≤ m ≤ 104) — the number of computers and the number of cables, correspondingly. The following m lines contain the cables' description. The i-th line contains space-separated pair of integers xi, yi (1 ≤ xi, yi ≤ n; xi ≠ yi) — the numbers of the computers that are connected by the i-th cable. Note that a pair of computers can be connected by multiple cables. The next line contains integer k (1 ≤ k ≤ 2·104) — the number of experiments. Next k lines contain the experiments' descriptions. The i-th line contains space-separated integers li, ri (1 ≤ li ≤ ri ≤ m) — the numbers of the cables that Polycarpus disconnects during the i-th experiment.

Print k numbers, the i-th number represents the number of connected components of the graph that defines the computer network during the i-th experiment.

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

struct Dsu
{
  int[] size;
  int[] directParent;
  int noSets;
  static Dsu makeEmpty(int noElements)
  {
    Dsu dsu;
    with(dsu)
      {
	size = new int[](noElements); size[] = 1;
	directParent = new int[](noElements); foreach(i; 0 .. noElements) directParent[i] = i;
	noSets = noElements;
      }
    return dsu;
  }
  int rep(int n)
  {
    int i;for(i = n;directParent[i] != i;i = directParent[i]) {}
    for(int j = n;directParent[j] != j;){auto nj = directParent[j];directParent[j] = i;j = nj;}
    return i;
  }
  bool uniteSets(int x, int y)
  {
    x = rep(x);
    y = rep(y);
    if (x == y) return false;
    if (size[x] < size[y])
      swap(x, y);
    assert(size[x] >= size[y]);
    directParent[y] = x;
    noSets--;
    size[x] += size[y];
    return true;
  }
}

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  auto n = next!int;
  auto m = next!int;
  auto edges = new int[2][](m);
  auto fdsu = Dsu.makeEmpty(n);
  auto bdsu = Dsu.makeEmpty(n);
  auto fre = new bool[](m);
  auto bre = new bool[](m);
  foreach(e; 0 .. m)
    edges[e][] = [next!int - 1, next!int - 1];
  foreach(i; 0 .. m)
    fre[i] = fdsu.uniteSets(edges[i][0], edges[i][1]);
  foreach_reverse(i; 0 .. m)
    bre[i] = bdsu.uniteSets(edges[i][0], edges[i][1]);
  struct Adj
  {
    int nei;
    int id;
  }
  auto adj = new Adj[][](n);
  foreach(i, e; edges)
    if (fre[i] || bre[i])
      {
	adj[e[0]] ~= Adj(e[1], cast(int) i);
	adj[e[1]] ~= Adj(e[0], cast(int) i);
      }

  auto visited = new bool[](n);
  auto k = next!int;
  foreach(q; 0 .. k)
    {
      auto l = next!int - 1;
      auto r = next!int - 1;
      visited[] = false;
      void dfs(int i)
      {
	visited[i] = true;
	foreach(a; adj[i])
	  {
	    if (a.id >= l && a.id <= r)
	      continue;
	    if (visited[a.nei])
	      continue;
	    dfs(a.nei);
	  }
      }
      int comps = 0;
      foreach(i; 0 .. n)
	{
	  if (!visited[i])
	    {
	      dfs(i);
	      comps++;
	    }
	}
      comps.writeln;
    }
}

// INPUT

enum InputStyle
  {
    byChunk, byLine
  };
enum inputStyle = InputStyle.byLine;

File inputFile;
string popWord();
static if (inputStyle == InputStyle.byChunk)
  {
    const chunkSize = 1024 * 1024 * 8;
    const wordSize = 4096;
    char[chunkSize] chunkBuff;
    char[] currChunk;
    void renewChunk()
    {
      if (inputFile.eof)
        currChunk = null;
      else
        currChunk = inputFile.rawRead(chunkBuff);
    }
    char[wordSize] wordBuff;
    char[] word;
    string popWord()
    {
      if (currChunk.length == 0)
        renewChunk;
      assert(currChunk.length > 0);
      while (currChunk[0].isWhite)
        {

          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            renewChunk;
        }
      word = wordBuff[0 .. 0];
      while (!currChunk[0].isWhite)
        {
          word.length++;
          word[$ - 1] = currChunk[0];
          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            {
              renewChunk;
              if (currChunk.length == 0)
                return cast(string) word;
            }
        }
      return cast(string) word;
    }
  }
 else
   {
     DList!string _words;
     string popWord()
     {
       while (_words.empty)
         {
           foreach(w; inputFile.readln.split)
             {
               _words.insertBack(w);
             }
         }
       auto word = _words.front;
       _words.removeFront;
       return word;
     }
   }
T next(T)()
{
  return to!T(popWord);
}
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;

struct Dsu
{
  int[] size;
  int[] directParent;
  int noSets;
  static Dsu makeEmpty(int noElements)
  {
    Dsu dsu;
    with(dsu)
      {
	size = new int[](noElements); size[] = 1;
	directParent = new int[](noElements); foreach(i; 0 .. noElements) directParent[i] = i;
	noSets = noElements;
      }
    return dsu;
  }
  int rep(int n)
  {
    int i;
    for(i = n;
	directParent[i] != i;
	i = directParent[i]) {}
    for(int j = n;
	directParent[j] != j;)
      {
	auto oldparent = directParent[j];
	directParent[j] = i;
	j = oldparent;
      }
    return i;
  }
  bool uniteSets(int x, int y)
  {
    x = rep(x);
    y = rep(y);
    if (x == y) return false;
    if (size[x] < size[y])
      swap(x, y);
    assert(size[x] >= size[y]);
    directParent[y] = x;
    noSets--;
    size[x] += size[y];
    return true;
  }
}

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  auto n = next!int;
  auto m = next!int;
  auto edges = new int[2][](m);
  auto fdsu = Dsu.makeEmpty(n);
  auto bdsu = Dsu.makeEmpty(n);
  auto fre = new bool[](m);
  auto bre = new bool[](m);
  foreach(e; 0 .. m)
    {
      edges[e][0] = next!int - 1;
      edges[e][1] = next!int - 1;
    }
  foreach(i; 0 .. m)
    fre[i] = fdsu.uniteSets(edges[i][0], edges[i][1]);
  foreach_reverse(i; 0 .. m)
    bre[i] = bdsu.uniteSets(edges[i][0], edges[i][1]);
  struct Adj
  {
    int nei;
    int id;
  }
  auto adj = new Adj[][](n);
  foreach(i, e; edges)
    if (fre[i] || bre[i])
      {
	adj[e[0]] ~= Adj(e[1], cast(int) i);
	adj[e[1]] ~= Adj(e[0], cast(int) i);
      }

  auto visited = new bool[](n);
  auto k = next!int;
  foreach(q; 0 .. k)
    {
      auto l = next!int - 1;
      auto r = next!int - 1;
      visited[] = false;
      void dfs(int i)
      {
	visited[i] = true;
	foreach(a; adj[i])
	  {
	    if (a.id >= l && a.id <= r)
	      continue;
	    if (visited[a.nei])
	      continue;
	    dfs(a.nei);
	  }
      }
      int comps = 0;
      foreach(i; 0 .. n)
	{
	  if (!visited[i])
	    {
	      dfs(i);
	      comps++;
	    }
	}
      comps.writeln;
    }
}

// INPUT

enum InputStyle
  {
    byChunk, byLine
  };
enum inputStyle = InputStyle.byLine;

File inputFile;
string popWord();
static if (inputStyle == InputStyle.byChunk)
  {
    const chunkSize = 1024 * 1024 * 8;
    const wordSize = 4096;
    char[chunkSize] chunkBuff;
    char[] currChunk;
    void renewChunk()
    {
      if (inputFile.eof)
        currChunk = null;
      else
        currChunk = inputFile.rawRead(chunkBuff);
    }
    char[wordSize] wordBuff;
    char[] word;
    string popWord()
    {
      if (currChunk.length == 0)
        renewChunk;
      assert(currChunk.length > 0);
      while (currChunk[0].isWhite)
        {

          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            renewChunk;
        }
      word = wordBuff[0 .. 0];
      while (!currChunk[0].isWhite)
        {
          word.length++;
          word[$ - 1] = currChunk[0];
          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            {
              renewChunk;
              if (currChunk.length == 0)
                return cast(string) word;
            }
        }
      return cast(string) word;
    }
  }
 else
   {
     DList!string _words;
     string popWord()
     {
       while (_words.empty)
         {
           foreach(w; inputFile.readln.split)
             {
               _words.insertBack(w);
             }
         }
       auto word = _words.front;
       _words.removeFront;
       return word;
     }
   }
T next(T)()
{
  return to!T(popWord);
}
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;

struct Dsu
{
  int[] size;
  int[] directParent;
  int noSets;
  static Dsu makeEmpty(int noElements)
  {
    Dsu dsu;
    with(dsu)
      {
	size = new int[](noElements); size[] = 1;
	directParent = new int[](noElements); foreach(i; 0 .. noElements) directParent[i] = i;
	noSets = noElements;
      }
    return dsu;
  }
  int rep(int n)
  {
    auto p = directParent[n];
    if (p == n)
      return p;
    directParent[n] = rep(p);
    return directParent[n];
  }
  bool uniteSets(int x, int y)
  {
    x = rep(x);
    y = rep(y);
    if (x == y) return false;
    if (size[x] < size[y])
      swap(x, y);
    assert(size[x] >= size[y]);
    directParent[y] = x;
    noSets--;
    size[x] += size[y];
    return true;
  }
}

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  auto n = next!int;
  auto m = next!int;
  auto edges = new int[2][](m);
  auto fdsu = Dsu.makeEmpty(n);
  auto bdsu = Dsu.makeEmpty(n);
  auto fre = new bool[](m);
  auto bre = new bool[](m);
  foreach(e; 0 .. m)
    {
      edges[e][0] = next!int - 1;
      edges[e][1] = next!int - 1;
    }
  foreach(i; 0 .. m)
    fre[i] = fdsu.uniteSets(edges[i][0], edges[i][1]);
  foreach_reverse(i; 0 .. m)
    bre[i] = bdsu.uniteSets(edges[i][0], edges[i][1]);
  struct Adj
  {
    int nei;
    int id;
  }
  auto adj = new Adj[][](n);
  foreach(i, e; edges)
    if (fre[i] || bre[i])
      {
	adj[e[0]] ~= Adj(e[1], cast(int) i);
	adj[e[1]] ~= Adj(e[0], cast(int) i);
      }

  auto visited = new bool[](n);
  auto k = next!int;
  foreach(q; 0 .. k)
    {
      auto l = next!int - 1;
      auto r = next!int - 1;
      visited[] = false;
      void dfs(int i)
      {
	visited[i] = true;
	foreach(a; adj[i])
	  {
	    if (a.id >= l && a.id <= r)
	      continue;
	    if (visited[a.nei])
	      continue;
	    dfs(a.nei);
	  }
      }
      int comps = 0;
      foreach(i; 0 .. n)
	{
	  if (!visited[i])
	    {
	      dfs(i);
	      comps++;
	    }
	}
      comps.writeln;
    }
}

// INPUT

enum InputStyle
  {
    byChunk, byLine
  };
enum inputStyle = InputStyle.byLine;

File inputFile;
string popWord();
static if (inputStyle == InputStyle.byChunk)
  {
    const chunkSize = 1024 * 1024 * 8;
    const wordSize = 4096;
    char[chunkSize] chunkBuff;
    char[] currChunk;
    void renewChunk()
    {
      if (inputFile.eof)
        currChunk = null;
      else
        currChunk = inputFile.rawRead(chunkBuff);
    }
    char[wordSize] wordBuff;
    char[] word;
    string popWord()
    {
      if (currChunk.length == 0)
        renewChunk;
      assert(currChunk.length > 0);
      while (currChunk[0].isWhite)
        {

          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            renewChunk;
        }
      word = wordBuff[0 .. 0];
      while (!currChunk[0].isWhite)
        {
          word.length++;
          word[$ - 1] = currChunk[0];
          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            {
              renewChunk;
              if (currChunk.length == 0)
                return cast(string) word;
            }
        }
      return cast(string) word;
    }
  }
 else
   {
     DList!string _words;
     string popWord()
     {
       while (_words.empty)
         {
           foreach(w; inputFile.readln.split)
             {
               _words.insertBack(w);
             }
         }
       auto word = _words.front;
       _words.removeFront;
       return word;
     }
   }
T next(T)()
{
  return to!T(popWord);
}
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;
    }
}


There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step. You're given the initial arrangement of the psychos in the line. Calculate how many steps are needed to the moment of time such, that nobody kills his neighbor after that moment. Look notes to understand the statement more precise.

The first line of input contains integer n denoting the number of psychos, (1 ≤ n ≤ 105). In the second line there will be a list of n space separated distinct integers each in range 1 to n, inclusive — ids of the psychos in the line from left to right.

Print the number of steps, so that the line remains the same afterward.

NoteIn the first sample line of the psychos transforms as follows: [10 9 7 8 6 5 3 4 2 1]  →  [10 8 4]  →  [10]. So, there are two steps.

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

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

    auto a = new int[n];
    foreach (i; 0..n) readf(" %d", &a[i]), --a[i];
    a ~= n;

    auto rt = array(iota(1, n + 1));
    auto ls = array(iota(n));
    int[] nls;
    auto done = new bool[n];

    int ans;
    while (true) {
        foreach_reverse (i; ls)
            if (a[i] > a[rt[i]])
                done[rt[i]] = true, rt[i] = rt[rt[i]];
            else
                done[i] = true;
        foreach (i; ls)
            if (!done[i])
                nls ~= i;
        if (nls !is null) {
            ls = null;
            swap(ls, nls);
            ++ans;
        } else
            break;
    }

    writeln(ans);
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [n];
		foreach (i; 0..n)
		{
			readf (" %s", &a[i]);
		}
		a = [0] ~ a ~ [n + 1];
		auto prev = new int [n + 2];
		prev[0] = 0;
		foreach (i; 0..n + 1)
		{
			prev[i + 1] = i;
		}
		auto next = new int [n + 2];
		next[n + 1] = n + 1;
		foreach (i; 0..n + 1)
		{
			next[i] = i + 1;
		}
		auto iprev = prev.dup;
		auto inext = next.dup;
		auto del = new bool [n + 2];
		del[] = false;

		int res = 0;
		while (true)
		{
			bool ok = false;

			int p = inext[0];
			while (p <= n)
			{
				debug {write (' ', p);}
				if (del[p])
				{
					iprev[inext[p]] = iprev[p];
					inext[iprev[p]] = inext[p];
				}
				debug {writef ("(%s.%s)", a[p], a[next[p]]);}
				if (a[p] > a[next[p]] && !del[next[p]])
				{
					debug {write ('[', next[p], ']');}
					ok = true;
					del[next[p]] = true;
					int q = next[p];
					prev[next[q]] = prev[q];
					next[prev[q]] = next[q];
				}
				else
				{
					iprev[inext[p]] = iprev[p];
					inext[iprev[p]] = inext[p];
				}
				p = inext[p];
			}
			debug {writeln ();}

			if (!ok)
			{
				break;
			}
			res++;
		}
		writeln (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;

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);

  auto n = next!int;
  auto a = next!int(n);
  auto dt = new int[](n);
  dt[] = int.max;
  auto possible = SList!int(0);
 iloop:foreach(i; 1 .. n)
    {
      dt[i] = 1;
    searchkiller: while(true)
        {
          auto np = possible.front;
          if (dt[np] < dt[i])
            {
              possible.removeFront;
              continue searchkiller;
            }
          if (a[np] > a[i])
            {
              possible.insertFront(i);
              continue iloop;
            }
          else
            {
              if (dt[np] == int.max)
                {
                  dt[i] = int.max;
                  possible.insertFront(i);
                  continue iloop;
                }
              dt[i] = dt[np] + 1;
              possible.removeFront;
              continue searchkiller;
            }
        }
    }
  writeln(dt.filter!(t => t != int.max).fold!max(0));
}

// INPUT

enum InputStyle
  {
    byChunk, byLine
  };
enum inputStyle = InputStyle.byLine;

File inputFile;
string popWord();
static if (inputStyle == InputStyle.byChunk)
  {
    const chunkSize = 1024 * 1024 * 8;
    const wordSize = 4096;
    char[chunkSize] chunkBuff;
    char[] currChunk;
    void renewChunk()
    {
      if (inputFile.eof)
        currChunk = null;
      else
        currChunk = inputFile.rawRead(chunkBuff);
    }
    char[wordSize] wordBuff;
    char[] word;
    string popWord()
    {
      if (currChunk.length == 0)
        renewChunk;
      assert(currChunk.length > 0);
      while (currChunk[0].isWhite)
        {

          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            renewChunk;
        }
      word = wordBuff[0 .. 0];
      while (!currChunk[0].isWhite)
        {
          word.length++;
          word[$ - 1] = currChunk[0];
          currChunk = currChunk[1 .. $];
          if (currChunk.length == 0)
            {
              renewChunk;
              if (currChunk.length == 0)
                return cast(string) word;
            }
        }
      return cast(string) word;
    }
  }
 else
   {
     DList!string _words;
     string popWord()
     {
       while (_words.empty)
         {
           foreach(w; inputFile.readln.split)
             {
               _words.insertBack(w);
             }
         }
       auto word = _words.front;
       _words.removeFront;
       return word;
     }
   }
T next(T)()
{
  return to!T(popWord);
}
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;
    }
}


Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-digit?

The first line contains the only integer n (0 ≤ n ≤ 10100000). It is guaranteed that n doesn't contain any leading zeroes.

Print the number of times a number can be replaced by the sum of its digits until it only contains one digit.

NoteIn the first sample the number already is one-digit — Herald can't cast a spell.The second test contains number 10. After one casting of a spell it becomes 1, and here the process is completed. Thus, Gerald can only cast the spell once.The third test contains number 991. As one casts a spell the following transformations take place: 991 → 19 → 10 → 1. After three transformations the number becomes one-digit.

import std.stdio;
import std.conv;

int sumit(string str) {
    int result = 0;
    foreach (c; str) {
        result += c - '0';
    }
    return result;
}

int main() {
    debug stdin = File("in.txt", "r");

    string str;
    readf(" %s\n", &str);
    int answer = 0;
    while (str.length > 1) {
        ++answer;
        int res = sumit(str);
        str = to!string(res);
    }
    writeln(answer);

    return 0;
}


You are given a complete directed graph $$$K_n$$$ with $$$n$$$ vertices: each pair of vertices $$$u \neq v$$$ in $$$K_n$$$ have both directed edges $$$(u, v)$$$ and $$$(v, u)$$$; there are no self-loops.You should find such a cycle in $$$K_n$$$ that visits every directed edge exactly once (allowing for revisiting vertices).We can write such cycle as a list of $$$n(n - 1) + 1$$$ vertices $$$v_1, v_2, v_3, \dots, v_{n(n - 1) - 1}, v_{n(n - 1)}, v_{n(n - 1) + 1} = v_1$$$ — a visiting order, where each $$$(v_i, v_{i + 1})$$$ occurs exactly once.Find the lexicographically smallest such cycle. It's not hard to prove that the cycle always exists.Since the answer can be too large print its $$$[l, r]$$$ segment, in other words, $$$v_l, v_{l + 1}, \dots, v_r$$$.

The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of test cases. Next $$$T$$$ lines contain test cases — one per line. The first and only line of each test case contains three integers $$$n$$$, $$$l$$$ and $$$r$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le l \le r \le n(n - 1) + 1$$$, $$$r - l + 1 \le 10^5$$$) — the number of vertices in $$$K_n$$$, and segment of the cycle to print. It's guaranteed that the total sum of $$$n$$$ doesn't exceed $$$10^5$$$ and the total sum of $$$r - l + 1$$$ doesn't exceed $$$10^5$$$.

For each test case print the segment $$$v_l, v_{l + 1}, \dots, v_r$$$ of the lexicographically smallest cycle that visits every edge exactly once.

NoteIn the second test case, the lexicographically minimum cycle looks like: $$$1, 2, 1, 3, 2, 3, 1$$$.In the third test case, it's quite obvious that the cycle should start and end in vertex $$$1$$$.

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int n;
		long lo, hi;
		readf !(" %s %s %s") (n, lo, hi);
		lo -= 1;
		int [] ans;
		long pos = 0;
		foreach (i; 0..n)
		{
			if (pos >= hi)
			{
				break;
			}
			if (pos + (n - i - 1) * 2 <= lo)
			{
				pos += (n - i - 1) * 2;
				continue;
			}
			foreach (j; i + 1..n)
			{
				if (lo <= pos && pos < hi)
				{
					ans ~= i;
				}
				pos += 1;
				if (lo <= pos && pos < hi)
				{
					ans ~= j;
				}
				pos += 1;
			}
		}
		if (pos < hi)
		{
			ans ~= 0;
		}
		ans[] += 1;
		writefln !("%(%s %)") (ans);
	}
}


You are given an array $$$a$$$ of length $$$n$$$. Let $$$cnt_x$$$ be the number of elements from the array which are equal to $$$x$$$. Let's also define $$$f(x, y)$$$ as $$$(cnt_x + cnt_y) \cdot (x + y)$$$.Also you are given $$$m$$$ bad pairs $$$(x_i, y_i)$$$. Note that if $$$(x, y)$$$ is a bad pair, then $$$(y, x)$$$ is also bad.Your task is to find the maximum value of $$$f(u, v)$$$ over all pairs $$$(u, v)$$$, such that $$$u \neq v$$$, that this pair is not bad, and also that $$$u$$$ and $$$v$$$ each occur in the array $$$a$$$. It is guaranteed that such a pair exists.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 3 \cdot 10^5$$$, $$$0 \le m \le 3 \cdot 10^5$$$) — the length of the array and the number of bad pairs. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — elements of the array. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i < y_i \le 10^9$$$), which represent a bad pair. It is guaranteed that no bad pair occurs twice in the input. It is also guaranteed that $$$cnt_{x_i} > 0$$$ and $$$cnt_{y_i} > 0$$$. It is guaranteed that for each test case there is a pair of integers $$$(u, v)$$$, $$$u \ne v$$$, that is not bad, and such that both of these numbers occur in $$$a$$$. It is guaranteed that the total sum of $$$n$$$ and the total sum of $$$m$$$ don't exceed $$$3 \cdot 10^5$$$.

For each test case print a single integer — the answer to the problem.

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

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

		alias Pair = Tuple !(int, q{x}, int, q{y});
		bool [Pair] bad;
		foreach (j; 0..m)
		{
			Pair p;
			readf !(" %s %s") (p.x, p.y);
			bad[p] = true;
			swap (p.x, p.y);
			bad[p] = true;
		}

		int [int] cnt;
		foreach (ref c; a)
		{
			cnt[c] += 1;
		}

		int [] [int] byCnt;
		foreach (k, v; cnt)
		{
			byCnt[v] ~= k;
		}

		foreach (line; byCnt)
		{
			sort (line);
		}

		long res = 0;
		foreach (k, _; cnt)
		{
			auto cntK = cnt[k];
			foreach (cnt2; 1..cntK + 1)
			{
				if (cnt2 !in byCnt)
				{
					continue;
				}
				foreach_reverse (elem; byCnt[cnt2])
				{
					if (k != elem &&
					   Pair (k, elem) !in bad)
					{
						res = max (res, (k + elem) *
						    1L * (cntK + cnt2));
						break;
					}
				}
			}
		}
		writeln (res);
	}
}

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

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

		alias Pair = Tuple !(int, q{x}, int, q{y});
		bool [Pair] bad;
		foreach (j; 0..m)
		{
			Pair p;
			readf !(" %s %s") (p.x, p.y);
			bad[p] = true;
			swap (p.x, p.y);
			bad[p] = true;
		}

		int [int] cnt;
		foreach (ref c; a)
		{
			cnt[c] += 1;
		}

		int [] [int] byCnt;
		foreach (k, v; cnt)
		{
			byCnt[v] ~= k;
		}

		foreach (line; byCnt)
		{
			sort (line);
		}

		long res = 0;
		foreach (k, _; cnt)
		{
			auto cntK = cnt[k];
			foreach (curCnt, line; byCnt)
			{
				foreach_reverse (elem; line)
				{
					if (k != elem &&
					   Pair (k, elem) !in bad)
					{
						res = max (res, (k + elem) *
						    1L * (cntK + curCnt));
						break;
					}
				}
			}
		}
		writeln (res);
	}
}

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

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

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

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

void main() {
  try {
    for (; ; ) {
      const numCases = readInt;
      foreach (caseId; 0 .. numCases) {
        const L = readInt;
        const M = readInt;
        auto A = new long[L];
        foreach (l; 0 .. L) {
          A[l] = readLong;
        }
        auto X = new long[M];
        auto Y = new long[M];
        foreach (i; 0 .. M) {
          X[i] = readLong;
          Y[i] = readLong;
        }

        auto as = A.dup;
        as = as.sort.uniq.array;
        const V = cast(int)(as.length);

        auto cnt = new int[V];
        foreach (l; 0 .. L) {
          ++cnt[as.lowerBound(A[l])];
        }
        auto uss = new int[][L + 1];
        foreach (u; 0 .. V) {
          uss[cnt[u]] ~= u;
        }
        foreach (k; 1 .. L + 1) if (!uss[k].empty) {
          uss[k].sort!((u, v) => (as[u] > as[v]));
        }

        auto graph = new int[][V];
        foreach (i; 0 .. M) {
          const u = as.lowerBound(X[i]);
          const v = as.lowerBound(Y[i]);
          graph[u] ~= v;
          graph[v] ~= u;
        }

        auto bad = new int[V];
        bad[] = -1;
        long ans;
        foreach (u; 0 .. V) {
          bad[u] = u;
          foreach (v; graph[u]) {
            bad[v] = u;
          }
          foreach (k; 1 .. cnt[u] + 1) {
            foreach (v; uss[k]) {
              if (bad[v] != u) {
                chmax(ans, 1L * (cnt[u] + cnt[v]) * (as[u] + as[v]));
                break;
              }
            }
          }
        }
        writeln(ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

		alias Pair = Tuple !(int, q{x}, int, q{y});
		bool [Pair] bad;
		foreach (j; 0..m)
		{
			Pair p;
			readf !(" %s %s") (p.x, p.y);
			bad[p] = true;
			swap (p.x, p.y);
			bad[p] = true;
		}

		int [int] cnt;
		foreach (ref c; a)
		{
			cnt[c] += 1;
		}

		int [] [int] byCnt;
		foreach (k, v; cnt)
		{
			byCnt[v] ~= k;
		}

		foreach (line; byCnt)
		{
			sort (line);
		}

		long res = 0;
		foreach (k, _; cnt)
		{
			auto cntK = cnt[k];
			foreach (cnt2; 1..cntK + 1)
			{
				if (cnt2 !in cnt)
				{
					continue;
				}
				foreach_reverse (elem; byCnt[cnt2])
				{
					if (k != elem &&
					   Pair (k, elem) !in bad)
					{
						res = max (res, (k + elem) *
						    1L * (cntK + cnt2));
						break;
					}
				}
			}
		}
		writeln (res);
	}
}


A total of $$$n$$$ depots are located on a number line. Depot $$$i$$$ lies at the point $$$x_i$$$ for $$$1 \le i \le n$$$.You are a salesman with $$$n$$$ bags of goods, attempting to deliver one bag to each of the $$$n$$$ depots. You and the $$$n$$$ bags are initially at the origin $$$0$$$. You can carry up to $$$k$$$ bags at a time. You must collect the required number of goods from the origin, deliver them to the respective depots, and then return to the origin to collect your next batch of goods.Calculate the minimum distance you need to cover to deliver all the bags of goods to the depots. You do not have to return to the origin after you have delivered all the bags.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \ldots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$). It is possible that some depots share the same position. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer denoting the minimum distance you need to cover to deliver all the bags of goods to the depots.

NoteIn the first test case, you can carry only one bag at a time. Thus, the following is a solution sequence that gives a minimum travel distance: $$$0 \to 2 \to 0 \to 4 \to 0 \to 3 \to 0 \to 1 \to 0 \to 5$$$, where each $$$0$$$ means you go the origin and grab one bag, and each positive integer means you deliver the bag to a depot at this coordinate, giving a total distance of $$$25$$$ units. It must be noted that there are other sequences that give the same distance.In the second test case, you can follow the following sequence, among multiple such sequences, to travel minimum distance: $$$0 \to 6 \to 8 \to 7 \to 0 \to 5 \to 4 \to 3 \to 0 \to (-5) \to (-10) \to (-15)$$$, with distance $$$41$$$. It can be shown that $$$41$$$ is the optimal distance for this test case.

immutable multi = true;

void solve(int tc)
{
  auto n = readInt!int;
  auto k = readInt!int;
  auto brchs = new long[][](2);
  auto xs = ma(n, readInt!long);
  foreach(xi; xs)
    if (xi > 0) brchs[1] ~= xi;
    else brchs[0] ~= -xi;
  sort(brchs[0]);
  sort(brchs[1]);
  debug writeln("branch 0 : ", brchs[0]);
  debug writeln("branch 1 : ", brchs[0]);
  long ans = long.max;
  long doBrch(int i, bool last)
  {
    auto vw = brchs[i][0 .. $];
    long vl = 0;
    if (last)
      {
	if (vw.length)
	  {
	    vl += vw.back;
	  }
	vw = vw[0 .. max(0, cast(int)$ - k)];
      }
    while (vw.length >= k)
      {
	vl += 2 * vw.back;
	vw = vw[0 .. $ - k];
      }
    if (vw.length) vl += 2 * vw.back;
    return vl;
  }
  debug writeln("brch 1 true " , doBrch(1, true));
  debug writeln("brch 1 false " , doBrch(1, false));

  debug writeln("brch 0 true " , doBrch(0, true));
  debug writeln("brch 0 false " , doBrch(0, false));

  return writeln(min(doBrch(0, true) + doBrch(1, false),
		     doBrch(0, false) + doBrch(1, true)));
}

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

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

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

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

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


As you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n - 1 two-way roads. The cities are numbered from 1 to n. You can get from one city to another moving along the roads.The «Two Paths» company, where Bob's brother works, has won a tender to repair two paths in Flatland. A path is a sequence of different cities, connected sequentially by roads. The company is allowed to choose by itself the paths to repair. The only condition they have to meet is that the two paths shouldn't cross (i.e. shouldn't have common cities).It is known that the profit, the «Two Paths» company will get, equals the product of the lengths of the two paths. Let's consider the length of each road equals 1, and the length of a path equals the amount of roads in it. Find the maximum possible profit for the company.

The first line contains an integer n (2 ≤ n ≤ 200), where n is the amount of cities in the country. The following n - 1 lines contain the information about the roads. Each line contains a pair of numbers of the cities, connected by the road ai, bi (1 ≤ ai, bi ≤ n).

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

void main(string[] args)
{
  auto n = next!int;
  auto adj = new int[][](n);
  foreach(i; 0 .. n - 1)
    {
      auto ai = next!int - 1;
      auto bi = next!int - 1;
      adj[ai] ~= bi;
      adj[bi] ~= ai;
    }

  auto mxSbPath = new int[](n);
  auto subMax = new int[](n);
  int realmax = 0;
  foreach(root; 0 .. n)
    {
      auto maxVal = redBlackTree!((a, b) => a > b, true, int)();
      void dfs1(int v, int p)
      {
	mxSbPath[v] = 1;
	int maxChild = 0;
	int fmax = 0, smax = 0;
	foreach(w; adj[v])
	  if (w != p)
	    {
	      dfs1(w, v);
	      auto e = mxSbPath[w];
	      if (e > fmax)
		{
		  smax = fmax;
		  fmax = e;
		}
	      else
		{
		  if (e > smax)
		    smax = e;
		}
	      maxChild = max(maxChild, mxSbPath[w]);
	    }
	subMax[v] = 1 + smax + fmax;
	mxSbPath[v] += maxChild;
	maxVal.insert(subMax[v]);
      }
      dfs1(root, -1);
      int mx = 0;
      void dfs2(int v, int p, int len)
      {
	maxVal.removeKey(subMax[v]);
	mx = max(mx, (len - 1) * (maxVal.front - 1));
	foreach(w; adj[v])
	  if (w != p)
	    {
	      dfs2(w, v, len + 1);
	    }
	maxVal.insert(subMax[v]);
      }
      dfs2(root, -1, 1);
      realmax = max(realmax, mx);
    }
  realmax.writeln;
}

static this()
{
  popChar;
}

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

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

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

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

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

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


You are given a board of size $$$2 \times n$$$ ($$$2$$$ rows, $$$n$$$ columns). Some cells of the board contain chips. The chip is represented as '*', and an empty space is represented as '.'. It is guaranteed that there is at least one chip on the board.In one move, you can choose any chip and move it to any adjacent (by side) cell of the board (if this cell is inside the board). It means that if the chip is in the first row, you can move it left, right or down (but it shouldn't leave the board). Same, if the chip is in the second row, you can move it left, right or up.If the chip moves to the cell with another chip, the chip in the destination cell disappears (i. e. our chip captures it).Your task is to calculate the minimum number of moves required to leave exactly one chip on the board.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the board. The second line of the test case contains the string $$$s_1$$$ consisting of $$$n$$$ characters '*' (chip) and/or '.' (empty cell). The third line of the test case contains the string $$$s_2$$$ consisting of $$$n$$$ characters '*' (chip) and/or '.' (empty cell). Additional constraints on the input:   in each test case, there is at least one chip on a board;  the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print one integer — the minimum number of moves required to leave exactly one chip on the board.

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

immutable int rows = 2;

auto solve (bool [] [] board, int cols)
{
	auto f = new int [rows] [cols + 1];
	bool prev = false;
	foreach (col; 0..cols)
	{
		foreach (row; 0..rows)
		{
			if (prev)
			{
				if (board[!row][col - 1])
				{
					f[col + 1][row] = min
					    (f[col][row] + 2,
					    f[col][!row] + 2);
				}
				else
				{
					f[col + 1][row] = min
					    (f[col][row] + 1,
					    f[col][!row] + 2);
				}
			}
		}
		if (board[0][col] || board[1][col])
		{
			prev = true;
		}
	}
	return f;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto cols = readln.strip.to !(int);
		bool [] [] board;
		foreach (row; 0..rows)
		{
			board ~= readln.strip.map !(q{a == '*'}).array;
		}
		auto f = solve (board, cols);
		foreach (row; 0..rows)
		{
			reverse (board[row]);
		}
		auto g = solve (board, cols);
		foreach (row; 0..rows)
		{
			reverse (board[row]);
		}
		reverse (g);
		debug {writeln (f); writeln (g);}
		int res = int.max;
		foreach (col; 0..cols)
		{
			foreach (row; 0..rows)
			{
				res = min (res, f[col + 1][row] +
				    g[col][row] + board[!row][col]);
			}
		}
		writeln (res);
	}
}

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

immutable int rows = 2;

auto solve (bool [] [] board, int cols)
{
	auto f = new int [rows] [cols + 1];
	bool prev = false;
	foreach (col; 0..cols)
	{
		foreach (row; 0..rows)
		{
			if (prev)
			{
				if (board[!row][col - 1])
				{
					f[col + 1][row] = min
					    (f[col][row] + 3,
					    f[col][!row] + 2);
				}
				else
				{
					f[col + 1][row] = min
					    (f[col][row] + 1,
					    f[col][!row] + 2);
				}
			}
		}
		if (board[0][col] || board[1][col])
		{
			prev = true;
		}
	}
	return f;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto cols = readln.strip.to !(int);
		bool [] [] board;
		foreach (row; 0..rows)
		{
			board ~= readln.strip.map !(q{a == '*'}).array;
		}
		auto f = solve (board, cols);
		foreach (row; 0..rows)
		{
			reverse (board[row]);
		}
		auto g = solve (board, cols);
		foreach (row; 0..rows)
		{
			reverse (board[row]);
		}
		reverse (g);
		debug {writeln (f); writeln (g);}
		int res = int.max;
		foreach (col; 0..cols)
		{
			foreach (row; 0..rows)
			{
				res = min (res, f[col + 1][row] +
				    g[col][row] + board[!row][col]);
			}
		}
		writeln (res);
	}
}


Berland is going through tough times — the dirt price has dropped and that is a blow to the country's economy. Everybody knows that Berland is the top world dirt exporter!The President of Berland was forced to leave only k of the currently existing n subway stations.The subway stations are located on a straight line one after another, the trains consecutively visit the stations as they move. You can assume that the stations are on the Ox axis, the i-th station is at point with coordinate xi. In such case the distance between stations i and j is calculated by a simple formula |xi - xj|.Currently, the Ministry of Transport is choosing which stations to close and which ones to leave. Obviously, the residents of the capital won't be too enthusiastic about the innovation, so it was decided to show the best side to the people. The Ministry of Transport wants to choose such k stations that minimize the average commute time in the subway!Assuming that the train speed is constant (it is a fixed value), the average commute time in the subway is calculated as the sum of pairwise distances between stations, divided by the number of pairs (that is ) and divided by the speed of the train.Help the Minister of Transport to solve this difficult problem. Write a program that, given the location of the stations selects such k stations that the average commute time in the subway is minimized.

The first line of the input contains integer n (3 ≤ n ≤ 3·105) — the number of the stations before the innovation. The second line contains the coordinates of the stations x1, x2, ..., xn ( - 108 ≤ xi ≤ 108). The third line contains integer k (2 ≤ k ≤ n - 1) — the number of stations after the innovation. The station coordinates are distinct and not necessarily sorted.

Print a sequence of k distinct integers t1, t2, ..., tk (1 ≤ tj ≤ n) — the numbers of the stations that should be left after the innovation in arbitrary order. Assume that the stations are numbered 1 through n in the order they are given in the input. The number of stations you print must have the minimum possible average commute time among all possible ways to choose k stations. If there are multiple such ways, you are allowed to print any of them.

NoteIn the sample testcase the optimal answer is to destroy the first station (with x = 1). The average commute time will be equal to 1 in this way.

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		alias Tuple !(int, "v", int, "d") pair;
		auto x = new pair [n];
		foreach (i; 0..n)
		{
			readf (" %s", &x[i].v);
			x[i].d = i + 1;
		}
		int k;
		readf (" %s", &k);
		x.sort !("a < b", SwapStrategy.stable);
		x ~= x[$ - 1];

		long s = 0;
		long cur = 0;
		foreach (i; 0..k)
		{
			s += x[i].v;
			cur += x[i].v * cast (long) (i + 1) - s;
		}

		long res = long.max;
		int st = int.min;
		foreach (i; k..n + 1)
		{
			debug {writefln ("i = %s, cur = %s, res = %s, s = %s",
			                 i, cur, res, s);}
			if (res > cur)
			{
				res = cur;
				st = i - k;
			}
			cur -= s - x[i - k].v * cast (long) k;
			s += x[i].v - x[i - k].v;
			cur += x[i].v * cast (long) k - s;
		}
		debug {writeln (res);}
		writefln ("%(%s %)", k.iota.map !(a => x[a + st].d).array);
	}
}

import std.algorithm;
import std.array;
import std.range;
import std.stdio;
import std.typecons;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		alias Tuple !(int, "v", int, "d") pair;
		auto x = new pair [n];
		foreach (i; 0..n)
		{
			readf (" %s", &x[i].v);
			x[i].d = i + 1;
		}
		int k;
		readf (" %s", &k);
		x.sort !("a < b", SwapStrategy.stable);
		x ~= x[$ - 1];

		long s = 0;
		long cur = 0;
		foreach (i; 0..k)
		{
			s += x[i].v;
			cur += x[i].v * cast (long) (i + 1) - s;
		}

		long res = long.max;
		int st = int.min;
		foreach (i; k..n + 1)
		{
			if (res > cur)
			{
				res = cur;
				st = i - k;
			}
			cur -= s - x[i - k].v * cast (long) k;
			s += x[i].v - x[i - k].v;
			cur += x[i].v * cast (long) k - s;
		}
		writefln ("%(%s %)", k.iota.map !(a => x[a + st].d).array);
	}
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto x = new int [n];
		foreach (i; 0..n)
		{
			readf (" %s", &x[i]);
		}
		int k;
		readf (" %s", &k);
		x.sort !("a < b", SwapStrategy.stable);
		x ~= x[$ - 1];

		long s = 0;
		long cur = 0;
		foreach (i; 0..k)
		{
			s += x[i];
			cur += x[i] * (i + 1) - s;
		}

		long res = long.max;
		int st = int.min;
		foreach (i; k..n + 1)
		{
			debug {writefln ("i = %s, cur = %s, res = %s, s = %s",
			                 i, cur, res, s);}
			if (res > cur)
			{
				res = cur;
				st = i - k + 1;
			}
			cur -= s - x[i - k] * k;
			s += x[i] - x[i - k];
			cur += x[i] * k - s;
		}
		debug {writeln (res);}
		writefln ("%(%s %)", k.iota.map !(a => a + st).array);
	}
}

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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto x = new int [n];
		foreach (i; 0..n)
		{
			readf (" %s", &x[i]);
		}
		int k;
		readf (" %s", &k);
		x.sort !("a < b", SwapStrategy.stable);
		x ~= x[$ - 1];

		long s = 0;
		long cur = 0;
		foreach (i; 0..k)
		{
			s += x[i];
			cur += x[i] * (i + 1) - s;
		}

		long res = long.max;
		foreach (i; k..n + 1)
		{
			debug {writefln ("i = %s, cur = %s, res = %s, s = %s",
			                 i, cur, res, s);}
			res = min (res, cur);
			cur -= s - x[i - k] * k;
			s += x[i] - x[i - k];
			cur += x[i] * k - s;
		}
		writeln (res);
	}
}


Ashish has an array $$$a$$$ of size $$$n$$$.A subsequence of $$$a$$$ is defined as a sequence that can be obtained from $$$a$$$ by deleting some elements (possibly none), without changing the order of the remaining elements.Consider a subsequence $$$s$$$ of $$$a$$$. He defines the cost of $$$s$$$ as the minimum between:   The maximum among all elements at odd indices of $$$s$$$.  The maximum among all elements at even indices of $$$s$$$. Note that the index of an element is its index in $$$s$$$, rather than its index in $$$a$$$. The positions are numbered from $$$1$$$. So, the cost of $$$s$$$ is equal to $$$min(max(s_1, s_3, s_5, \ldots), max(s_2, s_4, s_6, \ldots))$$$.For example, the cost of $$$\{7, 5, 6\}$$$ is $$$min( max(7, 6), max(5) ) = min(7, 5) = 5$$$.Help him find the minimum cost of a subsequence of size $$$k$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \leq k \leq n \leq 2 \cdot 10^5$$$)  — the size of the array $$$a$$$ and the size of the subsequence. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$)  — the elements of the array $$$a$$$.

Output a single integer  — the minimum cost of a subsequence of size $$$k$$$.

NoteIn the first test, consider the subsequence $$$s$$$ = $$$\{1, 3\}$$$. Here the cost is equal to $$$min(max(1), max(3)) = 1$$$.In the second test, consider the subsequence $$$s$$$ = $$$\{1, 2, 4\}$$$. Here the cost is equal to $$$min(max(1, 4), max(2)) = 2$$$.In the fourth test, consider the subsequence $$$s$$$ = $$$\{3, 50, 2, 4\}$$$. Here the cost is equal to $$$min(max(3, 2), max(50, 4)) = 3$$$.

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

alias A = Tuple!(int, "i", int, "a");

void main()
{
    auto nk = readln.split.to!(int[]);
    auto N = nk[0];
    auto K = nk[1];

    int o_i, o_j, e_i, e_j;
    if (K%2 == 0) {
        o_i = 0;
        o_j = N-2;
        e_i = 1;
        e_j = N-1;
    } else {
        o_i = 0;
        o_j = N-1;
        e_i = 1;
        e_j = N-2;
    }

    int[] aa, bb;
    foreach (a; readln.split.to!(int[])) {
        aa ~= a;
        bb ~= a;
    }
    sort(bb);
    bb.uniq();
    int l = -1, r = N-1;
    while (l+1 < r) {
        auto m = (l+r)/2;
        auto a = bb[m];
        // odd
        {
            int i = o_i;
            int o;
            while (i <= o_j) {
                if (aa[i] <= a) {
                    ++o;
                    ++i;
                }
                ++i;
            }

            if (o >= (K+1)/2) {
                r = m;
                continue;
            }
        }
        // even
        {
            auto i = e_i;
            int e;
            while (i <= e_j) {
                if (aa[i] <= a) {
                    ++e;
                    ++i;
                }
                ++i;
            }

            if (e >= K/2) {
                r = m;
                continue;
            }
        }

        l = m;
    }
    writeln(bb[r]);
}

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

bool ok (int [] a, int me, int k)
{
	int pos = 0;
	foreach (ref c; a)
	{
		if ((pos & 1) || (c <= me))
		{
			pos += 1;
		}
	}
	return pos >= k;
}

int solveOdd (int [] a, int k)
{
	int lo = 0;
	int hi = 10 ^^ 9 + 1;
	while (lo < hi)
	{
		int me = (lo + hi) >> 1;
		if (ok (a, me, k))
		{
			hi = me;
		}
		else
		{
			lo = me + 1;
		}
	}
	return lo;
}

void main ()
{
	int n, k;
	while (readf !(" %s %s") (n, k) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		writeln (min (solveOdd (a, k), solveOdd (a[1..$], k - 1)));
	}
}

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

long x10(long mul, long exp)
{
  long res = 1;
  foreach(i; 0 .. exp)
    res *= 10;
  res *= mul;
  return res;
}

int maxPlace(int[] arr, int ub)
{
  int res = 0;
  for(int i = 0; i < arr.length; i++)
    {
      if (arr[i] <= ub)
        {
          res++;
          i++;
        }
    }
  return res;
}

int[2.x10(5)] A;

void main()
{
  static assert(int.max >= 2.x10(5));
  int n, k; read(n, k);
  auto a = A[0 .. n];
  read(a);
  bool function(int, int, int[]) can;
  if (k % 2 == 0)
    {
      can = (int ub, int k, int[] a)
        {
          return maxPlace(a[0 .. $ - 1], ub) >= k / 2 ||
          maxPlace(a[1 .. $], ub) >= k / 2;
        };
    }
  else
    {
      can = (int ub, int k, int[] a)
        {
          return maxPlace(a[0 .. $], ub) >= (k / 2 + 1) ||
          maxPlace(a[1 .. $ - 1], ub) >= k / 2;
        };
    }
  auto minres = cast(int) 1.x10(9);
  int hi = minres;
  int lo = 1;
  while(lo <= hi)
    {
      int mid = (lo + hi) / 2;
      if (can(mid, k, a))
        {
          minres = min(minres, mid);
          hi = mid - 1;
        }
      else
        {
          lo = mid + 1;
        }
    }
  minres.writeln;
}

alias seq = (x, y) => iota(x, y + 1);
alias writesp = (x) => write(x, " ");

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

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

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

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

long x10(long mul, long exp)
{
  long res = 1;
  foreach(i; 0 .. exp)
    res *= 10;
  res *= mul;
  return res;
}

int[2.x10(5)] A;

void main()
{
  static assert(int.max >= 2.x10(5));
  int n, k; read(n, k);
  auto a = A[0 .. n];
  read(a);
  int maxPlace(int[] arr, int ub)
  {
    int res = 0;
    for(int i = 0; i < arr.length; i++)
      {
        if (arr[i] <= ub)
          {
            res++;
            i++;
          }
      }
    return res;
  }
  bool delegate(int) can;
  if (k % 2 == 0)
    {
      can = (int ub)
        {
          return maxPlace(a[0 .. $ - 1], ub) >= k / 2 ||
          maxPlace(a[1 .. $], ub) >= k / 2;
        };
    }
  else
    {
      can = (int ub)
        {
          return maxPlace(a[0 .. $], ub) >= (k / 2 + 1) ||
          maxPlace(a[1 .. $ - 1], ub) >= k / 2;
        };
    }
  auto minres = cast(int) 1.x10(9);
  int hi = minres;
  int lo = 1;
  while(lo <= hi)
    {
      int mid = (lo + hi) / 2;
      if (can(mid))
        {
          minres = min(minres, mid);
          hi = mid - 1;
        }
      else
        {
          lo = mid + 1;
        }
    }
  minres.writeln;
}

alias seq = (x, y) => iota(x, y + 1);
alias writesp = (x) => write(x, " ");

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

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

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

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

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

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

	bool f(int x)
	{
		{
			auto dp = new int[](n+2);
			auto begin = k % 2 ? 1 : 0;
			auto end   = n-1;
			foreach (i; begin..end)
			{
				if (a[i] <= x)
				{
					if (dp[i]+1 == k/2) return true;
					dp[i+2].chmax(dp[i]+1);
				}
				dp[i+1].chmax(dp[i]);
			}
		}
		{
			auto dp = new int[](n+2);
			auto begin = k % 2 ? 0 : 1;
			auto end   = n;
			foreach (i; begin..end)
			{
				if (a[i] <= x)
				{
					if (dp[i]+1 == (k+1)/2) return true;
					dp[i+2].chmax(dp[i]+1);
				}
				dp[i+1].chmax(dp[i]);
			}
		}
		return false;
	}

	auto ans = binarySearch!(f)(10^^9, 0);

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

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

alias A = Tuple!(int, "i", int, "a");

void main()
{
    auto nk = readln.split.to!(int[]);
    auto N = nk[0];
    auto K = nk[1];

    int o_i, o_j, e_i, e_j;
    if (K%2 == 0) {
        o_i = 0;
        o_j = N-2;
        e_i = 1;
        e_j = N-1;
    } else {
        o_i = 0;
        o_j = N-1;
        e_i = 1;
        e_j = N-2;
    }

    int[] aa;
    auto AA = [A(-1, -1)];
    foreach (i, a; readln.split.to!(int[])) {
        aa ~= a;
        AA ~= A(i.to!int, a);
    }
    sort!"a.a < b.a"(AA);
    int l, r = N;
    while (l+1 < r) {
        auto m = (l+r)/2;
        auto k = AA[m].i;
        auto a = AA[m].a;

        auto i = k;
        auto j = k;
        // odd
        if (o_i <= k && k <= o_j) {
            int o = 1;
            while (i-1 >= o_i) {
                --i;
                if (aa[i] <= a) {
                    ++o;
                    --i;
                }
            }
            while (j+1 <= o_j) {
                ++j;
                if (aa[j] <= a) {
                    ++o;
                    ++j;
                }
            }

            if (o >= (K+1)/2) {
                r = m;
                continue;
            }
        }

        i = k;
        j = k;
        // even
        if (e_i <= k && k <= e_j) {
            int e = 1;
            while (i-1 >= e_i) {
                --i;
                if (aa[i] <= a) {
                    ++e;
                    --i;
                }
            }
            while (j+1 <= e_j) {
                ++j;
                if (aa[j] <= a) {
                    ++e;
                    ++j;
                }
            }

            if (e >= K/2) {
                r = m;
                continue;
            }
        }

        l = m;
    }

    writeln(AA[r].a);
}

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

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

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

	bool f(int x)
	{
		auto dp = new int[](n+2);
		auto begin = k % 2 ? 1 : 0;
		foreach (i; begin..n)
		{
			if (a[i] <= x)
			{
				if (dp[i]+1 == k/2) return true;
				dp[i+2].chmax(dp[i]+1);
			}
			dp[i+1].chmax(dp[i]);
		}
		return false;
	}

	auto ans = binarySearch!(f)(10^^9, 0);

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


Initially Ildar has an empty array. He performs $$$n$$$ steps. On each step he takes a subset of integers already added to the array and appends the mex of this subset to the array. The mex of an multiset of integers is the smallest non-negative integer not presented in the multiset. For example, the mex of the multiset $$$[0, 2, 3]$$$ is $$$1$$$, while the mex of the multiset $$$[1, 2, 1]$$$ is $$$0$$$.More formally, on the step $$$m$$$, when Ildar already has an array $$$a_1, a_2, \ldots, a_{m-1}$$$, he chooses some subset of indices $$$1 \leq i_1 < i_2 < \ldots < i_k < m$$$ (possibly, empty), where $$$0 \leq k < m$$$, and appends the $$$mex(a_{i_1}, a_{i_2}, \ldots a_{i_k})$$$ to the end of the array.After performing all the steps Ildar thinks that he might have made a mistake somewhere. He asks you to determine for a given array $$$a_1, a_2, \ldots, a_n$$$ the minimum step $$$t$$$ such that he has definitely made a mistake on at least one of the steps $$$1, 2, \ldots, t$$$, or determine that he could have obtained this array without mistakes.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$) — the number of steps Ildar made. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$) — the array Ildar obtained.

If Ildar could have chosen the subsets on each step in such a way that the resulting array is $$$a_1, a_2, \ldots, a_n$$$, print $$$-1$$$. Otherwise print a single integer $$$t$$$ — the smallest index of a step such that a mistake was made on at least one step among steps $$$1, 2, \ldots, t$$$.

NoteIn the first example it is possible that Ildar made no mistakes. Here is the process he could have followed.  $$$1$$$-st step. The initial array is empty. He can choose an empty subset and obtain $$$0$$$, because the mex of an empty set is $$$0$$$. Appending this value to the end he gets the array $$$[0]$$$.  $$$2$$$-nd step. The current array is $$$[0]$$$. He can choose a subset $$$[0]$$$ and obtain an integer $$$1$$$, because $$$mex(0) = 1$$$. Appending this value to the end he gets the array $$$[0,1]$$$.  $$$3$$$-rd step. The current array is $$$[0,1]$$$. He can choose a subset $$$[0,1]$$$ and obtain an integer $$$2$$$, because $$$mex(0,1) = 2$$$. Appending this value to the end he gets the array $$$[0,1,2]$$$.  $$$4$$$-th step. The current array is $$$[0,1,2]$$$. He can choose a subset $$$[0]$$$ and obtain an integer $$$1$$$, because $$$mex(0) = 1$$$. Appending this value to the end he gets the array $$$[0,1,2,1]$$$. Thus, he can get the array without mistakes, so the answer is $$$-1$$$.In the second example he has definitely made a mistake on the very first step, because he could not have obtained anything different from $$$0$$$.In the third example he could have obtained $$$[0, 1, 2]$$$ without mistakes, but $$$239$$$ is definitely wrong.

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;

immutable int INF = 1 << 29;

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

    foreach (i; 0..N) {
        if (A[i] > m) {
            writeln(i + 1);
            return;
        }
        if (A[i] == m) {
            m += 1;
        }
    }

    writeln(-1);
}

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

int solve (int [] a)
{
	int next = 0;
	foreach (pos, ref cur; a)
	{
		if (cur > next)
		{
			return pos + 1;
		}
		next = max (next, cur + 1);
	}
	return -1;
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		writeln (solve (a));
	}
}

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

int solve (int [] a)
{
	int next = 0;
	foreach (pos, ref cur; a)
	{
		if (cur > next)
		{
			return pos;
		}
		next = max (next, cur + 1);
	}
	return -1;
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		writeln (solve (a));
	}
}


Polycarp was given a row of tiles. Each tile contains one lowercase letter of the Latin alphabet. The entire sequence of tiles forms the string $$$s$$$.In other words, you are given a string $$$s$$$ consisting of lowercase Latin letters.Initially, Polycarp is on the first tile of the row and wants to get to the last tile by jumping on the tiles. Jumping from $$$i$$$-th tile to $$$j$$$-th tile has a cost equal to $$$|index(s_i) - index(s_j)|$$$, where $$$index(c)$$$ is the index of the letter $$$c$$$ in the alphabet (for example, $$$index($$$'a'$$$)=1$$$, $$$index($$$'b'$$$)=2$$$, ..., $$$index($$$'z'$$$)=26$$$) .Polycarp wants to get to the $$$n$$$-th tile for the minimum total cost, but at the same time make maximum number of jumps.In other words, among all possible ways to get to the last tile for the minimum total cost, he will choose the one with the maximum number of jumps.Polycarp can visit each tile at most once.Polycarp asks you to help — print the sequence of indices of string $$$s$$$ on which he should jump.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case is given by the string $$$s$$$ ($$$2 \le |s| \le 2 \cdot 10^5$$$), where $$$|s|$$$ — is the length of string $$$s$$$. The string $$$s$$$ consists of lowercase Latin letters. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

The answer to each test case consists of two lines. In the first line print two integers $$$cost$$$, $$$m$$$, where $$$cost$$$ is the minimum total cost of the path, and $$$m$$$ is the maximum number of visited tiles Polycarp can make to get to $$$n$$$-th tiles for the minimum total cost $$$cost$$$ (i.e. the number of jumps is $$$m-1$$$). In the next line print $$$m$$$ different numbers $$$j_1, j_2, \dots, j_m$$$ ($$$1 \le j_i \le |s|$$$) — the sequence of indices of the tiles Polycarp will jump on. The first number in the sequence must be $$$1$$$ (that is, $$$j_1=1$$$) and the last number must be the value of $$$|s|$$$ (that is, $$$j_m=|s|$$$). If there are multiple answers, print any of them.

6

logic

codeforces

bca

aaaaaaaaaaa

adbaadabad

to

NoteIn the first test case, the required path corresponds to the picture:  In this case, the minimum possible total cost of the path is achieved. Since $$$index($$$'l'$$$)=12$$$, $$$index($$$'o'$$$)=15$$$, $$$index($$$'g'$$$)=7$$$, $$$index($$$'i'$$$)=9$$$, $$$index($$$'c'$$$)=3$$$, then the total cost of the path is $$$|12-9|+|9-7|+|7-3|=3+2+4=9$$$.

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

void solve() {
    char[] S = readln.chomp.to!(char[]);
    bool reversed = false;
    if (S[0] > S[$-1]) {
        S = reverse(S).to!(char[]);
        reversed = true;
    }
    auto ys = iota(0, S.length).array.sort!((a, b) => S[a] == S[b] ? a < b : S[a] < S[b]).array;
    int N = to!int(S.length);
    int s = 0, t = N;
    for (int i = 0; i < S.length; i++) {
        auto y = ys[i];
        if (y == 0) {
            s = i;
        }
        if (y == S.length - 1) {
            t = i;
        }
    }
    int cost = (S[$-1] - S[0]).to!int;
    writefln("%d %d", cost, t - s + 1);
    int[] ans;
    if (reversed) {
        ans = ys[s .. t + 1].map!((i) => N - i).array.reverse.array.to!(int[]);
    } else {
        ans = ys[s .. t + 1].map!"a+1".array.to!(int[]);
    }
    writefln("%(%s %)", ans);
}

void main() {
    int T; readf("%d\n", &T);
    foreach (t; 0 .. T) {
        solve();
    }
}

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

void solve() {
    char[] S = readln.chomp.to!(char[]);
    bool reversed = false;
    if (S[0] > S[$-1]) {
        S = reverse(S).to!(char[]);
        reversed = true;
    }
    auto ys = iota(0, S.length).array.sort!((a, b) => S[a] < S[b]).array;
    int N = to!int(S.length);
    int s = 0, t = N;
    for (int i = 0; i < S.length; i++) {
        auto y = ys[i];
        if (y == 0) {
            s = i;
        }
        if (y == S.length - 1) {
            t = i;
        }
    }
    int cost = (S[$-1] - S[0]).to!int;
    writefln("%d %d", cost, t - s + 1);
    int[] ans;
    if (reversed) {
        ans = ys[s .. t + 1].map!((i) => N - i).array.reverse.array.to!(int[]);
    } else {
        ans = ys[s .. t + 1].map!"a+1".array.to!(int[]);
    }
    writefln("%(%s %)", ans);
}

void main() {
    int T; readf("%d\n", &T);
    foreach (t; 0 .. T) {
        solve();
    }
}


After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points.At any time Andrew can visit the store where tasty buns are sold (you can assume that is doesn't take time to get to the store and back). One such bun costs C roubles and decreases hunger by N points. Since the demand for bakery drops heavily in the evening, there is a special 20% discount for buns starting from 20:00 (note that the cost might become rational). Of course, buns cannot be sold by parts.Determine the minimum amount of money Andrew has to spend in order to feed his cat. The cat is considered fed if its hunger level is less than or equal to zero.

The first line contains two integers hh and mm (00 ≤ hh ≤ 23, 00 ≤ mm ≤ 59) — the time of Andrew's awakening. The second line contains four integers H, D, C and N (1 ≤ H ≤ 105, 1 ≤ D, C, N ≤ 102).

Output the minimum amount of money to within three decimal digits. You answer is considered correct, if its absolute or relative error does not exceed 10 - 4. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .

NoteIn the first sample Andrew can visit the store at exactly 20:00. The cat's hunger will be equal to 315, hence it will be necessary to purchase 315 buns. The discount makes the final answer 25200 roubles.In the second sample it's optimal to visit the store right after he wakes up. Then he'll have to buy 91 bins per 15 roubles each and spend a total of 1365 roubles.

import
		std.math,
		std.conv,
		std.file,
		std.range,
		std.array,
		std.stdio,
		std.string,
		std.bitmanip,
		std.typecons,
		std.algorithm;

void main()
{
	uint hh, mm, h, d, c, n;

	readf!`%d %d %d %d %d %d`(hh, mm, h, d, c, n);

	auto e = ceil(float(h) / n) * c;

	if(hh >= 20)
	{
		writeln(e * 0.8);
	}
	else
	{
		auto v = ceil(float((20 * 60 - hh * 60 - mm) * d + h) / n) * c * 0.8;

		min(e, v).writeln;
	}
}

import core.stdc.stdio;
import core.stdc.stdlib;
import std.algorithm;
void main()
{
	int n,m,a,b,c,d;
	scanf("%d%d",&n,&m);
	scanf("%d%d%d%d",&a,&b,&c,&d);
	if (n>=20)
	{
		printf("%.5lf\n",((a-1)/d+1)*c*0.8);
		exit(0);
	}
	int dis=a+((60-m)+(19-n)*60)*b;
	printf("%.5lf\n",min(((dis-1)/d+1)*c*0.8,((a-1)/d+1)*c*1.0));
}

import
		std.math,
		std.conv,
		std.file,
		std.range,
		std.array,
		std.stdio,
		std.string,
		std.bitmanip,
		std.typecons,
		std.algorithm;

void main()
{
	uint hh, mm, h, d, c, n;

	readf!`%d %d %d %d %d %d`(hh, mm, h, d, c, n);

	auto e = ceil(double(h) / n) * c;

	if(hh >= 20)
	{
		writeln(e * 0.8);
	}
	else
	{
		auto v = ceil(double((20 * 60 - hh * 60 - mm) * d + h) / n * c * 0.8);

		min(e, v).writeln;
	}
}

import
		std.math,
		std.conv,
		std.file,
		std.range,
		std.array,
		std.stdio,
		std.string,
		std.bitmanip,
		std.typecons,
		std.algorithm;

void main()
{
	uint hh, mm, h, d, c, n;

	readf!`%d %d %d %d %d %d`(hh, mm, h, d, c, n);

	auto e = ceil(float(h) / n) * c;

	if(hh >= 20)
	{
		writeln(e * 0.8);
	}
	else
	{
		auto v = ceil(float((20 * 60 - hh * 60 - mm) * d + h) / n * c * 0.8);

		min(e, v).writeln;
	}
}


As you know, majority of students and teachers of Summer Informatics School live in Berland for the most part of the year. Since corruption there is quite widespread, the following story is not uncommon.Elections are coming. You know the number of voters and the number of parties — $$$n$$$ and $$$m$$$ respectively. For each voter you know the party he is going to vote for. However, he can easily change his vote given a certain amount of money. In particular, if you give $$$i$$$-th voter $$$c_i$$$ bytecoins you can ask him to vote for any other party you choose.The United Party of Berland has decided to perform a statistical study — you need to calculate the minimum number of bytecoins the Party needs to spend to ensure its victory. In order for a party to win the elections, it needs to receive strictly more votes than any other party.

The first line of input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 3000$$$) — the number of voters and the number of parties respectively. Each of the following $$$n$$$ lines contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$1 \le p_i \le m$$$, $$$1 \le c_i \le 10^9$$$) — the index of this voter's preferred party and the number of bytecoins needed for him to reconsider his decision. The United Party of Berland has the index $$$1$$$.

Print a single number — the minimum number of bytecoins needed for The United Party of Berland to win the elections.

NoteIn the first sample, The United Party wins the elections even without buying extra votes.In the second sample, The United Party can buy the votes of the first and the fourth voter. This way The Party gets two votes, while parties $$$3$$$, $$$4$$$ and $$$5$$$ get one vote and party number $$$2$$$ gets no votes.In the third sample, The United Party can buy the votes of the first three voters and win, getting three votes against two votes of the fifth party.

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;

immutable long MOD = 10^^9 + 7;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto A = new Tuple!(int, long)[][](M);
    Tuple!(int, long)[] B;
    int cnt = 0;

    foreach (i; 0..N) {
        s = readln.split.map!(to!int);
        auto m = s[0];
        auto c = s[1].to!long;
        if (m == 1) {
            cnt += 1;
        } else {
            A[m-1] ~= tuple(i, c);
            B ~= tuple(i, c);
        }
    }

    foreach (i; 0..M) {
        A[i].sort!"a[1] < b[1]"();
    }
    B.sort!"a[1] < b[1]"();

    auto used = new bool[](N);
    long ans = 1L << 59;

    foreach (x; 0..N-cnt+1) {
        used.fill(false);
        int v = cnt + x;
        if (v == 0) continue;
        long tmp = 0;
        int tmpcnt = cnt;
        foreach (i; 0..M) {
            for (int j = 0; A[i].length.to!int - j >= v; ++j) {
                tmp += A[i][j][1];
                used[A[i][j][0]] = true;
                tmpcnt += 1;
            }
        }
        for (int i = 0; i < B.length.to!int && tmpcnt < v; ++i) {
            if (used[B[i][0]]) continue;
            tmp += B[i][1];
            tmpcnt += 1;
        }
        if (tmpcnt >= v)
            ans = min(ans, tmp);
    }

    ans.writeln;
}

import std.algorithm;
import std.conv;
import std.stdio;

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto v = new int [] [m];
		foreach (i; 0..n)
		{
			int p, c;
			readf (" %s %s", &p, &c);
			p -= 1;
			v[p] ~= c;
		}

		foreach (j; 0..m)
		{
			sort !(q{a > b}) (v[j]);
		}

		long res = long.max;
		auto w = new int [n];
		for (int limit = 0; limit <= n; limit++)
		{
			long cur = 0;
			int votes = v[0].length.to !(int);
			int t = 0;
			foreach (j; 1..m)
			{
				foreach (k, c; v[j])
				{
					if (k < limit)
					{
						w[t] = c;
						t += 1;
					}
					else
					{
						cur += c;
						votes += 1;
					}
				}
			}

			sort (w[0..t]);
			int p = 0;
			while (votes <= limit && p < t)
			{
				cur += w[p];
				p += 1;
				votes += 1;
			}

			debug {writeln (limit, " ", votes, " ", cur);}
			if (votes > limit)
			{
				res = min (res, cur);
			}
		}

		writeln (res);
	}
}

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();
      const M = readInt();
      auto P = new int[N];
      auto C = new long[N];
      foreach (i; 0 .. N) {
        P[i] = readInt() - 1;
        C[i] = readLong();
      }

      auto css = new long[][M];
      foreach (i; 0 .. N) {
        css[P[i]] ~= C[i];
      }
      foreach (j; 0 .. M) {
        css[j].sort;
      }

      long ans = INF;
      foreach (k; 1 .. N + 1) {
        long cost;
        long[] cs;
        foreach (j; 1 .. M) {
          const len = cast(int)(css[j].length);
          const bribe = max(len - (k - 1), 0);
          foreach (x; 0 .. bribe) {
            cost += css[j][x];
          }
          foreach (x; bribe .. len) {
            cs ~= css[j][x];
          }
        }
        cs.sort;
        {
          const len = cast(int)(cs.length);
          const bribe = max(len - (N - k), 0);
          debug {
            writeln("  ", k, ": ", cs, " ", bribe);
          }
          foreach (x; 0 .. bribe) {
            cost += cs[x];
          }
        }
        debug {
          writeln(k, ": ", cost);
        }
        chmin(ans, cost);
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

    int partyvotes = 0;
    int[][int] votes;
    foreach (_; 0 .. n) {
        int p, c;
        readf("%s %s", &p, &c);
        readln;

        if (p == 1) partyvotes += 1;
        else votes[p] ~= c;
    }

    foreach (k, ref v; votes) sort(v);

    debug { votes.writeln; }

    auto ans = 3000L * 10 ^^ 9;
    foreach (x; partyvotes .. n+1) {
        auto curvotes = partyvotes;
        auto cursum = 0L;
        int[] cheap;
        foreach (k, v; votes) {
            auto need = max(0, cast(int)v.length - x + 1);

            debug { writeln(k, ' ', v, ' ', v.length, ' ', need); }

            curvotes += need;
            cursum += v.take(need).sum(0L);
            cheap ~= v.drop(need);
        }
        auto need = max(0, x - curvotes);
        curvotes = x;
        sort(cheap);
        cursum += cheap.take(need).sum(0L);

        debug { writeln(x, ' ', cursum); }

        ans = min(ans, cursum);
    }

    ans.writeln;
}

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;

immutable long MOD = 10^^9 + 7;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto A = new Tuple!(int, long)[][](M);
    auto B = new Tuple!(int, long)[](N);
    int cnt = 0;

    foreach (i; 0..N) {
        s = readln.split.map!(to!int);
        auto m = s[0];
        auto c = s[1].to!long;
        if (m == 1) {
            cnt += 1;
        } else {
            A[m-1] ~= tuple(i, c);
            B[i] = tuple(i, c);
        }
    }

    foreach (i; 0..M) {
        A[i].sort!"a[1] < b[1]"();
    }
    B.sort!"a[1] < b[1]"();
    auto used = new bool[](N);
    long ans = 1L << 59;

    foreach (x; 0..N-cnt+1) {
        int v = cnt + x;
        if (v == 0) continue;
        long tmp = 0;
        int tmpcnt = cnt;
        foreach (i; 0..M) {
            for (int j = 0; A[i].length.to!int - j >= v; ++j) {
                tmp += A[i][j][1];
                used[A[i][j][0]] = true;
                tmpcnt += 1;
            }
        }
        for (int i = 0; i < B.length.to!int && tmpcnt < v; ++i) {
            if (used[B[i][0]]) continue;
            tmp += B[i][1];
            tmpcnt += 1;
        }
        ans = min(ans, tmp);
        used.fill(false);
    }

    ans.writeln;
}

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();
      const M = readInt();
      auto P = new int[N];
      auto C = new long[N];
      foreach (i; 0 .. N) {
        P[i] = readInt() - 1;
        C[i] = readLong();
      }

      auto css = new long[][M];
      foreach (i; 0 .. N) {
        css[P[i]] ~= C[i];
      }
      foreach (j; 0 .. M) {
        css[j].sort;
      }

      long ans = INF;
      foreach (k; 1 .. N + 1) {
        long cost;
        long[] cs;
        foreach (j; 1 .. M) {
          const len = cast(int)(css[j].length);
          const bribe = max(len - (k - 1), 0);
          foreach (x; 0 .. bribe) {
            cost += css[j][x];
          }
          foreach (x; bribe .. len) {
            cs ~= css[j][x];
          }
        }
        {
          const len = cast(int)(cs.length);
          const bribe = max(len - (N - k), 0);
          foreach (x; 0 .. bribe) {
            cost += cs[x];
          }
        }
        debug {
          writeln(k, ": ", cost);
        }
        chmin(ans, cost);
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

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

    int partyvotes = 0;
    int[][int] votes;
    foreach (_; 0 .. n) {
        int p, c;
        readf("%s %s", &p, &c);
        readln;

        if (p == 1) partyvotes += 1;
        else votes[p] ~= c;
    }

    foreach (k, ref v; votes) sort(v);

    debug { votes.writeln; }

    auto ans = 3000L * 10 ^^ 9;
    foreach (x; partyvotes .. n+1) {
        auto curvotes = partyvotes;
        auto cursum = 0;
        int[] cheap;
        foreach (k, v; votes) {
            auto need = max(0, cast(int)v.length - x + 1);

            debug { writeln(k, ' ', v, ' ', v.length, ' ', need); }

            curvotes += need;
            cursum += v.take(need).sum(0L);
            cheap ~= v.drop(need);
        }
        auto need = max(0, x - curvotes);
        curvotes = x;
        sort(cheap);
        cursum += cheap.take(need).sum(0L);

        debug { writeln(x, ' ', cursum); }

        ans = min(ans, cursum);
    }

    ans.writeln;
}