Vasily has a deck of cards consisting of n cards. There is an integer on each of the cards, this integer is between 1 and 100 000, inclusive. It is possible that some cards have the same integers on them.Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on it equals the minimum number written on the cards in the deck, then he places the card away. Otherwise, he puts it under the deck and takes the next card from the top, and so on. The process ends as soon as there are no cards in the deck. You can assume that Vasily always knows the minimum number written on some card in the remaining deck, but doesn't know where this card (or these cards) is.You are to determine the total number of times Vasily takes the top card from the deck.

The first line contains single integer n (1 ≤ n ≤ 100 000) — the number of cards in the deck. The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000), where ai is the number written on the i-th from top card in the deck.

Print the total number of times Vasily takes the top card from the deck.

NoteIn the first example Vasily at first looks at the card with number 6 on it, puts it under the deck, then on the card with number 3, puts it under the deck, and then on the card with number 1. He places away the card with 1, because the number written on it is the minimum among the remaining cards. After that the cards from top to bottom are [2, 6, 3]. Then Vasily looks at the top card with number 2 and puts it away. After that the cards from top to bottom are [6, 3]. Then Vasily looks at card 6, puts it under the deck, then at card 3 and puts it away. Then there is only one card with number 6 on it, and Vasily looks at it and puts it away. Thus, in total Vasily looks at 7 cards.

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!int).array;
    auto B = new int[][](100010);

    if (N == 1) {
        writeln(1);
        return;
    }

    foreach (i, a; A.enumerate) {
        B[a] ~= i.to!int;
    }

    auto C = A.dup;
    C.sort();
    C = C.uniq().array;

    int p = -1;
    long ans = 0;
    auto st = new SegmentTree(100010);

    foreach (c; C) {
        int M = B[c].length.to!int;
        int q = B[c].assumeSorted.lowerBound(p).length.to!int;
        if (q == M) q = 0;
        foreach (i; 0..M) {
            if (B[c][(q+i)%M] >= p) {
                ans += B[c][(q+i)%M] - p;
                ans -= st.sum(p + 1, B[c][(q+i)%M]);
            } else {
                ans += B[c][(q+i)%M] - p + N;
                ans -= st.sum(p + 1, 100010) + st.sum(0, B[c][(q+i)%M]-1);
            }
            p = B[c][(q+i)%M];
            st.add(p, 1);
        }
    }

    ans.writeln;
}

class SegmentTree {
    int[] table;
    int size;

    this(int n) {
        assert(bsr(n) < 29);
        size = 1 << (bsr(n) + 2);
        table = new int[](size);
    }

    void add(int pos, int num) {
        return add(pos, num, 0, 0, size/2-1);
    }

    void add(int pos, int num, int i, int left, int right) {
        table[i] += num;
        if (left == right)
            return;
        auto mid = (left + right) / 2;
        if (pos <= mid)
            add(pos, num, i*2+1, left, mid);
        else
            add(pos, num, i*2+2, mid+1, right);
    }

    int sum(int pl, int pr) {
        if (pl > pr) return 0;
        return sum(pl, pr, 0, 0, size/2-1);
    }

    int sum(int pl, int pr, int i, int left, int right) {
        if (pl > right || pr < left)
            return 0;
        else if (pl <= left && right <= pr)
            return table[i];
        else
            return
                sum(pl, pr, i*2+1, left, (left+right)/2) +
                sum(pl, pr, i*2+2, (left+right)/2+1, right);
    }
}

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

immutable int MX = 10 ^^ 5 + 100;

struct fw {
    int n;
    int[] arr;

    this (int n) {
        this.n = n;
        arr = new int[n+1];
    }

    void add(int p, int x) {
        while (p <= n) {
            arr[p] += x;
            p += (p & (-p));
        }
    }

    int sm(int p) {
        int ret = 0;
        while (p > 0) {
            ret += arr[p];
            p -= (p & (-p));
        }

        return ret;
    }

    int sm(int le, int r) {
        return sm(r) - sm(le);
    }

    int dist(int fr, int to) {
        if (fr < to) { return sm(fr, to); }

        return sm(fr, n) + sm(0, to);
    }
}

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

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

    DList!int[int] d;

    foreach (e; arr.dup.sort.uniq) { d[e] = DList!int(); }
    foreach (i, e; arr) { d[e] ~= (i.to!int + 1); }

    debug { d.writeln; }

    auto f = new fw(n);
    foreach (i; 1 .. MX) { f.add(i, 1); }

    long ans = 0;
    int pos = 0;
    foreach (k; d.keys.sort) {
        auto lst = d[k];

        while (f.dist(pos, lst.back) < f.dist(pos, lst.front)) {
            lst.insertFront(lst.back);
            lst.removeBack();
        }

        debug { write(k, ": "); lst.each!write; writeln; }

        foreach (e; lst) {
            ans += f.dist(pos, e);

            f.add(e, -1);
            pos = e;
        }
    }

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

void bAdd(T)(T[] bit, int pos, T val)
in {
  assert(0 <= pos && pos < bit.length, "bAdd: 0 <= pos < |bit| must hold");
}
do {
  for (int x = pos; x < bit.length; x |= x + 1) {
    bit[x] += val;
  }
}

// sum of [0, pos)
T bSum(T)(T[] bit, int pos)
in {
  assert(0 <= pos && pos <= bit.length, "bSum: 0 <= pos <= |bit| must hold");
}
do {
  T ret = 0;
  for (int x = pos - 1; x >= 0; x = (x & (x + 1)) - 1) {
    ret += bit[x];
  }
  return ret;
}

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

      const lim = A.maxElement + 1;
      auto poss = new RedBlackTree!int[lim];
      foreach (a; 0 .. lim) {
        poss[a] = new RedBlackTree!int;
      }
      foreach (i; 0 .. N) {
        poss[A[i]].insert(i);
      }

      auto bit = new int[N];
      foreach (i; 0 .. N) {
        bit.bAdd(i, +1);
      }

      long ans;
      int cur;
      foreach (a; 0 .. lim) {
        for (; !poss[a].empty; ) {
          auto ran = poss[a].upperBound(cur - 1);
          if (ran.empty) {
            ans += bit.bSum(N) - bit.bSum(cur);
            cur = 0;
            ran = poss[a][];
          }
          const i = ran.front;
          poss[a].removeKey(i);
          ans += bit.bSum(i) - bit.bSum(cur);
          ans += 1;
          bit.bAdd(i, -1);
          cur = i;
          debug {
            writeln("cur = ", cur, ", ans = ", ans);
          }
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!int).array;
    auto B = new int[][](100010);

    if (N == 1) {
        writeln(1);
        return;
    }

    foreach (i, a; A.enumerate) {
        B[a] ~= i.to!int;
    }

    auto C = A.dup;
    C.sort();
    C = C.uniq().array;

    int p = -1;
    long ans = 0;
    auto st = new SegmentTree(100010);

    foreach (c; C) {
        int M = B[c].length.to!int;
        int q = B[c].assumeSorted.lowerBound(p + 1).length.to!int;
        if (q == M) q = 0;
        foreach (i; 0..M) {
            if (B[c][(q+i)%M] >= p) {
                ans += B[c][(q+i)%M] - p;
                ans -= st.sum(B[c][(q+i)%M], p-1);
            } else {
                ans += B[c][(q+i)%M] - p + N;
                ans -= st.sum(p + 1, 100010) + st.sum(0, B[c][(q+i)%M]-1);
            }
            p = B[c][(q+i)%M];
            st.add(p, 1);
        }
    }

    ans.writeln;
}

class SegmentTree {
    int[] table;
    int size;

    this(int n) {
        assert(bsr(n) < 29);
        size = 1 << (bsr(n) + 2);
        table = new int[](size);
    }

    void add(int pos, int num) {
        return add(pos, num, 0, 0, size/2-1);
    }

    void add(int pos, int num, int i, int left, int right) {
        table[i] += num;
        if (left == right)
            return;
        auto mid = (left + right) / 2;
        if (pos <= mid)
            add(pos, num, i*2+1, left, mid);
        else
            add(pos, num, i*2+2, mid+1, right);
    }

    int sum(int pl, int pr) {
        if (pl > pr) return 0;
        return sum(pl, pr, 0, 0, size/2-1);
    }

    int sum(int pl, int pr, int i, int left, int right) {
        if (pl > right || pr < left)
            return 0;
        else if (pl <= left && right <= pr)
            return table[i];
        else
            return
                sum(pl, pr, i*2+1, left, (left+right)/2) +
                sum(pl, pr, i*2+2, (left+right)/2+1, right);
    }
}

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

immutable int MX = 10 ^^ 5 + 100;

struct fw {
    int[] arr = new int[MX];

    void add(int p) {
        while (p < MX) {
            arr[p] += 1;
            p += (p & (-p));
        }
    }

    int sm(int p) {
        int ret = 0;
        while (p > 0) {
            ret += arr[p];
            p -= (p & (-p));
        }

        return ret;
    }

    int sm(int le, int r) {
        return sm(r) - sm(le);
    }
}

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

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

    DList!int[int] d;

    foreach (e; arr.dup.sort.uniq) {
        d[e] = DList!int();
    }

    foreach (i, e; arr) {
        d[e] ~= (i.to!int + 1);
    }

    debug { d.writeln; }

    bool isCloser(int curPos, int pos1, int pos2) {
        return curPos < pos1 || curPos > pos2;
    }

    auto f = new fw();

    long ans = 0;
    int pos = 0;
    foreach (k; d.keys.sort) {
        auto lst = d[k];
        while (!lst.front == lst.back && isCloser(pos, lst.back, lst.front)) {
            lst.insertFront(lst.back);
            lst.removeBack();
        }

        debug { write(k, ": "); lst.each!write; writeln; }

        int getCards(int le, int r) { return r - le - f.sm(le, r); }

        foreach (e; lst) {
            if (pos < e) {
                ans += getCards(pos, e);
            } else {
                ans += getCards(pos, n) + getCards(0, e);
            }

            f.add(e);
            pos = e;
        }
    }

    ans.writeln;
}

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

immutable int MX = 10 ^^ 5 + 100;

struct fw {
    int[] arr = new int[MX];

    void add(int p, int x) {
        while (p < MX) {
            arr[p] += x;
            p += (p & (-p));
        }
    }

    int sm(int p) {
        int ret = 0;
        while (p > 0) {
            ret += arr[p];
            p -= (p & (-p));
        }

        return ret;
    }

    int sm(int le, int r) {
        return sm(r) - sm(le);
    }
}

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

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

    DList!int[int] d;

    foreach (e; arr.dup.sort.uniq) {
        d[e] = DList!int();
    }

    foreach (i, e; arr) {
        d[e] ~= (i.to!int + 1);
    }

    debug { d.writeln; }

    bool isCloser(int curPos, int pos1, int pos2) {
        return curPos < pos1 || curPos > pos2;
    }

    auto f = new fw();
    foreach (i; 1 .. MX) f.add(i, 1);

    long ans = 0;
    int pos = 0;
    foreach (k; d.keys.sort) {
        auto lst = d[k];
        while (!lst.front == lst.back && isCloser(pos, lst.back, lst.front)) {
            lst.insertFront(lst.back);
            lst.removeBack();
        }

        debug { write(k, ": "); lst.each!write; writeln; }

        foreach (e; lst) {
            if (pos < e) {
                ans += f.sm(pos, e);
            } else {
                ans += f.sm(pos, n) + f.sm(0, e);
            }

            f.add(e, -1);
            pos = e;
        }
    }

    ans.writeln;
}

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

immutable int MX = 10 ^^ 5 + 100;

struct fw {
    int[] arr = new int[MX];

    void add(int p) {
        while (p < MX) {
            arr[p] += 1;
            p += (p & (-p));
        }
    }

    int sm(int p) {
        int ret = 0;
        while (p > 0) {
            ret += arr[p];
            p -= (p & (-p));
        }

        return ret;
    }

    int sm(int le, int r) {
        return sm(r) - sm(le);
    }
}

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

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

    DList!int[int] d;

    foreach (e; arr.sort.uniq) {
        d[e] = DList!int();
    }

    foreach (i, e; arr) {
        d[e] ~= (i.to!int + 1);
    }

    debug { d.writeln; }

    bool isCloser(int curPos, int pos1, int pos2) {
        return curPos < pos1 || curPos > pos2;
    }

    auto f = new fw();

    long ans = 0;
    int pos = 0;
    foreach (k; d.keys) {
        auto lst = d[k];
        while (!lst.front == lst.back && isCloser(pos, lst.back, lst.front)) {
            lst.insertFront(lst.back);
            lst.removeBack();
        }

        debug { lst.each!write; writeln; }

        foreach (e; lst) {
            if (pos < e) {
                ans += e - pos - f.sm(pos, e);
            } else {
                ans += n - pos - f.sm(pos, n) + e - f.sm(e);
            }

            f.add(e);
            pos = e;
        }
    }

    ans.writeln;
}

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

struct fw {
    int mx;
    int[] arr;

    this(int mx) {
        this.mx = mx;
        arr = new int[] (mx+1);
    }

    void add(int p) {
        while (p <= mx) {
            arr[p] += 1;
            p += (p & (-p));
        }
    }import core.bitop, std.bitmanip;
import core.checkedint;
import std.algorithm, std.functional;
import std.array, std.container;
import std.bigint;
import std.conv;
import std.datetime.stopwatch;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

struct fw {
    int mx;
    int[] arr;

    this(int mx) {
        this.mx = mx;
        arr = new int[] (mx+1);
    }

    void add(int p) {
        while (p <= mx) {
            arr[p] += 1;
            p += (p & (-p));
        }
    }

    int sm(int p) {
        int ret = 0;
        while (p > 0) {
            ret += arr[p];
            p -= (p & (-p));
        }

        return ret;
    }

    int sm(int p1, int p2) {
        return sm(p2) - sm(p1);
    }
};

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

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

    Tuple!(int, int)[] arr2;
    int[int] cnt;
    foreach (ref e; arr) {
        arr2 ~= tuple(e, cnt.get(e, 0));
        cnt[e] += 1;
    }

    auto idx = new int[n];
    makeIndex!("a < b")(arr2, idx);

    idx = idx.map!(x => x+1).array;

    debug { idx.writeln; }

    auto f = new fw(n);

    long ans = 0;
    int lst = 0;
    foreach (e; idx) {
        if (e > lst) { ans += e - lst - f.sm(lst, e); }
        else {
            ans += n - lst - f.sm(lst, n) + e - f.sm(e);
        }

        debug { ans.writeln; }

        f.add(e);
        lst = e;
    }

    ans.writeln;
}

    int sm(int p) {
        int ret = 0;
        while (p > 0) {
            ret += arr[p];
            p -= (p & (-p));
        }

        return ret;
    }

    int sm(int p1, int p2) {
        return sm(p2) - sm(p1);
    }
};

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

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

    Tuple!(int, int)[] arr2;
    int[int] cnt;
    foreach (ref e; arr) {
        arr2 ~= tuple(e, cnt.get(e, 0));
        cnt[e] += 1;
    }

    auto idx = new int[n];
    makeIndex!("a < b")(arr2, idx);

    idx = idx.map!(x => x+1).array;

    debug { idx.writeln; }

    auto f = new fw(n);

    int ans = 0;
    int lst = 0;
    foreach (e; idx) {
        if (e > lst) { ans += e - lst - f.sm(lst, e); }
        else {
            ans += n - lst - f.sm(lst, n) + e - f.sm(e);
        }

        debug { ans.writeln; }

        f.add(e);
        lst = e;
    }

    ans.writeln;
}

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

immutable int MX = 10 ^^ 5 + 100;

struct fw {
    int n;
    int[] arr;

    this (int n) {
        this.n = n;
        arr = new int[n+1];
    }

    void add(int p, int x) {
        while (p <= n) {
            arr[p] += x;
            p += (p & (-p));
        }
    }

    int sm(int p) {
        int ret = 0;
        while (p > 0) {
            ret += arr[p];
            p -= (p & (-p));
        }

        return ret;
    }

    int sm(int le, int r) {
        return sm(r) - sm(le);
    }

    int dist(int le, int r) {
        if (le < r) { return sm(le, r); }

        return sm(r, n) + sm(0, le);
    }
}

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

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

    DList!int[int] d;

    foreach (e; arr.dup.sort.uniq) { d[e] = DList!int(); }

    foreach (i, e; arr) { d[e] ~= (i.to!int + 1); }

    debug { d.writeln; }

    auto f = new fw(n);
    foreach (i; 1 .. MX) f.add(i, 1);

    long ans = 0;
    int pos = 0;
    foreach (k; d.keys.sort) {
        auto lst = d[k];
        while (!lst.front == lst.back && f.dist(pos, lst.back) < f.dist(pos, lst.front)) {
            lst.insertFront(lst.back);
            lst.removeBack();
        }

        debug { write(k, ": "); lst.each!write; writeln; }

        foreach (e; lst) {
            ans += f.dist(pos, e);

            f.add(e, -1);
            pos = e;
        }
    }

    ans.writeln;
}

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

immutable int MX = 10 ^^ 5 + 100;

struct fw {
    int n;
    int[] arr;

    this (int n) {
        this.n = n;
        arr = new int[n+1];
    }

    void add(int p, int x) {
        while (p <= n) {
            arr[p] += x;
            p += (p & (-p));
        }
    }

    int sm(int p) {
        int ret = 0;
        while (p > 0) {
            ret += arr[p];
            p -= (p & (-p));
        }

        return ret;
    }

    int sm(int le, int r) {
        return sm(r) - sm(le);
    }

    int dist(int le, int r) {
        if (le < r) { return sm(le, r); }

        return sm(r, n) + sm(0, le);
    }
}

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

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

    DList!int[int] d;

    foreach (e; arr.dup.sort.uniq) { d[e] = DList!int(); }

    foreach (i, e; arr) { d[e] ~= (i.to!int + 1); }

    debug { d.writeln; }

    auto f = new fw(n);
    foreach (i; 1 .. MX) f.add(i, 1);

    long ans = 0;
    int pos = 0;
    foreach (k; d.keys.sort) {
        auto lst = d[k];
        while (f.dist(pos, lst.back) < f.dist(pos, lst.front)) {
            lst.insertFront(lst.back);
            lst.removeBack();
        }

        debug { write(k, ": "); lst.each!write; writeln; }

        foreach (e; lst) {
            ans += f.dist(pos, e);

            f.add(e, -1);
            pos = e;
        }
    }

    ans.writeln;
}


Everything is great about Ilya's city, except the roads. The thing is, the only ZooVille road is represented as n holes in a row. We will consider the holes numbered from 1 to n, from left to right.Ilya is really keep on helping his city. So, he wants to fix at least k holes (perharps he can fix more) on a single ZooVille road. The city has m building companies, the i-th company needs ci money units to fix a road segment containing holes with numbers of at least li and at most ri. The companies in ZooVille are very greedy, so, if they fix a segment containing some already fixed holes, they do not decrease the price for fixing the segment. Determine the minimum money Ilya will need to fix at least k holes.

The first line contains three integers n, m, k (1 ≤ n ≤ 300, 1 ≤ m ≤ 105, 1 ≤ k ≤ n). The next m lines contain the companies' description. The i-th line contains three integers li, ri, ci (1 ≤ li ≤ ri ≤ n, 1 ≤ ci ≤ 109).

Print a single integer — the minimum money Ilya needs to fix at least k holes.  If it is impossible to fix at least k holes, print -1. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

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

immutable long INF = long.max / 1024;

void main ()
{
	int n, m, k;
	while (readf (" %s %s %s", &n, &m, &k) > 0)
	{
		auto c = new long [] [] (n, n);
		foreach (i; 0..n)
		{
			foreach (j; 0..n)
			{
				c[i][j] = INF;
			}
		}
		foreach (i; 0..m)
		{
			int l, r, w;
			readf (" %s %s %s", &l, &r, &w);
			l--;
			r--;
			c[l][r] = min (c[l][r], w);
		}

		for (int l = n; l >= 1; l--)
		{
			foreach (i; 0..n - l)
			{
				int j = i + l;
				c[i][j - 1] = min (c[i][j - 1], c[i][j]);
				c[i + 1][j] = min (c[i + 1][j], c[i][j]);
			}
		}
		debug {writefln ("%(%(%s %)\n%)", c);}

		auto f = new long [] [] (n + 1, 2 * n + 1);
		foreach (i; 0..n + 1)
		{
			foreach (j; 0..2 * n + 1)
			{
				f[i][j] = INF;
			}
		}
		f[0][0] = 0;

		foreach (i; 0..n)
		{
			foreach (p; 0..n + 1)
			{
				f[i + 1][p] = min (f[i + 1][p], f[i][p]);
				foreach (j; i..n)
				{
					int q = p + j - i + 1;
					long cur = f[i][p] + c[i][j];
					f[j + 1][q] = min (f[j + 1][q], cur);
				}
			}
		}

		long res = INF;
		foreach (i; 0..n + 1)
		{
			foreach (p; k..n + 1)
			{
				res = min (res, f[i][p]);
			}
		}
		if (res == INF)
		{
			res = -1;
		}
		writeln (res);
	}
}


Danny, the local Math Maniac, is fascinated by circles, Omkar's most recent creation. Help him solve this circle problem!You are given $$$n$$$ nonnegative integers $$$a_1, a_2, \dots, a_n$$$ arranged in a circle, where $$$n$$$ must be odd (ie. $$$n-1$$$ is divisible by $$$2$$$). Formally, for all $$$i$$$ such that $$$2 \leq i \leq n$$$, the elements $$$a_{i - 1}$$$ and $$$a_i$$$ are considered to be adjacent, and $$$a_n$$$ and $$$a_1$$$ are also considered to be adjacent. In one operation, you pick a number on the circle, replace it with the sum of the two elements adjacent to it, and then delete the two adjacent elements from the circle. This is repeated until only one number remains in the circle, which we call the circular value.Help Danny find the maximum possible circular value after some sequences of operations.

The first line contains one odd integer $$$n$$$ ($$$1 \leq n < 2 \cdot 10^5$$$, $$$n$$$ is odd)  — the initial size of the circle. The second line contains $$$n$$$ integers $$$a_{1},a_{2},\dots,a_{n}$$$ ($$$0 \leq a_{i} \leq 10^9$$$)  — the initial numbers in the circle.

Output the maximum possible circular value after applying some sequence of operations to the given circle.

NoteFor the first test case, here's how a circular value of $$$17$$$ is obtained:Pick the number at index $$$3$$$. The sum of adjacent elements equals $$$17$$$. Delete $$$7$$$ and $$$10$$$ from the circle and replace $$$2$$$ with $$$17$$$.Note that the answer may not fit in a $$$32$$$-bit integer.

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

void main ()
{
	auto n = readln.strip.to !(int);
	auto a = readln.splitter.map !(to !(int)).array;

	int [] b;
	for (int i = 0; i < n; i++)
	{
		b ~= a[(i * 2) % n];
	}
	b ~= b;
	debug {writeln (b);}

	long [] s = [0L];
	foreach (c; b)
	{
		s ~= s.back + c;
	}
	debug {writeln (s);}

	int half = n / 2 + 1;
	long res = 0;
	foreach (i; half..s.length)
	{
		res = max (res, s[i] - s[i - half]);
	}
	writeln (res);
}

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

string FMT_F = "%.10f";

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

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

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

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

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

	long best = long.max;
	long cnt;
	foreach (i; 0..n/2)
	{
		cnt += a[i*2];
	}
	best.chmin(cnt);
	foreach (i; 1..n/2+1)
	{
		auto l = ((i-1)*2) % n;
		auto r = (l+(n/2*2)) % n;
		cnt += a[r] - a[l];
		best.chmin(cnt);
		debug writeln("l:", l, " r:", r, " cnt:", cnt);
	}

	cnt = 0;
	foreach (i; 0..n/2)
	{
		cnt += a[i*2+1];
	}
	best.chmin(cnt);
	foreach (i; 1..n/2)
	{
		auto l = ((i-1)*2+1) % n;
		auto r = (l+(n/2*2)) % n;
		cnt += a[r] - a[l];
		best.chmin(cnt);
		debug writeln("l:", l, " r:", r, " cnt:", cnt);
	}

	long ans;
	foreach (e; a)
		ans += e;
	ans -= best;

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

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

void main ()
{
	auto n = readln.strip.to !(int);
	auto a = readln.splitter.map !(to !(int)).array;
	long cur = 0;
	long res = 0;
	auto b = a.cycle;
	foreach (i; 0..n * 2)
	{
		cur += b.front;
		b.popFront ();
		b.popFront ();
		if (i > n / 2)
		{
			cur -= b[n];
		}
		res = max (res, cur);
//		writeln (cur);
	}
	writeln (res);
}

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

string FMT_F = "%.10f";

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

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

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

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

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

	long best = long.max;
	long cnt;
	foreach (i; 0..n/2)
	{
		cnt += a[i*2];
	}
	best.chmin(cnt);
	foreach (i; 1..n/2+1)
	{
		auto l = ((i-1)*2) % n;
		auto r = (i*2+n/2-1) % n;
		cnt += a[r] - a[l];
		best.chmin(cnt);
		debug writeln("l:", l, " r:", r, " cnt:", cnt);
	}

	cnt = 0;
	foreach (i; 0..n/2)
	{
		cnt += a[i*2+1];
	}
	best.chmin(cnt);
	foreach (i; 1..n/2+1)
	{
		auto l = ((i-1)*2+1) % n;
		auto r = (i*2+n/2) % n;
		cnt += a[r] - a[l];
		best.chmin(cnt);
		debug writeln("l:", l, " r:", r, " cnt:", cnt);
	}

	long ans;
	foreach (e; a)
		ans += e;
	ans -= best;

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

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

string FMT_F = "%.10f";

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

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

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

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

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

	long best = long.max;
	foreach (i; 0..4)
	{
		foreach (dir; [-2, 2])
		{
			long cnt;
			int pos = i % n;
			foreach (j; 0..n/2)
			{
				cnt += a[pos];
				pos += dir;
				pos = (pos + n) % n;
			}
			best.chmin(cnt);
		}
	}

	auto ans = a.sum - best;

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

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

string FMT_F = "%.10f";

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

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

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

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

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

	long best = long.max;
	long cnt;
	foreach (i; 0..n/2)
	{
		cnt += a[i*2];
	}
	best.chmin(cnt);
	foreach (i; 1..n/2+1)
	{
		auto l = ((i-1)*2) % n;
		auto r = (i*2+n/2-1) % n;
		cnt += a[r] - a[l];
		best.chmin(cnt);
	}

	cnt = 0;
	foreach (i; 0..n/2)
	{
		cnt += a[i*2+1];
	}
	best.chmin(cnt);
	foreach (i; 1..n/2+1)
	{
		auto l = ((i-1)*2+1) % n;
		auto r = (i*2+n/2) % n;
		cnt += a[r] - a[l];
		best.chmin(cnt);
	}

	auto ans = a.sum - best;

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


Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home.In the city in which Alice and Bob live, the first metro line is being built. This metro line contains $$$n$$$ stations numbered from $$$1$$$ to $$$n$$$. Bob lives near the station with number $$$1$$$, while Alice lives near the station with number $$$s$$$. The metro line has two tracks. Trains on the first track go from the station $$$1$$$ to the station $$$n$$$ and trains on the second track go in reverse direction. Just after the train arrives to the end of its track, it goes to the depot immediately, so it is impossible to travel on it after that.Some stations are not yet open at all and some are only partially open — for each station and for each track it is known whether the station is closed for that track or not. If a station is closed for some track, all trains going in this track's direction pass the station without stopping on it.When the Bob got the information on opened and closed stations, he found that traveling by metro may be unexpectedly complicated. Help Bob determine whether he can travel to the Alice's home by metro or he should search for some other transport.

The first line contains two integers $$$n$$$ and $$$s$$$ ($$$2 \le s \le n \le 1000$$$) — the number of stations in the metro and the number of the station where Alice's home is located. Bob lives at station $$$1$$$. Next lines describe information about closed and open stations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$). If $$$a_i = 1$$$, then the $$$i$$$-th station is open on the first track (that is, in the direction of increasing station numbers). Otherwise the station is closed on the first track. The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$b_i = 0$$$ or $$$b_i = 1$$$). If $$$b_i = 1$$$, then the $$$i$$$-th station is open on the second track (that is, in the direction of decreasing station numbers). Otherwise the station is closed on the second track.

Print "YES" (quotes for clarity) if Bob will be able to commute to the Alice's home by metro and "NO" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower).

NoteIn the first example, all stations are opened, so Bob can simply travel to the station with number $$$3$$$.In the second example, Bob should travel to the station $$$5$$$ first, switch to the second track and travel to the station $$$4$$$ then.In the third example, Bob simply can't enter the train going in the direction of Alice's home.

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

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

		auto c = new bool [n];
		foreach (i; 0..n)
		{
			c[i] = a[0] && a[i];
		}

		bool can = false;
		auto d = new bool [n];
		foreach_reverse (j; 0..n)
		{
			can |= c[j] && b[j];
			d[j] = can && b[j];
		}

		writeln (c[s] || d[s] ? "YES" : "NO");
	}
}

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

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

		auto c = new bool [n];
		foreach (i; 0..n)
		{
			c[i] = a[0] && a[i];
		}

		bool can = false;
		auto d = new bool [n];
		foreach_reverse (j; 0..n)
		{
			can |= c[j];
			d[j] = can && b[j];
		}

		writeln (c[s] || d[s] ? "YES" : "NO");
	}
}


Polycarp likes to play with numbers. He takes some integer number $$$x$$$, writes it down on the board, and then performs with it $$$n - 1$$$ operations of the two kinds:   divide the number $$$x$$$ by $$$3$$$ ($$$x$$$ must be divisible by $$$3$$$);  multiply the number $$$x$$$ by $$$2$$$. After each operation, Polycarp writes down the result on the board and replaces $$$x$$$ by the result. So there will be $$$n$$$ numbers on the board after all.You are given a sequence of length $$$n$$$ — the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board.Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number.It is guaranteed that the answer exists.

The first line of the input contatins an integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the number of the elements in the sequence. The second line of the input contains $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 3 \cdot 10^{18}$$$) — rearranged (reordered) sequence that Polycarp can wrote down on the board.

Print $$$n$$$ integer numbers — rearranged (reordered) input sequence that can be the sequence that Polycarp could write down on the board. It is guaranteed that the answer exists.

NoteIn the first example the given sequence can be rearranged in the following way: $$$[9, 3, 6, 12, 4, 8]$$$. It can match possible Polycarp's game which started with $$$x = 9$$$.

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

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

    bool[BigInt] d;

    int maxPow = -1;
    BigInt curValue = ulong.max;

    foreach (_; 0 .. n)
    {
        ulong t;
        readf(" %s", t);
        d[cast(BigInt)t] = true;

        int pow = 0;
        BigInt tc = t;

        while (tc % 3 == 0)
        {
            tc /= 3;
            pow++;
        }

        if (pow > maxPow || pow == maxPow && curValue > t)
        {
            maxPow = pow;
            curValue = t;
        }
    }

    foreach (_; 0 .. n)
    {
        write(curValue, ' ');

        if (curValue * 2 in d)
        {
            curValue *= 2;
        }
        else
        {
            curValue /= 3;
        }
    }
}

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

void main()
{
    readln;

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

    int div3 (ulong x) {
        return x % 3 == 0 ? 1 + div3(x/3) : 0;
    }

    auto b = a
        .map!(x => tuple(div3(x), x)).array
        .multiSort!(q{ a[0] > b[0] }, q{ a[1] < b[1] })
        .map!(q{ a[1] });

    writefln ("%(%s %)", b);
}

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

void main()
{
    readln;

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

    int div3 (ulong x) {
        int r = 0;
        while (x % 3 == 0) x /= 3, ++r;
        return r;
    }

    auto b = a
        .map!(x => tuple(div3(x), x)).array
        .multiSort!(q{ a[0] > b[0] }, q{ a[1] < b[1] })
        .map!(q{ a[1] });

    writefln ("%(%s %)", b);
}

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

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

void main()
{
  int n; readV(n);
  long[] a; readA(n, a);

  auto p = new int[](n); p[] = -1;
  foreach (i; 0..n)
    foreach (j; 0..n)
      if (a[j]%3 == 0 && a[j]/3 == a[i] || a[j]*2 == a[i]) p[j] = i;

  auto i = iota(n).countUntil!(i => !p.canFind(i));
  while (i != -1) {
    write(a[i], " ");
    i = p[i];
  }
}

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

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

    bool[ulong] d;

    int maxPow = -1;
    ulong curValue;

    foreach (_; 0 .. n)
    {
        ulong t;
        readf(" %s", t);
        d[t] = true;

        int pow = 0;
        ulong tc = t;

        while (tc % 3 == 0)
        {
            tc /= 3;
            pow++;
        }

        if (pow > maxPow)
        {
            maxPow = pow;
            curValue = t;
        }
    }

    foreach (_; 0 .. n)
    {
        write(curValue, ' ');

        if (curValue * 2 in d)
        {
            curValue *= 2;
        }
        else
        {
            curValue /= 3;
        }
    }
}

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

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

    bool[BigInt] d;

    int maxPow = -1;
    BigInt curValue = ulong.max;

    foreach (_; 0 .. n)
    {
        ulong t;
        readf(" %s", t);
        d[cast(BigInt)t] = true;

        int pow = 0;
        BigInt tc = t;

        while (tc % 3 == 0)
        {
            tc /= 3;
            pow++;
        }

        if (pow > maxPow && curValue > t)
        {
            maxPow = pow;
            curValue = t;
        }
    }

    foreach (_; 0 .. n)
    {
        write(curValue, ' ');

        if (curValue * 2 in d)
        {
            curValue *= 2;
        }
        else
        {
            curValue /= 3;
        }
    }
}

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

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

    bool[BigInt] d;

    int maxPow = -1;
    BigInt curValue;

    foreach (_; 0 .. n)
    {
        ulong t;
        readf(" %s", t);
        d[cast(BigInt)t] = true;

        int pow = 0;
        BigInt tc = t;

        while (tc % 3 == 0)
        {
            tc /= 3;
            pow++;
        }

        if (pow > maxPow)
        {
            maxPow = pow;
            curValue = t;
        }
    }

    foreach (_; 0 .. n)
    {
        write(curValue, ' ');

        if (curValue * 2 in d)
        {
            curValue *= 2;
        }
        else
        {
            curValue /= 3;
        }
    }
}

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

void main()
{
    readln;

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

    int div3 (ulong x) {
        int r = 0;
        while (x % 3 == 0) x /= 3, ++r;
        return r;
    }

    auto b = a.map!(x => tuple(div3(x), x)).array.sort!(q{ a[0] > b[0] }).map!(q{ a[1] });
    writefln ("%(%s %)", b);

}


You are given an array of $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$.You will perform $$$q$$$ operations. In the $$$i$$$-th operation, you have a symbol $$$s_i$$$ which is either "<" or ">" and a number $$$x_i$$$.You make a new array $$$b$$$ such that $$$b_j = -a_j$$$ if $$$a_j s_i x_i$$$ and $$$b_j = a_j$$$ otherwise (i.e. if $$$s_i$$$ is '>', then all $$$a_j > x_i$$$ will be flipped). After doing all these replacements, $$$a$$$ is set to be $$$b$$$.You want to know what your final array looks like after all operations.

The first line contains two integers $$$n,q$$$ ($$$1 \leq n,q \leq 10^5$$$) — the number of integers and the number of queries. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^5 \leq a_i \leq 10^5$$$) — the numbers. Each of the next $$$q$$$ lines contains a character and an integer $$$s_i, x_i$$$. ($$$s_i \in \{<, >\}, -10^5 \leq x_i \leq 10^5$$$) – the queries.

Print $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ representing the array after all operations.

import std.conv, std.functional, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.complex, std.container, std.math, std.numeric, std.range, 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 IDENTITY = 0b10;

int comp(int f, int g) {
  return ((f >> ((g >> 0) & 1)) & 1) << 0 | ((f >> ((g >> 1) & 1)) & 1) << 1;
}

class SegmentTree {
  int n;
  int[] fun, add;
  this(int n_) {
    for (n = 1; n < n_; n <<= 1) {}
    fun = new int[n << 1];
    add = new int[n << 1];
    fun[] = IDENTITY;
    add[] = IDENTITY;
  }
  // [a, b)
  private int query(int u, int x, int y, int a, int b, int val) {
    chmax(a, x);
    chmin(b, y);
    if (a >= b) {
      return -1;
    }
    if (a == x && b == y) {
      fun[u] = comp(val, fun[u]);
      add[u] = comp(val, add[u]);
      return fun[u];
    }
    assert(u < n);
    const uL = u << 1 | 0;
    const uR = u << 1 | 1;
    const mid = (x + y) >> 1;
    if (add[u] != IDENTITY) {
      fun[uL] = comp(add[u], fun[uL]);
      fun[uR] = comp(add[u], fun[uR]);
      add[uL] = comp(add[u], add[uL]);
      add[uR] = comp(add[u], add[uR]);
      add[u] = IDENTITY;
    }
    const resL = query(uL, x, mid, a, b, val);
    const resR = query(uR, mid, y, a, b, val);
    fun[u] = fun[uL];
    return (resL != -1) ? resL : resR;
  }
  // [a, b]
  int query(int a, int b, int val) {
    return query(1, 0, n, a, b + 1, val);
  }
}

int N, Q;
int[] A;
string[] S;
int[] X;

void main() {
  debug {
    foreach (f; 0 .. 4) foreach (g; 0 .. 4) {
      writeln(f, " o ", g, " = ", comp(f, g));
    }
  }

  try {
    for (; ; ) {
      N = readInt();
      Q = readInt();
      A = new int[N];
      foreach (i; 0 .. N) {
        A[i] = readInt();
      }
      S = new string[Q];
      X = new int[Q];
      foreach (q; 0 .. Q) {
        S[q] = readToken();
        X[q] = readInt();
      }

      auto ps = new Tuple!(int, int)[N];
      foreach (i; 0 .. N) {
        ps[i] = tuple(A[i], i);
      }
      ps.sort;
      auto as = new int[N];
      foreach (i; 0 .. N) {
        as[i] = ps[i][0];
      }

      auto seg = new SegmentTree(N);
      foreach (q; 0 .. Q) {
        switch (S[q]) {
          case "<": {
            /*
              a < x <=> a < x
              -a < x <=> a > -x
            */
            const posP = as.lowerBound(+X[q]);
            const posM = as.upperBound(-X[q]);
            if (X[q] > 0) {
              // 0 -x] 01 [x 1
              seg.query(0, posM - 1, 0b11);
              seg.query(posM, posP - 1, 0b01);
              seg.query(posP, N - 1, 0b00);
            } else {
              // 0 [x  -x] 1
              seg.query(0, posP - 1, 0b11);
              seg.query(posM, N - 1, 0b00);
            }
          } break;
          case ">": {
            /*
              a > x <=> a > x
              -a > x <=> a < -x
            */
            const posP = as.upperBound(+X[q]);
            const posM = as.lowerBound(-X[q]);
            if (X[q] > 0) {
              // 1 [-x  x] 0
              seg.query(0, posM - 1, 0b00);
              seg.query(posP, N - 1, 0b11);
            } else {
              // 1 x] 01 [-x 0
              seg.query(0, posP - 1, 0b00);
              seg.query(posP, posM - 1, 0b01);
              seg.query(posM, N - 1, 0b11);
            }
          } break;
          default: assert(false);
        }
      }

      auto ans = new int[N];
      foreach (i; 0 .. N) {
        const f = seg.query(i, i + 1, IDENTITY);
        ans[ps[i][1]] = (((f >> 0) & 1) ? -1 : +1) * ps[i][0];
      }
      writeln(ans.to!string.replaceAll(regex(`[\[\],]`), ""));
    }
  } catch (EOFException e) {
  }
}

import std.conv, std.functional, std.stdio, std.string;
import std.algorithm, std.array, std.bigint, std.complex, std.container, std.math, std.numeric, std.range, 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 IDENTITY = 0b10;

int comp(int f, int g) {
  return ((f >> ((g >> 0) & 1)) & 1) << 0 | ((f >> ((g >> 1) & 1)) & 1) << 1;
}

class SegmentTree {
  int n;
  int[] fun, add;
  this(int n_) {
    for (n = 1; n < n_; n <<= 1) {}
    fun = new int[n << 1];
    add = new int[n << 1];
    fun[] = IDENTITY;
    add[] = IDENTITY;
  }
  // [a, b)
  private int query(int u, int x, int y, int a, int b, int val) {
    chmax(a, x);
    chmin(b, y);
    if (a >= b) {
      return -1;
    }
    if (a == x && b == y) {
      fun[u] = comp(val, fun[u]);
      add[u] = comp(val, add[u]);
      return fun[u];
    }
    assert(u < n);
    const uL = u << 1 | 0;
    const uR = u << 1 | 1;
    const mid = (x + y) >> 1;
    if (add[u] != IDENTITY) {
      fun[uL] = comp(add[u], fun[uL]);
      fun[uR] = comp(add[u], fun[uR]);
      add[uL] = comp(add[u], add[uL]);
      add[uR] = comp(add[u], add[uR]);
      add[u] = IDENTITY;
    }
    const resL = query(uL, x, mid, a, b, val);
    const resR = query(uR, mid, y, a, b, val);
    fun[u] = fun[uL];
    return (resL != -1) ? resL : resR;
  }
  // [a, b]
  int query(int a, int b, int val) {
    return query(1, 0, n, a, b + 1, val);
  }
}

int N, Q;
int[] A;
string[] S;
int[] X;

void main() {
  try {
    for (; ; ) {
      N = readInt();
      Q = readInt();
      A = new int[N];
      foreach (i; 0 .. N) {
        A[i] = readInt();
      }
      S = new string[Q];
      X = new int[Q];
      foreach (q; 0 .. Q) {
        S[q] = readToken();
        X[q] = readInt();
      }

      auto ps = new Tuple!(int, int)[N];
      foreach (i; 0 .. N) {
        ps[i] = tuple(A[i], i);
      }
      ps.sort;
      auto as = new int[N];
      foreach (i; 0 .. N) {
        as[i] = ps[i][0];
      }

      auto seg = new SegmentTree(N);
      foreach (q; 0 .. Q) {
        switch (S[q]) {
          case "<": {
            /*
              a < x <=> a < x
              -a < x <=> a > -x
            */
            const posP = as.lowerBound(+X[q]);
            const posM = as.upperBound(-X[q]);
            seg.query(0, posP - 1, 0b11);
            seg.query(posM, N - 1, 0b00);
          } break;
          case ">": {
            /*
              a > x <=> a > x
              -a > x <=> a < -x
            */
            const posP = as.upperBound(+X[q]);
            const posM = as.lowerBound(-X[q]);
            seg.query(0, posM - 1, 0b00);
            seg.query(posP, N - 1, 0b11);
          } break;
          default: assert(false);
        }
      }

      auto ans = new int[N];
      foreach (i; 0 .. N) {
        const f = seg.query(i, i + 1, IDENTITY);
        ans[ps[i][1]] = (((f >> 0) & 1) ? -1 : +1) * ps[i][0];
      }
      writeln(ans.to!string.replaceAll(regex(`[\[\],]`), ""));
    }
  } catch (EOFException e) {
  }
}


You have $$$n$$$ sticks of the given lengths.Your task is to choose exactly four of them in such a way that they can form a rectangle. No sticks can be cut to pieces, each side of the rectangle must be formed by a single stick. No stick can be chosen multiple times. It is guaranteed that it is always possible to choose such sticks.Let $$$S$$$ be the area of the rectangle and $$$P$$$ be the perimeter of the rectangle. The chosen rectangle should have the value $$$\frac{P^2}{S}$$$ minimal possible. The value is taken without any rounding.If there are multiple answers, print any of them.Each testcase contains several lists of sticks, for each of them you are required to solve the problem separately.

The first line contains a single integer $$$T$$$ ($$$T \ge 1$$$) — the number of lists of sticks in the testcase. Then $$$2T$$$ lines follow — lines $$$(2i - 1)$$$ and $$$2i$$$ of them describe the $$$i$$$-th list. The first line of the pair contains a single integer $$$n$$$ ($$$4 \le n \le 10^6$$$) — the number of sticks in the $$$i$$$-th list. The second line of the pair contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_j \le 10^4$$$) — lengths of the sticks in the $$$i$$$-th list. It is guaranteed that for each list there exists a way to choose four sticks so that they form a rectangle. The total number of sticks in all $$$T$$$ lists doesn't exceed $$$10^6$$$ in each testcase.

Print $$$T$$$ lines. The $$$i$$$-th line should contain the answer to the $$$i$$$-th list of the input. That is the lengths of the four sticks you choose from the $$$i$$$-th list, so that they form a rectangle and the value $$$\frac{P^2}{S}$$$ of this rectangle is minimal possible. You can print these four lengths in arbitrary order. If there are multiple answers, print any of them.

NoteThere is only one way to choose four sticks in the first list, they form a rectangle with sides $$$2$$$ and $$$7$$$, its area is $$$2 \cdot 7 = 14$$$, perimeter is $$$2(2 + 7) = 18$$$. $$$\frac{18^2}{14} \approx 23.143$$$.The second list contains subsets of four sticks that can form rectangles with sides $$$(1, 2)$$$, $$$(2, 8)$$$ and $$$(1, 8)$$$. Their values are $$$\frac{6^2}{2} = 18$$$, $$$\frac{20^2}{16} = 25$$$ and $$$\frac{18^2}{8} = 40.5$$$, respectively. The minimal one of them is the rectangle $$$(1, 2)$$$.You can choose any four of the $$$5$$$ given sticks from the third list, they will form a square with side $$$5$$$, which is still a rectangle with sides $$$(5, 5)$$$.

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

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

void solve() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;
    long[long] C;
    long[] B;

    foreach (a; A) C[a] += 1;
    foreach (k; C.keys) if (C[k] >= 2) B ~= k;
    B.sort();

    bool comp(long a1, long b1, long a2, long b2) {
        return
            4 * (a1 + b1) * (a1 + b1) * a2 * b2 <=
            4 * (a2 + b2) * (a2 + b2) * a1 * b1;
    }

    long aa = -1;
    long bb = -1;

    foreach (i; 0..B.length.to!int) {
        long b = B[i];
        long a1 = -1;
        long a2 = -1;
        if (C[b] >= 4) {
            a1 = a2 = b;
        } else if (i == 0) {
            a1 = a2 = B[i+1];
        } else if (i == B.length.to!int - 1) {
            a1 = a2 = B[i-1];
        } else {
            a1 = B[i+1];
            a2 = B[i-1];
        }
        long a = comp(a1, b, a2, b) ? a1 : a2;
        if (aa == -1) {
            aa = a;
            bb = b;
        } else if (comp(a, b, aa, bb)) {
            aa = a;
            bb = b;
        }
    }

    writeln(aa, " ", aa, " ", bb, " ", bb);
}

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

    while (t--) {
        int n;
        readf("%s", &n);
        readln;

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

        auto nrs1 = zip(arr, arr.dropOne).filter!(t => t[0] == t[1]).map!(t => t[0]).uniq.array;
        auto nrs2 = zip(arr, arr.drop(3)).filter!(t => t[0] == t[1]).map!(t => t[0]).uniq.array;

        auto nrs = nrs1.chain(nrs2).sort().array;

        debug { nrs.writeln; }

        auto ans = tuple(nrs[0], nrs[1]);
        foreach (a, b; lockstep(nrs.dropOne, nrs.drop(2))) {
            if (ans[1] * a > ans[0] * b) ans = tuple(a, b);
        }

        writeln(ans[0], ' ', ans[0], ' ', ans[1], ' ', ans[1]);
    }
}

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

    while (t--) {
        int n;
        readf("%s", &n);
        readln;

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

        auto f = (int x) => zip(arr, arr.drop(x)).filter!(t => t[0] == t[1]).map!(t => t[0]).uniq;
        auto nrs1 = f(1);
        auto nrs2 = f(3);

        auto nrs = nrs1.chain(nrs2).array.sort();

        debug { nrs.writeln; }

        auto ans = tuple(nrs[0], nrs[1]);
        foreach (a, b; lockstep(nrs.dropOne, nrs.drop(2))) {
            if (ans[1] * a > ans[0] * b) ans = tuple(a, b);
        }

        writeln(ans[0], ' ', ans[0], ' ', ans[1], ' ', ans[1]);
    }
}


You are given $$$n$$$ words, each of which consists of lowercase alphabet letters. Each word contains at least one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible.Each lyric consists of two lines. Each line consists of two words separated by whitespace. A lyric is beautiful if and only if it satisfies all conditions below.   The number of vowels in the first word of the first line is the same as the number of vowels in the first word of the second line.  The number of vowels in the second word of the first line is the same as the number of vowels in the second word of the second line.  The last vowel of the first line is the same as the last vowel of the second line. Note that there may be consonants after the vowel. Also, letters "a", "e", "o", "i", and "u" are vowels. Note that "y" is never vowel.For example of a beautiful lyric,  "hello hellooowww" "whatsup yowowowow"  is a beautiful lyric because there are two vowels each in "hello" and "whatsup", four vowels each in "hellooowww" and "yowowowow" (keep in mind that "y" is not a vowel), and the last vowel of each line is "o".For example of a not beautiful lyric,  "hey man""iam mcdic"  is not a beautiful lyric because "hey" and "iam" don't have same number of vowels and the last vowels of two lines are different ("a" in the first and "i" in the second).How many beautiful lyrics can you write from given words? Note that you cannot use a word more times than it is given to you. For example, if a word is given three times, you can use it at most three times.

The first line contains single integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of words. The $$$i$$$-th of the next $$$n$$$ lines contains string $$$s_{i}$$$ consisting lowercase alphabet letters — the $$$i$$$-th word. It is guaranteed that the sum of the total word length is equal or less than $$$10^{6}$$$. Each word contains at least one vowel.

In the first line, print $$$m$$$ — the number of maximum possible beautiful lyrics. In next $$$2m$$$ lines, print $$$m$$$ beautiful lyrics (two lines per lyric). If there are multiple answers, print any.

14
wow
this
is
the
first
mcdics
codeforces
round
hooray
i
am
proud
about
that

7
arsijo
suggested
the
idea
for
this
problem

3
about proud
hooray round
wow first
this is
i that
mcdics am

NoteIn the first example, those beautiful lyrics are one of the possible answers. Let's look at the first lyric on the sample output of the first example. "about proud hooray round" forms a beautiful lyric because "about" and "hooray" have same number of vowels, "proud" and "round" have same number of vowels, and both lines have same last vowel. On the other hand, you cannot form any beautiful lyric with the word "codeforces".In the second example, you cannot form any beautiful lyric from given words.In the third example, you can use the word "same" up to three times.

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

struct Word {
  string s;
  int last;
}

void main() {
  int[char] v = [
    'a' : 0,
    'e' : 1,
    'i' : 2,
    'o' : 3,
    'u' : 4
  ];
  int vowel (char c) {
    return v.get(c, -1);
  }
  immutable n = readln.strip.to!int;
  auto a = new string[n];
  size_t maxlen;
  foreach (i; 0 .. n) {
    a[i] = readln.strip;
    maxlen = max(maxlen, a[i].length);
  }
  auto l = new int[][5 * (maxlen+1)];
  foreach (i; 0 .. n) {
    int t, last = -1;
    foreach (c; a[i]) {
      int x = vowel (c);
      if (x >= 0){
        ++t;
        last = x;
      }
    }
    l[5 * t + last] ~= i;
  }
  alias T = Tuple!(int, int);
  T[] b;
  T[] c;
  foreach (k; 1 .. maxlen+1) {
    int[] tail;
    foreach (i; 0 .. 5) {
      auto idx = 5 * k + i;
      int cur = -1;
      foreach (j; l[idx]) {
        if (cur >= 0) {
          b ~= tuple (cur, j);
          cur = -1;
        } else {
          cur = j;
        }
      }
      if (cur >= 0) tail ~= cur;
    }
    foreach (i; 0 .. tail.length / 2) {
      c ~= tuple (tail[2*i], tail[2*i+1]);
    }
  }
  immutable bl = b.length;
  immutable cl = c.length;
  auto m = min (bl, (bl + cl) / 2);
  c ~= b[m .. $];
  writeln (m);
  foreach (i; 0 .. m) {
    int p12 = b[i][0], p22 = b[i][1];
    int p11 = c[i][0], p21 = c[i][1];
    writeln (a[p11], ' ', a[p12]);
    writeln (a[p21], ' ', a[p22]);
  }
}

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

void solve(){
	int n = read.to!int;

	string[] ws;
	foreach(i; 0 .. n) ws ~= readln.chomp;

	struct X{ char last; int count; }
	string[][X] dic;
	foreach(w; ws){
		int k;
		char x;
		foreach(c; w) if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){
			x = c;
			k += 1;
		}
		if(X(x, k) !in dic) dic[X(x, k)] = [];
		dic[X(x, k)] ~= w;
	}
	log("dic:", dic);

	string[2][] latters;
	X[] ks = dic.keys;
	string[][int] dic2;
	foreach(k; ks){
		string[] qs = dic[k];
		for(int i = 0; i < qs.length - 1; i += 2){
			latters ~= [qs[i], qs[i + 1]];
		}
		if(qs.length % 2){
			if(k.count !in dic2) dic2[k.count] = [];
			dic2[k.count] ~= qs[$ - 1];
		}
	}
	log("latters:", latters);
	log("dic2:", dic2);

	string[2][] firsts;
	int[] cts = dic2.keys;
	foreach(ct; cts){
		string[] qs = dic2[ct];
		for(int i = 0; i < qs.length - 1; i += 2){
			firsts ~= [qs[i], qs[i + 1]];
		}
	}

	int m = (latters.length + firsts.length).to!int / 2;
	if(m > latters.length) m = latters.length.to!int;
	else{
		foreach(i; m .. latters.length) firsts ~= latters[i];
	}

	m.writeln;
	foreach(i; 0 .. m){
		writeln(firsts[i][0], " ", latters[i][0]);
		writeln(firsts[i][1], " ", latters[i][1]);
	}
}

/*

settify with (last vowel, vowel count)

greedily make pair for latter words
greedily make pair for first words

*/

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

string FMT_F = "%.10f";

static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

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

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

void main()
{
	auto n = RD!int;
	auto s = new string[](n);
	int[2][][int] info1;
	int[2][][int] info2;
	auto toNum = ['a':0, 'i':1, 'u':2, 'e':3, 'o':4];
	foreach (i; 0..n)
	{
		s[i] = RD!string;
		int last;
		int cnt;
		foreach (c; s[i])
		{
			auto num = toNum.get(c, -1);
			if (num != -1)
			{
				++cnt;
				last = num;
			}
		}
		info1[cnt]         ~= [i, last];
		info2[cnt*10+last] ~= [i, last];
	}

	int[] ansSec;
	auto used = new bool[](n);
	auto keys2 = info2.keys;
	foreach (key2; keys2)
	{
		auto arr2 = info2[key2];
		auto len2 = arr2.length;
		foreach (i; 0..len2/2)
		{
			auto j  = arr2[i*2][0];
			auto k  = arr2[i*2+1][0];
			ansSec ~= [j, k];
			used[j] = true;
			used[k] = true;
		}
	}

	int[] ansFst;
	auto keys1 = info1.keys;
	foreach (key1; keys1)
	{
		auto arr1 = info1[key1];
		auto len1 = arr1.length;
		int[] tmp;
		foreach (i; 0..len1)
		{
			auto j  = arr1[i][0];
			if (used[j]) continue;

			tmp ~= j;
			if (tmp.length == 2)
			{
				ansFst ~= tmp;
				tmp.length = 0;
			}
		}
	}

	auto diff = max(0, (cast(int)ansSec.length - cast(int)ansFst.length) / 4);
	foreach (i; 0..diff)
	{
		ansFst ~= [ansSec[$-2], ansSec[$-1]];
		ansSec.length = ansSec.length - 2;
	}

	auto len = min(ansFst.length, ansSec.length);
	writeln(len/2);
	foreach (i; 0..len)
	{
		auto j = ansFst[i];
		auto k = ansSec[i];
		writeln(s[j], " ", s[k]);
	}
	stdout.flush();
	debug readln();
}

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

string FMT_F = "%.10f";

static string[] s_rd;
T RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

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

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

void main()
{
	auto n = RD!int;
	auto s = new string[](n);
	int[2][][int] info1;
	int[2][][int] info2;
	auto toNum = ['a':0, 'i':1, 'u':2, 'e':3, 'o':4];
	foreach (i; 0..n)
	{
		s[i] = RD!string;
		int last;
		int cnt;
		foreach (c; s[i])
		{
			auto num = toNum.get(c, -1);
			if (num != -1)
			{
				++cnt;
				last = num;
			}
		}
		info1[cnt]         ~= [i, last];
		info2[cnt*10+last] ~= [i, last];
	}

	int[] ansSec;
	auto used = new bool[](n);
	auto keys2 = info2.keys;
	foreach (key2; keys2)
	{
		auto arr2 = info2[key2];
		auto len2 = arr2.length;
		foreach (i; 0..len2/2)
		{
			auto j  = arr2[i*2][0];
			auto k  = arr2[i*2+1][0];
			ansSec ~= [j, k];
			used[j] = true;
			used[k] = true;
		}
	}

	int[] ansFst;
	auto keys1 = info1.keys;
	foreach (key1; keys1)
	{
		auto arr1 = info1[key1];
		auto len1 = arr1.length;
		int[] tmp;
		foreach (i; 0..len1)
		{
			auto j  = arr1[i][0];
			if (used[j]) continue;

			tmp ~= j;
			if (tmp.length == 2)
			{
				ansFst ~= tmp;
				tmp.length = 0;
			}
		}
	}

	auto diff = max(0, (cast(int)ansSec.length - cast(int)ansFst.length) / 4);
	foreach (i; 0..diff)
	{
		ansFst ~= [ansSec[$-2], ansSec[$-1]];
		ansSec.length = ansSec.length - 2;
	}

	writeln(ansSec.length/2);
	foreach (i; 0..ansSec.length)
	{
		auto j = ansFst[i];
		auto k = ansSec[i];
		writeln(s[j], " ", s[k]);
	}
	stdout.flush();
	debug readln();
}


In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another.(Cultural note: standing in huge and disorganized queues for hours is a native tradition in Russia, dating back to the Soviet period. Queues can resemble crowds rather than lines. Not to get lost in such a queue, a person should follow a strict survival technique: you approach the queue and ask who the last person is, somebody answers and you join the crowd. Now you're the last person in the queue till somebody else shows up. You keep an eye on the one who was last before you as he is your only chance to get to your destination) I'm sure many people have had the problem when a stranger asks who the last person in the queue is and even dares to hint that he will be the last in the queue and then bolts away to some unknown destination. These are the representatives of the modern world, in which the ratio of lack of time is so great that they do not even watch foreign top-rated TV series. Such people often create problems in queues, because the newcomer does not see the last person in the queue and takes a place after the "virtual" link in this chain, wondering where this legendary figure has left.The Smart Beaver has been ill and he's made an appointment with a therapist. The doctor told the Beaver the sad news in a nutshell: it is necessary to do an electrocardiogram. The next day the Smart Beaver got up early, put on the famous TV series on download (three hours till the download's complete), clenched his teeth and bravely went to join a queue to the electrocardiogram room, which is notorious for the biggest queues at the clinic.Having stood for about three hours in the queue, the Smart Beaver realized that many beavers had not seen who was supposed to stand in the queue before them and there was a huge mess. He came up to each beaver in the ECG room queue and asked who should be in front of him in the queue. If the beaver did not know his correct position in the queue, then it might be his turn to go get an ECG, or maybe he should wait for a long, long time...As you've guessed, the Smart Beaver was in a hurry home, so he gave you all the necessary information for you to help him to determine what his number in the queue can be.

The first line contains two integers n (1 ≤ n ≤ 103) and x (1 ≤ x ≤ n) — the number of beavers that stand in the queue and the Smart Beaver's number, correspondingly. All willing to get to the doctor are numbered from 1 to n. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ n) — the number of the beaver followed by the i-th beaver. If ai = 0, then the i-th beaver doesn't know who is should be in front of him. It is guaranteed that values ai are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue. The input limits for scoring 30 points are (subproblem B1):    It is guaranteed that the number of zero elements ai doesn't exceed 20.  The input limits for scoring 100 points are (subproblems B1+B2):    The number of zero elements ai is arbitrary.

Print all possible positions of the Smart Beaver in the line in the increasing order.

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

immutable int MAX_N = 100_005;
immutable int MAX_C = 0x3F3F3F3F;
immutable int NA    = -1;

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

		auto r = new int [n];
		r[] = NA;
		foreach (i; 0..n)
		{
			if (p[i] != NA)
			{
				r[p[i]] = i;
			}
		}

		int [] [] s;
		int d = NA;

		foreach (i; 0..n)
		{
			if (p[i] == NA)
			{
				int [] cur;
				int j = i;
				cur ~= j;
				while (r[j] != NA)
				{
					j = r[j];
					cur ~= j;
				}
				int e = cur.countUntil (x);
				if (e != NA)
				{
					d = e;
				}
				else
				{
					s ~= cur;
				}
			}
		}
		assert (d != NA);

		auto f = new bool [n + 1];
		f[0] = true;
		foreach (cur; s)
		{
			int l = cur.length;
			for (int i = n; i >= l; i--)
			{
				f[i] |= f[i - l];
			}
		}

		foreach (i; 0..n)
		{
			if (f[i])
			{
				writeln (i + d + 1);
			}
		}
	}
}


Toastman came up with a very complicated task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o', or nothing. How many ways to fill all the empty cells with 'x' or 'o' (each cell must contain only one character in the end) are there, such that for each cell the number of adjacent cells with 'o' will be even? Find the number of ways modulo 1000000007 (109 + 7). Two cells of the board are adjacent if they share a side.

The first line contains two integers n, k (1 ≤ n, k ≤ 105) — the size of the board, and the number of cells that has characters initially.  Then k lines follows. The i-th line contains two integers and a character: ai, bi, ci (1 ≤ ai, bi ≤ n; ci is either 'o' or 'x'). This line means: there is a character ci in the cell that is located on the intersection of the ai-th row and bi-th column. All the given cells are distinct. Consider that the rows are numbered from 1 to n from top to bottom. Analogically, the columns are numbered from 1 to n from left to right.

Print a single integer — the answer to the problem.

NoteIn the first example there are two ways:    xxo          xoo    xox          ooo    oxx          oox

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

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

//	chmin/chmax
void chmin(T)(ref T t, in T f) { if (t > f) t = f; }
void chmax(T)(ref T t, in T f) { if (t < f) t = f; }

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

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

int root(int[] p, int[] q, int u) {
	if (p[u] < 0) {
		return u;
	} else {
		int r = root(p, q, p[u]);
		// q[u] += q[p[u]];
		q[u] ^= q[p[u]];
		return (p[u] = r);
	}
}
int conn(int[] p, int[] q, int u, int v, int c) {
debug{
writeln("  conn ",u," ",v," ",c);
}
	int ru = root(p, q, u), rv = root(p, q, v);
	// c -= q[v] - q[u];
	c ^= q[v] ^ q[u];
	if (ru == rv) return (c != 0) ? -1 : 0;
	// if (p[ru] > p[rv]) { swap(ru, rv); c *= -1; }
	if (p[ru] > p[rv]) { swap(ru, rv); }
	p[ru] += p[rv]; p[rv] = ru; q[rv] = c;
	return 1;
}

immutable MO = 1000000007L;

int N, K;
int[] X, Y;
string[] C;

long solve() {
	long ret = 1;
	foreach (s; 0 .. 2) {
		if (N == 1 && s == 1) {
			continue;
		}
		const l = (N - 1 - s) / 2 + 1;
debug{
writeln(N," ",s," ",l);
}
		int[] p = new int[l + 1];
		int[] q = new int[l + 1];
		p[] = -1;
		foreach (k; 0 .. K) if ((X[k] + Y[k]) % 2 == s) {
			const a = abs(X[k] - Y[k]);
			const b = abs(X[k] + Y[k] - (N + 1));
			const u = (a - s) / 2;
			const v = ((N - 1 - s) - b) / 2;
			assert(u <= v);
debug{
writeln(" ",u," ",v," ",C[k]);
}
			const res = conn(p, q, u, v + 1, (C[k] == "o") ? 1 : 0);
			if (res == -1) {
				return 0;
			}
		}
		int cnt = p.count!"a < 0";
		foreach (_; 0 .. cnt - 1) {
			(ret *= 2) %= MO;
		}
	}
	return ret;
}

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		K = readInt;
		X = new int[K];
		Y = new int[K];
		C = new string[K];
		foreach (k; 0 .. K) {
			X[k] = readInt;
			Y[k] = readInt;
			C[k] = readToken;
		}
		const res = solve;
		writeln(res);
	}
	} catch (EOFException) {}
}


Monocarp had a tree which consisted of $$$n$$$ vertices and was rooted at vertex $$$1$$$. He decided to study BFS (Breadth-first search), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:a = [] # the order in which vertices were processedq = Queue()q.put(1) # place the root at the end of the queuewhile not q.empty():    k = q.pop() # retrieve the first vertex from the queue    a.append(k) # append k to the end of the sequence in which vertices were visited    for y in g[k]: # g[k] is the list of all children of vertex k, sorted in ascending order        q.put(y)Monocarp was fascinated by BFS so much that, in the end, he lost his tree. Fortunately, he still has a sequence of vertices, in which order vertices were visited by the BFS algorithm (the array a from the pseudocode). Monocarp knows that each vertex was visited exactly once (since they were put and taken from the queue exactly once). Also, he knows that all children of each vertex were viewed in ascending order.Monocarp knows that there are many trees (in the general case) with the same visiting order $$$a$$$, so he doesn't hope to restore his tree. Monocarp is okay with any tree that has minimum height.The height of a tree is the maximum depth of the tree's vertices, and the depth of a vertex is the number of edges in the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all root's children are $$$1$$$.Help Monocarp to find any tree with given visiting order $$$a$$$ and minimum height.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$; $$$a_i \neq a_j$$$; $$$a_1 = 1$$$) — the order in which the vertices were visited by the BFS algorithm. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case print the minimum possible height of a tree with the given visiting order $$$a$$$.

NoteIn the first test case, there is only one tree with the given visiting order:   In the second test case, there is only one tree with the given visiting order as well:   In the third test case, an optimal tree with the given visiting order is shown below:

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		int [] levels;
		levels ~= 1;
		int cur = 0;
		int prev = 1;
		foreach (i; 2..n)
		{
			if (a[i] < a[i - 1])
			{
				cur -= 1;
				if (cur < 0)
				{
					levels ~= i - prev;
					prev = i;
					cur = levels.back - 1;
				}
			}
		}
		writeln (levels.length);
	}
}