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

immutable int MAX_N = 100_000;
int n, m;
Array!int[MAX_N] g;
int[3][MAX_N] comp;
int[3] cc;
int[MAX_N] ans;

void main()
{
    readln.strip.formattedRead(" %s %s", n, m);

    foreach (i; 0 .. m)
    {
        int a, b;
        readln.strip.formattedRead(" %s %s", a, b);
        a--, b--;
        g[a] ~= b;
        g[b] ~= a;
    }

    foreach (i; 0 .. n)
    {
        bool ok = false;
        foreach (j; 0 .. 3)
        {
            if (!comp[i][j])
            {
                ans[i] = j;
                cc[j]++;
                foreach (k; g[i])
                {
                    comp[k][j] = true;
                }
                ok = true;
                break;
            }
        }

        if (!ok)
        {
            writeln(-1);
            return;
        }
    }

    bool ok = true;

    foreach (i; 0 .. n)
    {
        ok &= n == (g[i].length + cc[ans[i]]);
    }

    ok &= cc[0] > 0 && cc[1] > 0 && cc[2] > 0;

    if (ok)
    {
        foreach (i; 0 .. n)
        {
            write(ans[i] + 1, " ");
        }
        writeln();
    }
    else
    {
        writeln(-1);
    }
}

import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;
import std.traits;
import std.array;
struct Input
{
  T next(T)()
  {
    import std.conv;
    return to!T(nextWord);
  }
  string nextWord()
  {
    if (_nextWords.empty)
	_nextWords.insertFront(readln().split);
    string word = _nextWords.front; _nextWords.removeFront;
    return word;
  }
  import std.container;
  DList!string _nextWords;
}
Input input;
void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]) && !is(T[i] == string))
      foreach(ref e; args[i])
    	read(e);
    else static if(isTuple!(T[i]))
      static foreach(n; 0 .. T[i].Types.length)
	read(args[i][n]);
    else
      args[i] = input.next!(typeof(args[i]))();
}
auto itup(alias k, alias F)()
{
  alias T = Parameters!F;
  foreach(i; 0 .. k)
    {
      T t; get(t);
      F(t);
    }
}
alias get = read;
void wone(T)(T t, char end)
{
  static if(isArray!T && !is(T == string))
    {
      foreach(i; 0 .. t.length - 1)
	  write(t[i], ' ');
      write(t[$ - 1], end);
    }
  else
      write(t, end);
}
void wr(T...)(T t)
{
  static foreach(i; 0 .. T.length)
    static if(i + 1 < T.length)
      wone(t[i], ' ');
    else
      wone(t[i], '\n');
}
void ans(T...)(T t)
{
  import core.stdc.stdlib;
  wr(t);
  exit(0);
}
import std.container;
long[][] adj;
string[] adjstr;

void connect(long a, long b)
{
  adj[cast(uint)a] ~= b;
  adj[cast(uint)b] ~= a;
}

void main()
{
  import std.conv;
  long n, m; get(n, m);
  adj = new long[][cast(uint)n];
  adjstr = new string[cast(uint)n];
  itup!(m, (long a, long b) {
      connect(a - 1, b - 1);
    });
  short[string] color;
  short col = 1;
  foreach(size_t v, ref a; adj)
    {
      sort(a);
      adjstr[v] = "";
      foreach(e; a)
	  adjstr[v] ~= to!string(e) ~ ".";
      if(adjstr[v] !in color)
	{
	  if ( col > 3 )
	    ans(-1);
	  color[adjstr[v]] = col;
	  col++;
	}
    }
  if (col != 4)
    ans(-1);
  short[int] colorfor;
  int[3] cant;
  int[3] reqsum;
  foreach(v; 0 .. n)
    {
      colorfor[cast(int)v] = color[adjstr[cast(int)v]];
      cant[color[adjstr[cast(uint)v]] - 1]++;
    }
  reqsum[0] = cant[1] + cant[2];
  reqsum[1] = cant[0] + cant[2];
  reqsum[2] = cant[0] + cant[1];
  foreach(v; 0 .. n)
    {
      if(adj[cast(uint)v].length != reqsum[colorfor[cast(int)v] - 1])
	ans(-1);
    }
  foreach(v; 0 .. n)
    write(colorfor[cast(int)v], " ");
  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.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

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

    RedBlackTree!int[] g;
    foreach (_; 0 .. n) {
        g ~= make!(RedBlackTree!int);
    }

    foreach (_; 0 .. m) {
        int u, v;
        readf("%s %s", &u, &v);
        readln;

        --u, --v;

        g[u].insert(v);
        g[v].insert(u);
    }

    debug { g.writeln; }

    if (g[0].empty()) {
        writeln(-1);
        return;
    }

    auto ans = new int[] (n);

    ans[0] = 1;
    int nxt = g[0].front;
    ans[nxt] = 2;

    foreach (u; g[0].array.dropOne) {
        if (g[u].equalRange(nxt).empty()) { ans[u] = 2; }
        else { ans[u] = 3; }
    }

    foreach (v; 1 .. n) {
        if (ans[v] == 0) {
            bool to0 = ! g[v].equalRange(0).empty();
            bool to1 = ! g[v].equalRange(nxt).empty();

            if (to0 && to1) { ans[v] = 3; }
            else if (to0) { ans[v] = 2; }
            else if (to1) { ans[v] = 1; }
            else {
                writeln(-1);
                return;
            }
        }
    }

    foreach (v; 0 .. n) {
        foreach (u; g[v]) {
            if (ans[v] == ans[u]) {
                writeln(-1);
                return;
            }
        }
    }

    int[4] cnts;
    foreach (e; ans) { ++cnts[e]; }

    foreach (v; 0 .. n) {
        int other = n - cnts[ans[v]];
        if (g[v].length != other) {
            writeln(-1);
            return;
        }
    }

    if (ans.all!(x => x != 3)) {
        writeln(-1);
        return;
    }

    ans.map!(to!string).join(' ').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.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

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

    RedBlackTree!int[] g;
    foreach (_; 0 .. n) {
        g ~= make!(RedBlackTree!int);
    }

    foreach (_; 0 .. m) {
        int u, v;
        readf("%s %s", &u, &v);
        readln;

        --u, --v;

        g[u].insert(v);
        g[v].insert(u);
    }

    debug { g.writeln; }

    if (g[0].empty()) {
        writeln(-1);
        return;
    }

    auto ans = new int[] (n);

    ans[0] = 1;
    int nxt = g[0].front;
    ans[nxt] = 2;

    foreach (u; g[0].array.dropOne) {
        if (g[u].equalRange(nxt).empty()) { ans[u] = 2; }
        else { ans[u] = 3; }
    }

    foreach (v; 1 .. n) {
        if (ans[v] == 0) {
            bool to0 = ! g[v].equalRange(0).empty();
            bool to1 = ! g[v].equalRange(nxt).empty();

            if (to0 && to1) { ans[v] = 3; }
            else if (to0) { ans[v] = 2; }
            else if (to1) { ans[v] = 1; }
            else {
                writeln(-1);
                return;
            }
        }
    }

    foreach (v; 0 .. n) {
        foreach (u; g[v]) {
            if (ans[v] == ans[u]) {
                writeln(-1);
                return;
            }
        }
    }

    if (ans.dup.sort().uniq().array.length != 3) {
        writeln(-1);
        return;
    }

    ans.map!(to!string).join(' ').writeln;
}


import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm : sort, each, maxElement, minElement;
import std.conv : to;
import std.range : iota, tee, enumerate;
import std.algorithm.comparison : equal, max, min;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!int;

void main() {
  GC.disable();

  uint n;
  readf(" %s", n);
  auto l = new int[n];
  auto r = new int[n];
  foreach(i; 0..n) {
    uint ll, rr;
    readf(" %s %s", ll, rr);
    l[i] = ll;
    r[i] = rr;
  }

  uint k;
  readf(" %s", k);

  uint tt =0;
  uint ss = 0;
  foreach(i; 0..n) {

    if (l[i] <= k && r[i] >= k) {
      ss = i;
      break;
    }
  }

  writeln(n - ss);

}

import std.stdio;
int main()
{
	int t=0;
	readf(" %d", &t);
	int[] m = new int[t];
	for (int i=0; i<t; i++)
	{
		int a=0;
		readf(" %d", &a);
		readf(" %d", &m[i]);
	}
	int x=0;
	readf(" %d", &x);
	int count=0;
	for (int i=0; i<t; i++)
	{
		if (x>m[i])
		{
			count=count+1;
		}
	}
	writeln(t-count);
	return 0;
}


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

immutable int NA = -1;

void main ()
{
	int n;
multitest_loop:
	while (readf !(" %s") (n) > 0)
	{
		auto a = new int [n];
		auto b = new int [n];
		auto c = new int [n];
		foreach (i; 0..n)
		{
			readf !(" %s %s %s") (a[i], b[i], c[i]);
		}
		auto adj = new int [] [n];
		foreach (j; 0..n - 1)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			adj[u] ~= v;
			adj[v] ~= u;
		}

		if (sum (b) != sum (c))
		{
			writeln (-1);
			continue multitest_loop;
		}

		long recur (int v, int p)
		{
			long res = 0;
			int need = b[v] - c[v];
			foreach (u; adj[v])
			{
				if (u != p)
				{
					a[u] = min (a[u], a[v]);
					res += recur (u, v);
					b[v] += b[u];
					c[v] += c[u];
					int next = b[u] - c[u];
					while (need < 0 && next > 0)
					{
						res += a[v];
						need += 1;
						next -= 1;
					}
					while (need > 0 && next < 0)
					{
						res += a[v];
						need -= 1;
						next += 1;
					}
					need += next;
				}
			}
			return res;
		}

		long res = recur (0, NA);
		writeln (res * 2);
	}
}

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;

void main(string[] args)
{
  inputFile = stdin;
  auto n = next!int;
  enum NodeType
    {
      empty,
      mis0,
      mis1,
    }
  auto nodetype = new NodeType[](n);
  auto aValue = new long[](n);
  int dlt = 0;
  foreach(i; 0 .. n)
    {
      auto a = next!long;
      auto b = next!long;
      auto c = next!long;
      aValue[i] = a;
      if (b == c)
	{
	  nodetype[i] = NodeType.empty;
	}
      else
	{
	  if (b == 0)
	    {
	      nodetype[i] = NodeType.mis0;
	      dlt++;
	    }
	  else
	    {
	      nodetype[i] = NodeType.mis1;
	      dlt--;
	    }
	}
    }
  if (dlt != 0) return writeln(-1);
  debug writeln(nodetype);
  auto mis1cnt = new int[](n);
  auto mis0cnt = new int[](n);
  auto cost = new long[](n);
  auto height = new int[](n);
  auto parent = new int[](n);
  auto als = new int[][](n);
  foreach(i; 0 .. n - 1)
    {
      auto u = next!int - 1;
      auto v = next!int - 1;
      als[u] ~= v;
      als[v] ~= u;
    }
  auto queue = new Tuple!(int, int)[](n);
  void calcdfs(int v, long c, int h, int p)
  {
    cost[v] = c;
    height[v] = h;
    parent[v] = p;
    queue[v] = tuple(h, v);
    mis1cnt[v] = (nodetype[v] == NodeType.mis1);
    mis0cnt[v] = (nodetype[v] == NodeType.mis0);
    foreach(w; als[v])
      if (w != p)
	{
	  calcdfs(w, min(cost[v], aValue[w]), h + 1, v);
	}
  }
  /*
            1
          /   \
	 5     2
              / \
             4   3
   */
  calcdfs(0, aValue[0], 0, -1);
  auto squeue = sort(queue);
  auto totalCost = long(0);
  foreach_reverse(q; squeue)
    {
      auto node = q[1];
      debug writeln("doing node ", node + 1, " m0 ", mis0cnt[node], " m1 ", mis1cnt[node]);
      auto toremove = min(mis1cnt[node], mis0cnt[node]);
      totalCost += toremove * cost[node] * 2;
      mis1cnt[node] -= toremove;
      mis0cnt[node] -= toremove;
      debug writeln("doing node ", node + 1, " m0 ", mis0cnt[node], " m1 ", mis1cnt[node],
		    " p ", parent[node] + 1);
      if (parent[node] != -1)
	{
	  mis1cnt[parent[node]] += mis1cnt[node];
	  mis0cnt[parent[node]] += mis0cnt[node];
	}
    }
  totalCost.writeln;
}
ulong bitCnt(long x)
{
  ulong cnt = 0;
  while(x) {cnt += x & 1; x>>=1;}
  return cnt;
}
alias Arr(T) = Mat!(T, 1);
struct Mat(T, size_t dimension)
{
  T[] _baseArray;
  T[] _slice;
  size_t[dimension] _sizes; size_t dim(size_t i) {return _sizes[i];}
  size_t[dimension] _indexer;
  this(T[] baseArray, size_t[dimension] sizes)
  {
    _baseArray = baseArray;
    _sizes = sizes;
    _indexer[dimension - 1] = 1;
    static foreach_reverse(i; 0 .. dimension - 1)
      _indexer[i] = _indexer[i + 1] * _sizes[i + 1];
    auto requiredSize = _indexer[0] * _sizes[0];
    debug assert(_baseArray.length >= requiredSize);
    _slice = _baseArray[0 .. requiredSize];
  }
  this(size_t[dimension] sizes)
  {
    size_t reqSize = 1;
    static foreach(i; 0 .. dimension)
      reqSize *= sizes[i];
    this(new T[](reqSize), sizes);
  }
  ref auto opIndex()
  {
    pragma(inline, true);
    return _slice[];
  }
  ref auto opIndex(I...)(I i)
  {
    pragma(inline, true);
    debug assert(i.length <= dimension);
    size_t index = mixin(iota(0, i.length).map!(j => text("i[", j, "]*_indexer[", j, "]")).join("+"));
    static if (i.length == dimension)
      {
	return _slice[index];
      }
    else
      {
	enum sliceDimension = dimension - i.length;
	size_t[sliceDimension] remSizes = _sizes[i.length .. $];
	auto basePortion = _slice[index .. index + _indexer[i.length - 1]];
 	return Mat!(T, sliceDimension)(basePortion, remSizes);
      }
  }
  static if (dimension == 2)
    {
      auto identity()
      {
	debug assert(dim(0) == dim(1));
	auto n = dim(0);
	auto id = Mat!(T, 2)([n, n]);
	foreach(k; 0 .. n)
	  id[k, k] = T(1);
	return id;
      }
      bool canMultiply(Mat!(T, 2) b)
      {
	return this.dim(1) == b.dim(0);
      }
      auto opBinary(string op)(Mat!(T, 2) b)
	if (op == "*")
	  {
	    debug assert(canMultiply(b));
	    auto res = Mat!(T, 2)([this.dim(0), b.dim(1)]);
	    foreach(i; 0 .. res.dim(0))
	      foreach(k; 0 .. this.dim(1))
		foreach(j; 0 .. res.dim(1))
		  res[i, j] = res[i, j] + this[i, k] * b[k, j];
	    return res;
	  }
      auto opBinary(string op)(ulong exp)
	if (op == "^^")
	  {
	    return this.pow(identity, exp);
	  }
      mixin interiorBinPow;
    }
}

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

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

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

import std.stdio, 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 = new long[](n);
	auto b = new long[](n);
	auto c = new long[](n);
	foreach (i; 0..n)
	{
		a[i] = RD;
		b[i] = RD;
		c[i] = RD;
	}
	auto edges = new int[][](n);
	foreach (i; 0..n-1)
	{
		auto u = RD!int-1;
		auto v = RD!int-1;
		edges[u] ~= v;
		edges[v] ~= u;
	}

	auto d = new long[](n);
	auto cnt = new long[](n);
	auto par = new int[](n);

	long[] dfs(int pos, int last)
	{
		par[pos] = last;
		d[pos] = c[pos] - b[pos];
		cnt[pos] = b[pos] == c[pos] ? 0 : 1;
		foreach (to; edges[pos])
		{
			if (to == last) continue;
			auto r = dfs(to, pos);
			d[pos] += r[0];
			cnt[pos] += r[1];
		}
		return [d[pos], cnt[pos]];
	}
	dfs(0, -1);

	if (d[0] != 0)
		writeln(-1);
	else
	{
		long ans = a[0] * cnt[0];
		void dfs2(int pos, int last, long cost)
		{
			if (a[pos] < cost)
			{
				auto x = cnt[pos] - abs(d[pos]);
				ans -= cost * x;
				ans += a[pos] * x;
				cost = a[pos];
			}

			foreach (to; edges[pos])
			{
				if (to == last) continue;
				dfs2(to, pos, cost);
			}
		}
		dfs2(0, -1, a[0]);
		writeln(ans);
	}

	stdout.flush;
	debug readln;
}

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;

void main(string[] args)
{
  inputFile = stdin;
  auto n = next!int;
  enum NodeType
    {
      empty,
      mis0,
      mis1,
    }
  auto nodetype = new NodeType[](n);
  auto aValue = new int[](n);
  int dlt = 0;
  foreach(i; 0 .. n)
    {
      auto a = next!int;
      auto b = next!int;
      auto c = next!int;
      aValue[i] = a;
      if (b == c)
	{
	  nodetype[i] = NodeType.empty;
	}
      else
	{
	  if (b == 0)
	    {
	      nodetype[i] = NodeType.mis0;
	      dlt++;
	    }
	  else
	    {
	      nodetype[i] = NodeType.mis1;
	      dlt--;
	    }
	}
    }
  if (dlt != 0) return writeln(-1);
  debug writeln(nodetype);
  auto mis1cnt = new int[](n);
  auto mis0cnt = new int[](n);
  auto cost = new int[](n);
  auto height = new int[](n);
  auto parent = new int[](n);
  auto als = new int[][](n);
  foreach(i; 0 .. n - 1)
    {
      auto u = next!int - 1;
      auto v = next!int - 1;
      als[u] ~= v;
      als[v] ~= u;
    }
  auto queue = new Tuple!(int, int)[](n);
  void calcdfs(int v, int c, int h, int p)
  {
    cost[v] = c;
    height[v] = h;
    parent[v] = p;
    queue[v] = tuple(h, v);
    mis1cnt[v] = (nodetype[v] == NodeType.mis1);
    mis0cnt[v] = (nodetype[v] == NodeType.mis0);
    foreach(w; als[v])
      if (w != p)
	{
	  calcdfs(w, min(cost[v], aValue[w]), h + 1, v);
	}
  }
  /*
            1
          /   \
	 5     2
              / \
             4   3
   */
  calcdfs(0, aValue[0], 0, -1);
  auto squeue = sort(queue);
  auto totalCost = long(0);
  foreach_reverse(q; squeue)
    {
      auto node = q[1];
      debug writeln("doing node ", node + 1, " m0 ", mis0cnt[node], " m1 ", mis1cnt[node]);
      auto toremove = min(mis1cnt[node], mis0cnt[node]);
      totalCost += toremove * cost[node] * 2;
      mis1cnt[node] -= toremove;
      mis0cnt[node] -= toremove;
      debug writeln("doing node ", node + 1, " m0 ", mis0cnt[node], " m1 ", mis1cnt[node],
		    " p ", parent[node] + 1);
      if (parent[node] != -1)
	{
	  mis1cnt[parent[node]] += mis1cnt[node];
	  mis0cnt[parent[node]] += mis0cnt[node];
	}
    }
  totalCost.writeln;
}
ulong bitCnt(long x)
{
  ulong cnt = 0;
  while(x) {cnt += x & 1; x>>=1;}
  return cnt;
}
alias Arr(T) = Mat!(T, 1);
struct Mat(T, size_t dimension)
{
  T[] _baseArray;
  T[] _slice;
  size_t[dimension] _sizes; size_t dim(size_t i) {return _sizes[i];}
  size_t[dimension] _indexer;
  this(T[] baseArray, size_t[dimension] sizes)
  {
    _baseArray = baseArray;
    _sizes = sizes;
    _indexer[dimension - 1] = 1;
    static foreach_reverse(i; 0 .. dimension - 1)
      _indexer[i] = _indexer[i + 1] * _sizes[i + 1];
    auto requiredSize = _indexer[0] * _sizes[0];
    debug assert(_baseArray.length >= requiredSize);
    _slice = _baseArray[0 .. requiredSize];
  }
  this(size_t[dimension] sizes)
  {
    size_t reqSize = 1;
    static foreach(i; 0 .. dimension)
      reqSize *= sizes[i];
    this(new T[](reqSize), sizes);
  }
  ref auto opIndex()
  {
    pragma(inline, true);
    return _slice[];
  }
  ref auto opIndex(I...)(I i)
  {
    pragma(inline, true);
    debug assert(i.length <= dimension);
    size_t index = mixin(iota(0, i.length).map!(j => text("i[", j, "]*_indexer[", j, "]")).join("+"));
    static if (i.length == dimension)
      {
	return _slice[index];
      }
    else
      {
	enum sliceDimension = dimension - i.length;
	size_t[sliceDimension] remSizes = _sizes[i.length .. $];
	auto basePortion = _slice[index .. index + _indexer[i.length - 1]];
 	return Mat!(T, sliceDimension)(basePortion, remSizes);
      }
  }
  static if (dimension == 2)
    {
      auto identity()
      {
	debug assert(dim(0) == dim(1));
	auto n = dim(0);
	auto id = Mat!(T, 2)([n, n]);
	foreach(k; 0 .. n)
	  id[k, k] = T(1);
	return id;
      }
      bool canMultiply(Mat!(T, 2) b)
      {
	return this.dim(1) == b.dim(0);
      }
      auto opBinary(string op)(Mat!(T, 2) b)
	if (op == "*")
	  {
	    debug assert(canMultiply(b));
	    auto res = Mat!(T, 2)([this.dim(0), b.dim(1)]);
	    foreach(i; 0 .. res.dim(0))
	      foreach(k; 0 .. this.dim(1))
		foreach(j; 0 .. res.dim(1))
		  res[i, j] = res[i, j] + this[i, k] * b[k, j];
	    return res;
	  }
      auto opBinary(string op)(ulong exp)
	if (op == "^^")
	  {
	    return this.pow(identity, exp);
	  }
      mixin interiorBinPow;
    }
}

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

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

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

import std.stdio, 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 = new long[](n);
	auto b = new long[](n);
	auto c = new long[](n);
	foreach (i; 0..n)
	{
		a[i] = RD;
		b[i] = RD;
		c[i] = RD;
	}
	auto edges = new int[][](n);
	foreach (i; 0..n-1)
	{
		auto u = RD!int-1;
		auto v = RD!int-1;
		edges[u] ~= v;
		edges[v] ~= u;
	}

	auto d = new long[](n);
	auto cnt = new long[](n);
	auto par = new int[](n);

	long[] dfs(int pos, int last)
	{
		par[pos] = last;
		d[pos] = c[pos] - b[pos];
		cnt[pos] = b[pos] == c[pos] ? 0 : 1;
		foreach (to; edges[pos])
		{
			if (to == last) continue;
			auto r = dfs(to, pos);
			d[pos] += r[0];
			cnt[pos] += r[1];
		}
		return [d[pos], cnt[pos]];
	}
	dfs(0, -1);

	if (d[0] != 0)
		writeln(-1);
	else
	{
		long ans;
		auto index = a.MAKE_IDX();
		foreach (i; index)
		{
			auto x = min(cnt[i] - abs(d[i]), cnt[0]);
			cnt[i] -= x;
			ans += x * a[i];
			if (cnt[0] == 0)
				break;
			auto p = par[i];
			while (p != -1)
			{
				cnt[p] -= x;
				p = par[p];
			}
		}
		writeln(ans);
	}

	stdout.flush;
	debug readln;
}


module main;
__gshared:
import core.bitop, std.algorithm, std.bigint, std.bitmanip, std.complex,
	std.container, std.conv, std.datetime, std.functional, std.math, std.meta;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.parallelism, std.random, std.range, std.regex, std.stdio, std.string,
	std.traits, std.typecons, std.uni, std.variant;

alias pair(X, Y) = Tuple!(X, "fi", Y, "se");
alias mp = make_pair;
alias pii = pair!(int, int);
alias pll = pair!(long, long);
alias gcd = std.numeric.gcd;
alias lint = long;
alias rbt = RedBlackTree;
///modulo
enum mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///lcm
		T lcm(T)(auto ref T a, auto ref T b)
		{
			return a / gcd(a, b) * b;
		}
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///BigInt greatest common divizor
		BigInt gcd(BigInt a, BigInt b)
		{
			while (b)
			{
				a %= b;
				swap(a, b);
			}
			return a;
		}
		///square
		@property X sqr(X)(in X a_)
		{
			return a_ * a_;
		}
		///cube
		@property X cub(X)(in X a_)
		{
			return a_ * a_ * a_;
		}
		///posicion lower bound
		size_t lowb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			size_t l, r = a.length;
			while (r - l > 1)
			{
				auto m = (l + r) >> 1;
				if (!(a[m] < g))
					r = m;
				else
					l = m;
			}
			return (!(a[l] < g)) ? l : r;
		}
		///posicion upper bound
		size_t upb(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			size_t l, r = a.length;
			while (r - l > 1)
			{
				auto m = (l + r) >> 1;
				if (g < a[m])
					r = m;
				else
					l = m;
			}
			return (g < a[l]) ? l : r;
		}
		///posicion binary search
		size_t binf(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			auto pos = lowb(a, g);
			return (g == a[pos]) ? pos : a.length;
		}
		///binary search
		bool binary_search(T, X)(T a, auto ref X g)
				if (isRandomAccessRange!T && hasLength!T && is(typeof(g < a[0]) == bool))
		{
			return binf(a, g) != a.length;
		}
	}
	///write an array
	void putarr(X)(in X a, in char ch = ' ') if (isInputRange!X)
	{
		writefln("%(%s" ~ ch ~ "%)", a);
	}
	///write a matrix
	void putarr(X)(in X a)
			if (isInputRange!X && isInputRange!(ElementType!X) && !isSomeString!(ElementType!X))
	{
		writefln("%(%(%s %)\n%)", a);
	}
	///get an array
	bool getarr(X)(X a, in size_t n)
	{
		bool b = 1;
		foreach (ref i; a[0 .. n])
			b = input(&i);
		return b;
	}
	///read without format
	bool input(T...)(ref T ptrs) if (ptrs.length > 0)
	{
		size_t s;
		foreach (ref e; ptrs)
		{
			if (isSomeChar!(Unqual!(typeof(e))))
				s += readf(" %c", &e);
			else
				s += readf(" %s", &e);
		}
		return s == ptrs.length;
	}
	///readln without format
	bool read(T...)(ref T ptrs) if (ptrs.length > 0)
	{
		size_t s;
		foreach (ref e; ptrs)
		{
			if (isSomeChar!(Unqual!(typeof(e))))
				s += readf(" %c", &e);
			else
				s += readf(" %s", &e);
		}
		readln;
		return s == ptrs.length;
	}
	///opening file
	nothrow auto inf(in char* name)
	{
		return freopen(name, "r", core.stdc.stdio.stdin);
	}
	///closing file
	nothrow auto ouf(in char* name)
	{
		return freopen(name, "w", core.stdc.stdio.stdout);
	}
	///parsing array from line
	@property auto arread(T)()
	{
		return readln.splitter.map!(to!(T)).array;
	}
	///outbuffer
	void enter(T...)(T args)
	{
		writeln(args);
		stdout.flush;
	}
}
//foreach_reverse isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold return static heapify join filter foreach
//------------------------------------------program beginning--------------------------

void main()
{
	version (home)
	{
		freopen("input.txt", "r", core.stdc.stdio.stdin);
		//freopen("output.txt", "w", core.stdc.stdio.stdout);
	}
	int n;
	loop: while (read(n))
	{
		auto a = arread!int;
		foreach (ref x; a)
		{
			x /= 100;
		}
		auto dp = new int[][n];
		dp[0] = new int[31];
		dp[0][] = int.max;
		dp[0][a[0] / 10] = a[0];
		foreach (int i; 1 .. n)
		{
			dp[i] = new int[31];
			dp[i][] = int.max;
			foreach (int j; 0 .. 31)
			{
				if (dp[i - 1][j] != int.max)
				{
					if (j + a[i] / 10 <= 30)
						dp[i][j + a[i] / 10] = min(dp[i][j + a[i] / 10], dp[i - 1][j] + a[i]);
					dp[i][max(0, j - a[i])] = min(dp[i][max(0, j - a[i])],
							dp[i - 1][j] + max(0, a[i] - j));
				}
			}
		}
		writeln(fold!(min)(dp[n - 1]) * 100);
	}
}

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

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

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

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

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

      auto ASum = new int[N + 1];
      foreach (i; 0 .. N) {
        ASum[i + 1] = ASum[i] + A[i];
      }

      int ans;
      foreach (i; 0 .. N + 1) {
        chmax(ans, min(ASum[i], 10 * (ASum[N] - ASum[i])));
      }

      /*
        |1
          22|22
      */
      foreach (i; 0 .. N) {
        if (A[i] == 1) {
          int j;
          for (j = i + 1; j < N && A[j] == 2; ++j) {}
          const s = j - (i + 1);
          foreach (t; 0 .. s + 1) {
            const a = min(ASum[i], 10);
            const score = a + min(ASum[i] - a + 2 * t, 20 * (s - t) + 10 * (ASum[N] - ASum[j]));
            chmax(ans, score);
          }
        }
      }
      /*
             1|
        22|22
      */
      foreach (i; 0 .. N) {
        if (A[i] == 1) {
          int j;
          for (j = i; j > 0 && A[j - 1] == 2; --j) {}
          debug {
            writeln("! ", j, " ", i);
          }
          const s = i - j;
          foreach (t; 0 .. s + 1) {
            const a = min(ASum[j] + 2 * t, 20 * (s - t));
            const score = a + min((ASum[j] + 2 * t) - a + 1, 10 * (ASum[N] - ASum[i + 1]));
            debug {
              writeln("  ", t, ": ", score);
            }
            chmax(ans, score);
          }
        }
      }

      debug {
        writeln("ans = ", ans);
      }
      writeln(1000L * ASum[N] - 100L * ans);

      debug {
        auto dp = new int[][](N + 1, 2 * N + 1);
        foreach (i; 0 .. N + 1) {
          dp[i][] = -1;
        }
        dp[0][0] = 0;
        foreach (i; 0 .. N) {
          foreach (j; 0 .. 2 * N + 1) {
            if (dp[i][j] >= 0) {
              // chmax(dp[i + 1][j + A[i]], dp[i][j] + A[i]);
              foreach (dj; 1 .. A[i] + 1) {
                chmax(dp[i + 1][j + dj], dp[i][j] + dj);
              }
              chmax(dp[i + 1][max(j - 10 * A[i], 0)], dp[i][j]);
            }
          }
        }
        foreach (i; 0 .. N + 1) {
          writeln(i, ": ", dp[i]);
        }
        assert(dp[N][0] == ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

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

      auto ASum = new int[N + 1];
      foreach (i; 0 .. N) {
        ASum[i + 1] = ASum[i] + A[i];
      }

      int ans;
      foreach (i; 0 .. N + 1) {
        chmax(ans, min(ASum[i], 10 * (ASum[N] - ASum[i])));
      }

      /*
        |1
          22|22
      */
      foreach (i; 0 .. N) {
        if (A[i] == 1) {
          int j;
          for (j = i + 1; j < N && A[j] == 2; ++j) {}
          const s = j - (i + 1);
          foreach (t; 0 .. 2 * s) {
            const a = min(ASum[i], 10);
            const score = a + min(ASum[i] - a + 2 * t, 20 * (s - t) + 10 * (ASum[N] - ASum[j]));
            chmax(ans, score);
          }
        }
      }
      /*
             1|
        22|22
      */
      foreach (i; 0 .. N) {
        if (A[i] == 1) {
          int j;
          for (j = i; j > 0 && A[j - 1] == 2; --j) {}
          const s = j - i;
          foreach (t; 0 .. 2 * s) {
            const a = min(ASum[j] + 2 * t, 20 * (s - t));
            const score = min((ASum[j] + 2 * t) - a + 1, 10 * (ASum[N] - ASum[i + 1]));
            chmax(ans, score);
          }
        }
      }

      debug {
        writeln("ans = ", ans);
      }
      writeln(1000L * ASum[N] - 100L * ans);

      debug {
        auto dp = new int[][](N + 1, 2 * N + 1);
        foreach (i; 0 .. N + 1) {
          dp[i][] = -1;
        }
        dp[0][0] = 0;
        foreach (i; 0 .. N) {
          foreach (j; 0 .. 2 * N + 1) {
            if (dp[i][j] >= 0) {
              // chmax(dp[i + 1][j + A[i]], dp[i][j] + A[i]);
              foreach (dj; 1 .. A[i] + 1) {
                chmax(dp[i + 1][j + dj], dp[i][j] + dj);
              }
              chmax(dp[i + 1][max(j - 10 * A[i], 0)], dp[i][j]);
            }
          }
        }
        foreach (i; 0 .. N + 1) {
          writeln(i, ": ", dp[i]);
        }
        assert(dp[N][0] == ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

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

      auto ASum = new int[N + 1];
      foreach (i; 0 .. N) {
        ASum[i + 1] = ASum[i] + A[i];
      }

      int ans;
      foreach (i; 0 .. N + 1) {
        chmax(ans, min(ASum[i], 10 * (ASum[N] - ASum[i])));
      }

      /*
        |1
          22|22
      */
      foreach (i; 0 .. N) {
        if (A[i] == 1) {
          int j;
          for (j = i + 1; j < N && A[j] == 2; ++j) {}
          const s = j - (i + 1);
          foreach (t; 0 .. 2 * s) {
            const a = min(ASum[i], 10);
            const score = a + min(ASum[i] - a + 2 * t, 20 * (s - t) + 10 * (ASum[N] - ASum[j]));
            chmax(ans, score);
          }
        }
      }
      /*
             1|
        22|22
      */
      foreach (i; 0 .. N) {
        if (A[i] == 1) {
          int j;
          for (j = i; j > 0 && A[j - 1] == 2; --j) {}
          const s = i - j;
          foreach (t; 0 .. 2 * s) {
            const a = min(ASum[j] + 2 * t, 20 * (s - t));
            const score = min((ASum[j] + 2 * t) - a + 1, 10 * (ASum[N] - ASum[i + 1]));
            chmax(ans, score);
          }
        }
      }

      debug {
        writeln("ans = ", ans);
      }
      writeln(1000L * ASum[N] - 100L * ans);

      debug {
        auto dp = new int[][](N + 1, 2 * N + 1);
        foreach (i; 0 .. N + 1) {
          dp[i][] = -1;
        }
        dp[0][0] = 0;
        foreach (i; 0 .. N) {
          foreach (j; 0 .. 2 * N + 1) {
            if (dp[i][j] >= 0) {
              // chmax(dp[i + 1][j + A[i]], dp[i][j] + A[i]);
              foreach (dj; 1 .. A[i] + 1) {
                chmax(dp[i + 1][j + dj], dp[i][j] + dj);
              }
              chmax(dp[i + 1][max(j - 10 * A[i], 0)], dp[i][j]);
            }
          }
        }
        foreach (i; 0 .. N + 1) {
          writeln(i, ": ", dp[i]);
        }
        assert(dp[N][0] == ans);
      }
    }
  } catch (EOFException e) {
  }
}

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

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

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

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

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

      auto ASum = new int[N + 1];
      foreach (i; 0 .. N) {
        ASum[i + 1] = ASum[i] + A[i];
      }

      int ans;
      foreach (i; 0 .. N + 1) {
        chmax(ans, min(ASum[i], 10 * (ASum[N] - ASum[i])));
      }

      /*
        |1
          22|22
      */
      foreach (i; 0 .. N) {
        if (A[i] == 1) {
          int j;
          for (j = i + 1; j < N && A[j] == 2; ++j) {}
          const s = j - (i + 1);
          foreach (t; 0 .. 2 * s) {
            const a = min(ASum[i], 10);
            const score = a + min(ASum[i] - a + 2 * t, 20 * (s - t) + 10 * (ASum[N] - ASum[j]));
            chmax(ans, score);
          }
        }
      }
      /*
             1|
        22|22
      */
      foreach (i; 0 .. N) {
        if (A[i] == 1) {
          int j;
          for (j = i; j > 0 && A[j - 1] == 2; --j) {}
          const s = j - (i + 1);
          foreach (t; 0 .. 2 * s) {
            const a = min(ASum[j] + 2 * t, 20 * (s - t));
            const score = min((ASum[j] + 2 * t) - a + 1, 10 * (ASum[N] - ASum[i + 1]));
            chmax(ans, score);
          }
        }
      }

      debug {
        writeln("ans = ", ans);
      }
      writeln(1000L * ASum[N] - 100L * ans);

      debug {
        auto dp = new int[][](N + 1, 2 * N + 1);
        foreach (i; 0 .. N + 1) {
          dp[i][] = -1;
        }
        dp[0][0] = 0;
        foreach (i; 0 .. N) {
          foreach (j; 0 .. 2 * N + 1) {
            if (dp[i][j] >= 0) {
              // chmax(dp[i + 1][j + A[i]], dp[i][j] + A[i]);
              foreach (dj; 1 .. A[i] + 1) {
                chmax(dp[i + 1][j + dj], dp[i][j] + dj);
              }
              chmax(dp[i + 1][max(j - 10 * A[i], 0)], dp[i][j]);
            }
          }
        }
        foreach (i; 0 .. N + 1) {
          writeln(i, ": ", dp[i]);
        }
        assert(dp[N][0] == ans);
      }
    }
  } catch (EOFException e) {
  }
}


import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

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

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

alias Spell1 = Tuple!(int, `manacost`, int, `newTime`);
alias Spell2 = Tuple!(int, `manacost`, int, `handicap`);

int n, m, k;
int baseTime, manapool;
Spell1[200_000] _spells1;
Spell2[200_000] _spells2;
Spell1[ ] spells1;
Spell2[ ] spells2;
int[200_000] _maxHandicap;
int[ ] maxHandicap;

long check(int mana, int time) {
    int left = 0, right = k;
    while (left != right) {
        int mid = (left + right) >>> 1;
        if (mana < spells2[mid].manacost)
            right = mid;
        else
            left = mid + 1;
    }
    return (left? n - maxHandicap[left - 1] : n) * cast(long)time;
}

void main() {
    while (read(&n, &m, &k, &baseTime, &manapool)) {
        spells1 = _spells1[0 .. m];
        spells2 = _spells2[0 .. k];
        maxHandicap = _maxHandicap[0 .. k];
        foreach (ref sp; spells1)
            read(&sp.newTime);
        foreach (ref sp; spells1)
            read(&sp.manacost);
        foreach (ref sp; spells2)
            read(&sp.handicap);
        foreach (ref sp; spells2)
            read(&sp.manacost);
        int t = 0;
        foreach (ref sp, ref b; lockstep(spells2, maxHandicap))
            b = t = max(t, sp.handicap);
        long result = check(manapool, baseTime);
        foreach (ref sp; spells1)
            if (sp.manacost <= manapool)
                result = min(result, check(manapool - sp.manacost, sp.newTime));
        writeln(result);
    }
}

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.range;
import std.range.primitives;
import std.conv;

struct spell {
    int pnt;
    int eff;
}

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

    int n, m, k;
    readf(" %s %s %s\n", &n, &m, &k);
    int x, s;
    readf(" %s %s\n", &x, &s);
    spell[] t1 = new spell[m+1];
    spell[] t2 = new spell[k+1];
    t1[0].pnt = 0;
    t1[0].eff = x;
    t2[0].pnt = 0;
    t2[0].eff = 0;
    foreach ( i; 1 .. m+1 ) {
        readf(" %s", &t1[i].eff);
    }
    readf("\n");
    foreach ( i; 1 .. m+1 ) {
        readf(" %s", &t1[i].pnt);
    }
    foreach ( i; 1 .. k+1 ) {
        readf(" %s", &t2[i].eff);
    }
    readf("\n");
    foreach ( i; 1 .. k+1 ) {
        readf(" %s", &t2[i].pnt);
    }
    readf("\n");

    long answer = long.max;
    int pntsAvail = s;
    long poTime = x;
    spell dummySpell;
    auto t2as = assumeSorted!"a.pnt < b.pnt"(t2);
    foreach ( s1; t1 ) {
        pntsAvail = s - s1.pnt;
        if (pntsAvail < 0) continue;
        poTime = s1.eff;
        dummySpell.pnt = pntsAvail;
        auto idx = k - t2as.upperBound(dummySpell).length;
        long toMake = max(0, n - t2[idx].eff);
        answer = min(answer, toMake * poTime);
    }
    writeln(answer);

    return 0;
}

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.range;
import std.range.primitives;
import std.conv;

struct spell {
    int pnt;
    int eff;
}

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

    int n, m, k;
    readf(" %s %s %s\n", &n, &m, &k);
    int x, s;
    readf(" %s %s\n", &x, &s);
    spell[] t1 = new spell[m+1];
    spell[] t2 = new spell[k+1];
    t1[0].pnt = 0;
    t1[0].eff = x;
    t2[0].pnt = 0;
    t2[0].eff = 0;
    foreach ( i; 1 .. m+1 ) {
        readf(" %s", &t1[i].eff);
    }
    readf("\n");
    foreach ( i; 1 .. m+1 ) {
        readf(" %s", &t1[i].pnt);
    }
    foreach ( i; 1 .. k+1 ) {
        readf(" %s", &t2[i].eff);
    }
    readf("\n");
    foreach ( i; 1 .. k+1 ) {
        readf(" %s", &t2[i].pnt);
    }
    readf("\n");

    long answer = long.max;
    int pntsAvail = s;
    long poTime = x;
    spell dummySpell;
    auto t2as = assumeSorted!"a.pnt < b.pnt"(t2);
    foreach ( s1; t1 ) {
        pntsAvail = s - s1.pnt;
        if (pntsAvail < 0) continue;
        poTime = s1.eff;
        dummySpell.pnt = pntsAvail;
        auto idx = t2as.lowerBound(dummySpell).length;
        while (idx < t2.length && t2[idx].pnt <= pntsAvail) ++idx;
        if (idx > 0) --idx;
        long toMake = max(0, n - t2[idx].eff);
        answer = min(answer, toMake * poTime);
    }
    writeln(answer);

    return 0;
}

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.range;
import std.range.primitives;
import std.conv;

struct spell {
    int pnt;
    int eff;
}

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

    int n, m, k;
    readf(" %s %s %s\n", &n, &m, &k);
    int x, s;
    readf(" %s %s\n", &x, &s);
    spell[] t1 = new spell[m+1];
    spell[] t2 = new spell[k+1];
    t1[0].pnt = 0;
    t1[0].eff = x;
    t2[0].pnt = 0;
    t2[0].eff = 0;
    foreach ( i; 1 .. m+1 ) {
        readf(" %s", &t1[i].eff);
    }
    readf("\n");
    foreach ( i; 1 .. m+1 ) {
        readf(" %s", &t1[i].pnt);
    }
    foreach ( i; 1 .. k+1 ) {
        readf(" %s", &t2[i].eff);
    }
    readf("\n");
    foreach ( i; 1 .. k+1 ) {
        readf(" %s", &t2[i].pnt);
    }
    readf("\n");

    long answer = long.max;
    int pntsAvail = s;
    long poTime = x;
    foreach ( s1; t1 ) {
        pntsAvail = s - s1.pnt;
        if (pntsAvail < 0) continue;
        poTime = s1.eff;
        int lo = 0, hi = k;
        while (lo < hi) {
            int mid = (lo + hi) / 2;
            if (pntsAvail < t2[mid].pnt) hi = mid;
            else lo = mid + 1;
        }
        if (pntsAvail < t2[lo].pnt) --lo;
        long toMake = max(0, n - t2[lo].eff);
        answer = min(answer, toMake * poTime);
    }
    writeln(answer);

    return 0;
}

import std.stdio;
import std.algorithm.comparison;
import std.algorithm.sorting;
import std.range;
import std.range.primitives;
import std.conv;

struct spell {
    int pnt;
    int eff;
}

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

    int n, m, k;
    readf(" %s %s %s\n", &n, &m, &k);
    int x, s;
    readf(" %s %s\n", &x, &s);
    spell[] t1 = new spell[m+1];
    spell[] t2 = new spell[k+1];
    t1[0].pnt = 0;
    t1[0].eff = x;
    t2[0].pnt = 0;
    t2[0].eff = 0;
    foreach ( i; 1 .. m+1 ) {
        readf(" %s", &t1[i].eff);
    }
    readf("\n");
    foreach ( i; 1 .. m+1 ) {
        readf(" %s", &t1[i].pnt);
    }
    foreach ( i; 1 .. k+1 ) {
        readf(" %s", &t2[i].eff);
    }
    readf("\n");
    foreach ( i; 1 .. k+1 ) {
        readf(" %s", &t2[i].pnt);
    }
    readf("\n");

    int answer = int.max;
    int pntsAvail = s;
    int poTime = x;
    spell dummySpell;
    auto t2as = assumeSorted!"a.pnt < b.pnt"(t2);
    foreach ( s1; t1 ) {
        pntsAvail = s - s1.pnt;
        if (pntsAvail < 0) continue;
        poTime = s1.eff;
        dummySpell.pnt = pntsAvail;
        auto idx = t2as.lowerBound(dummySpell).length;
        while (idx < t2.length && t2[idx].pnt <= pntsAvail) ++idx;
        if (idx > 0) --idx;
        int toMake = max(0, n - t2[idx].eff);
        answer = min(answer, toMake * poTime);
    }
    writeln(answer);

    return 0;
}

import core.bitop;
import core.checkedint;
import core.simd;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.complex;
import std.container;
import std.conv;
import std.datetime;
import std.format;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

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

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

struct Spell1 {
    int manacost, newTime;
}

struct Spell2 {
    int manacost, handicap;
}

int n, m, k;
int baseTime, manapool;
Spell1[200_000] _spells1;
Spell2[200_000] _spells2;
Spell1[ ] spells1;
Spell2[ ] spells2;
int[200_000] _maxHandicap;
int[ ] maxHandicap;

long check(int mana, int time) {
    int left = 0, right = k;
    while (left != right) {
        int mid = (left + right) >>> 1;
        if (mana < spells2[mid].manacost)
            right = mid;
        else
            left = mid + 1;
    }
    return (left? (n - maxHandicap[left - 1]) : n) * cast(long)time;
}

void main() {
    while (read(&n, &m, &k, &baseTime, &manapool)) {
        spells1 = _spells1[0 .. m];
        spells2 = _spells2[0 .. k];
        maxHandicap = _maxHandicap[0 .. m];
        foreach (ref sp; spells1)
            read(&sp.newTime);
        foreach (ref sp; spells1)
            read(&sp.manacost);
        foreach (ref sp; spells2)
            read(&sp.handicap);
        foreach (ref sp; spells2)
            read(&sp.manacost);
        int t = 0;
        foreach (ref sp, ref b; lockstep(spells2, maxHandicap))
            b = t = max(t, sp.handicap);
        long result = check(manapool, baseTime);
        foreach (ref sp; spells1)
            if (sp.manacost <= manapool)
                result = min(result, check(manapool - sp.manacost, sp.newTime));
        writeln(result);
    }
}


import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!long;

void main() {
    GC.disable();

    long n, m;
    readf(" %s %s", n, m);

    auto b = new long[to!int(n)];
    auto g = new long[to!int(m)];

    foreach(i;0 .. n) readf(" %s", b[to!int(i)]);
    foreach(i;0 .. m) readf(" %s", g[to!int(i)]);

    long ans = -1;
    if  (b.maxElement > g.minElement) {
      ans = -1;
    } else if (g.minElement > b.maxElement) {
      sort(b);
      long tt = sum(g) + sum(b) * m - b[$-1]*(m-1) - b[$-2];
      ans = tt;
    } else {
      long ss = sum(b);
      long tt = 0;
      auto tree = new Tree(b);
      foreach(gg; g) {
        auto rr = tree.lowerBound(gg+1);
        tt = tt + (ss - rr.back() + gg);
      }

      ans = tt;

    }

    writeln(ans);

}

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

void main()
{
    auto nm = readln.split.to!(int[]);
    auto N = nm[0];
    auto M = nm[1];
    auto BS = readln.split.to!(long[]);
    auto GS = readln.split.to!(long[]);

    long ret;
    foreach (b; BS) {
        ret += b * M;
    }
    sort!"a > b"(BS);
    int c;
    sort!"a < b"(GS);
    foreach (g; GS) {
        if (g < BS[0]) {
            writeln("-1");
            return;
        }
        if (g == BS[0]) {
            continue;
        }
        if (c == M-1) {
            ret += g - BS[1];
        } else {
            ++c;
            ret += g - BS[0];
        }
    }
    writeln(ret);
}

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

void main()
{
    auto nm = readln.split.to!(int[]);
    auto N = nm[0];
    auto M = nm[1];
    auto BS = readln.split.to!(long[]);
    auto GS = readln.split.to!(long[]);

    long ret;
    foreach (b; BS) {
        ret += b * M;
    }
    sort!"a < b"(BS);
    int[] uc;
    uc.length = N;
    foreach (g; GS) {
        if (g < BS[$-1]) {
            writeln("-1");
            return;
        }
        size_t l, r = N-1;
        while (l+1 != r) {
            auto m = (l+r)/2;
            if (BS[m] <= g) {
                l = m;
            } else {
                r = m;
            }
        }
        if (r <= g) l = r;
        if (l == g) continue;
        if (uc[l] == M-1) {
            if (l == 0) {
                writeln("-1");
                return;
            }
            --l;
        }
        ++uc[l];
        ret += g - BS[l];
    }
    writeln(ret);
}

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

void main()
{
    auto nm = readln.split.to!(int[]);
    auto N = nm[0];
    auto M = nm[1];
    auto BS = readln.split.to!(long[]);
    auto GS = readln.split.to!(long[]);

    long ret;
    foreach (b; BS) {
        ret += b * M;
    }
    sort!"a > b"(BS);
    int c;
    sort!"a < b"(GS);
    long prev = -1;
    foreach (g; GS) {
        if (g == prev) continue;
        prev = g;
        if (g < BS[0]) {
            writeln("-1");
            return;
        }
        if (g == BS[0]) {
            continue;
        }
        if (c == M-1) {
            ret += g - BS[1];
        } else {
            ++c;
            ret += g - BS[0];
        }
    }
    writeln(ret);
}

import std.stdio : writef, readf, readln, writeln, writefln;
import std.array : array, split;
import std.algorithm;
import std.conv : to;
import std.range : iota, tee;
import std.algorithm.comparison;
import std.container.rbtree : RBT = RedBlackTree;
import std.string : strip;
import core.memory : GC;
import std.typecons : tuple;

alias Tree = RBT!int;

void main() {
    GC.disable();

    int n, m;
    readf(" %s %s", n, m);

    auto b = new int[n];
    auto g = new int[m];

    foreach(i;0 .. n) readf(" %s", b[i]);
    foreach(i;0 .. m) readf(" %s", g[i]);

    int ans = -1;
    if  (b.maxElement > g.minElement) {
      ans = -1;
    } else if (g.minElement > b.maxElement) {
      sort(b);
      int tt = sum(g) + sum(b) * m - b[$-1]*(m-1) - b[$-2];
      ans = tt;
    } else {
      int ss = sum(b);
      int tt = 0;
      auto tree = new Tree(b);
      foreach(gg; g) {
        auto rr = tree.lowerBound(gg+1);
        tt = tt + (ss - rr.back() + gg);
      }

      ans = tt;

    }

    writeln(ans);

}


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

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

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

    auto arr = readln.chomp.split.map!(to!int).map!(x => x-1).array;

    auto g = new int[][] (n);
    foreach (_; 0 .. m) {
        int u, v;
        readf("%s %s", &u, &v);
        readln;

        --u, --v;
        g[v] ~= u;
    }

    auto cnt = new int[] (n);
    foreach (u; g[arr.back]) { cnt[u] += 1; }

    int ans = 0, needToBypass = 1;
    foreach_reverse (e; arr.dropBackOne) {
        debug { writeln(e, ' ', cnt[e], ' ', needToBypass); }

        if (cnt[e] == needToBypass) { ++ans; }
        else {
            ++needToBypass;
            foreach (u; g[e]) { ++cnt[u]; }
        }
    }

    ans.writeln;
}

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

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
}

void main() {
  auto r = new InputReader;
  immutable int n = r.next!uint;
  immutable int m = r.next!uint;
  auto p = uninitializedArray!(int[]) (n);
  auto pos = uninitializedArray!(int[]) (n + 1);
  foreach (i; 0 .. n) {
    p[i] = r.next!uint;
    pos[p[i]] = i;
  }
  auto e = new int[][n+1];
  foreach (edgeid; 0 .. m) {
    immutable i = r.next!uint;
    immutable j = r.next!uint;
    e[i] ~= j;
  }
  debug stderr.writeln (e);
  int res;
  auto d = new bool[n+1];
  int l = 1;
  foreach_reverse (i; 0 .. n - 1) {
    int cnt;
    immutable pi = p[i];
    immutable pk = pos[pi];
    foreach (j; e[pi]) {
      if (!d[j] && pk < pos[j]) ++cnt;
    }
    debug stderr.writeln (cnt, ' ', l);
    if (cnt == l) {
      ++res;
      d[pi] = true;
    } else {
      ++l;
    }
  }
  write (res);
}

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

class InputReader {
  private:
  ubyte[] p;
  ubyte[] buffer;
  size_t cur;
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
    p = stdin.rawRead (buffer);
  }
  final ubyte skipByte (ubyte lo) {
    while (true) {
      auto a = p[cur .. $];
      auto r = a.find! (c => c >= lo);
      if (!r.empty) {
        cur += a.length - r.length;
        return p[cur++];
      }
      p = stdin.rawRead (buffer);
      cur = 0;
      if (p.empty) return 0;
    }
  }
  final ubyte nextByte () {
    if (cur < p.length) {
       return p[cur++];
    }
    p = stdin.rawRead (buffer);
    if (p.empty) return 0;
    cur = 1;
    return p[0];
  }
  template next(T) if (isUnsigned!T) {
    final T next () {
      T res = skipByte (48) - 48;
      while (true) {
        ubyte b = nextByte ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
}

void main() {
  auto r = new InputReader;
  immutable int n = r.next!uint;
  immutable int m = r.next!uint;
  auto p = uninitializedArray!(int[]) (n);
  auto pos = uninitializedArray!(int[]) (n + 1);
  foreach (i; 0 .. n) {
    p[i] = r.next!uint;
    pos[p[i]] = i;
  }
  auto c = new int[n+1];
  foreach (edge_id; 0 .. m) {
    immutable i = r.next!uint;
    immutable j = r.next!uint;
    if (pos[i] < pos[j]) ++c[i];
  }
  int res;
  debug stderr.writeln (c[1..$]);
  foreach_reverse (i; 0 .. n - 1) {
    debug stderr.writeln (c[p[i]], ' ', n - i - 1);
    if (c[p[i]] == n - i - 1) ++res;
  }
  write (res);
}


// problem: http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_3_A
// require: graph/articulation_points.d

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;

//LRDU

bool solve2(int a, int b, int x1, int x2) {
    if (x1 == 0 && x2 == 0) {
        return a == 0 && b == 0;
    } else if (a == b) {
        return true;
    } else if (a > b) {
        return abs(x1) >= a - b;
    } else {
        return abs(x2) >= b - a;
    }
}

void solve(int T) {
    while (T--) {
        auto s = readln.split.map!(to!int);
        auto A = s[0];
        auto B = s[1];
        auto C = s[2];
        auto D = s[3];
        s = readln.split.map!(to!int);
        auto X = s[0];
        auto Y = s[1];
        auto x1 = s[2] - X;
        auto y1 = s[3] - Y;
        auto x2 = s[4] - X;
        auto y2 = s[5] - Y;
        auto AB = A - B;
        auto ans = solve2(A, B, x1, x2) && solve2(C, D, y1, y2);
        writeln(ans ? "Yes" : "No");
    }
}

void main() {
    auto T = readln.chomp.to!int;
    solve(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) { x.modm(y.modpow(mod - 2)); }

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (ti; 0..t)
	{
		auto abcd = RDA;
		auto x = RD;
		auto y = RD;
		auto x1 = RD;
		auto y1 = RD;
		auto x2 = RD;
		auto y2 = RD;

		bool check(long pos, long l, long r, long dl, long dr)
		{
			auto d = dr - dl;
			if (!inside(pos+d, l, r+1)) return false;
			if (dl != 0 || dr != 0)
			{
				if (pos == l && pos == r) return false;
			}
			return true;
		}
		ans[ti] = check(x, x1, x2, abcd[0], abcd[1]) && check(y, y1, y2, abcd[2], abcd[3]);
	}

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


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

void main ()
{
	int n, t;
	while (readf (" %s %s", &n, &t) > 0)
	{
		readln;
		auto s = readln.strip.dup;
		int i = 0;
		while (s[i] != '.')
		{
			i += 1;
		}
		int pre = i;
		s = s[0..i] ~ s[i + 1..$];
		n -= 1;
		while (i < n)
		{
			if (s[i] >= '5')
			{
				int j = i - 1;
				while (j >= pre && i - j < t && s[j] >= '4')
				{
					j -= 1;
				}
				while (j > 0 && s[j] == '9')
				{
					s[j] = '0';
					j -= 1;
				}
				if (s[j] == '9')
				{
					s[j] = '0';
					s = s[0..j + 1];
					s = '1' ~ s;
					pre += 1;
				}
				else
				{
					s[j] += 1;
					s = s[0..j + 1];
				}
				break;
			}
			i += 1;
		}
		while (s.length < pre)
		{
			s ~= '0';
		}
		while (s.length > pre && s[$ - 1] == '0')
		{
			s.length -= 1;
		}
		if (s.length > pre)
		{
			s = s[0..pre] ~ '.' ~ s[pre..$];
		}
		writeln (s);
	}
}

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

/// custom bigint
struct BigInt {
    ///value
    int[] value = [0];
    ///init
    this(string s) {
        value = [];
        foreach(char sym; s) {
            value ~= sym - '0';
        }
    }
    ///to_string
    string to_string() {
        string s = "";
        foreach(int sym; value) {
            s ~= sym.to!string();
        }
        return s;
    }
    ///plus_one
    void plus_one() {
        value[$ - 1] += 1;
        foreach_reverse(int idx; 1 .. value.length) {
            if (value[idx] == 10) {
                value[idx] = 0;
                value[idx - 1] += 1;
            }
        }
        if (value[0] == 10) {
            value[0] = 0;
            value = [1] ~ value;
        }
    }
}
unittest {
    BigInt b;
    foreach(int i; 0 .. 10) {
        b.plus_one();
        assert(b.value == [i + 1]);
        assert(b.to_string() == (i + 1).to!string());
    }
    //from_string
    b = BigInt("1234567890");
    assert(b.value == [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);
    //to_string
    assert(b.to_string() == "1234567890");

    // plus_one
    foreach(int i; 0 .. 100) {
        b.plus_one();
        int curr_val = 1_234_567_890 + i + 1;
        BigInt c = BigInt(curr_val.to!string());
        assert(b.value == c.value);
    }
}

///solve
void solve() {
    int n, t;
    readf(" %s %s\n", &n, &t);
    auto grade = split(readln().strip(), '.');
    int len = n - 1 - grade[0].length;
    BigInt base = BigInt(grade[0]);
    debug {
        len.writeln();
        grade.writeln();
        writeln(base.value);
    }
    int[] tail;
    foreach(int idx; 0 .. len) {
        tail ~= grade[1][idx] - '0';
    }
    // tail.writeln();
    len = tail.length;
    int replaces = 0;
    foreach(int idx; 0 .. len) {
        if (tail[idx] > 4) {
            if (idx == 0) {
                base.plus_one();
                len = 0;
                replaces++;
                break;
            }
            else {
                tail[idx - 1] += 1;
                len = idx;
                replaces++;
                break;
            }
        }
    }
    while (true) {
        bool flag = false;
        if (replaces >= t) {
            break;
        }
        foreach_reverse(int idx; 0 .. len) {
            debug writeln(idx);
            if (tail[idx] > 4) {
                if (idx == 0) {
                    base.plus_one();
                    len = 0;
                    replaces++;
                    break;
                }
                else {
                    tail[idx - 1] += 1;
                    len = idx;
                    flag = true;
                    replaces++;
                    break;
                }
            }
        }
        if (!flag) {
            break;
        }
    }
    string ans = "";
    write(base.to_string());
    if (len > 0) {
        ans ~= '.';
    }
    foreach(int x; 0 .. len) {
        ans ~= tail[x].to!string;
    }
    writeln(ans);
}
void main() {
    debug {
        char[200_000] x = '9';
        string a = x.dup;
        BigInt b = BigInt(a);
        "b".writeln();
        b.plus_one();
        "b + 1".writeln;
    }

    solve();
}

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

///solve
void solve() {
    int n, t;
    readf(" %s %s\n", &n, &t);
    auto grade = split(readln().strip(), '.');
    int len = n - 1 - grade[0].length;
    BigInt base = grade[0].to!BigInt;
    debug {
        len.writeln();
        grade.writeln();
        base.writeln();
    }
    int[] tail;
    foreach(int idx; 0 .. len) {
        tail ~= grade[1][idx] - '0';
    }
    // tail.writeln();
    len = tail.length;
    int replaces = 0;
    foreach(int idx; 0 .. len) {
        if (tail[idx] > 4) {
            if (idx == 0) {
                base += 1;
                len = 0;
                replaces++;
                break;
            }
            else {
                tail[idx - 1] += 1;
                len = idx;
                replaces++;
                break;
            }
        }
    }
    if (n == 200_000) {
        return;
    }
    while (true) {
        bool flag = false;
        if (replaces >= t) {
            break;
        }
        foreach_reverse(int idx; 0 .. len) {
            debug writeln(idx);
            if (tail[idx] > 4) {
                if (idx == 0) {
                    base += 1;
                    len = 0;
                    replaces++;
                    break;
                }
                else {
                    tail[idx - 1] += 1;
                    len = idx;
                    flag = true;
                    replaces++;
                    break;
                }
            }
        }
        if (!flag) {
            break;
        }
    }
    write(base);
    if (len > 0) {
        write('.');
    }
    foreach(int x; 0 .. len) {
        write(tail[x]);
    }
    writeln();
}
void main() {
    debug {
        char[200_000] x = '9';
        string a = x.dup;
        BigInt b = a.to!BigInt;
        "b".writeln();
        b += 1;
        "b + 1".writeln;
    }

    solve();
}

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

///solve
void solve() {
    int n, t;
    readf(" %s %s\n", &n, &t);
    auto grade = split(readln().strip(), '.');
    int len = n - 1 - grade[0].length;
    BigInt base = grade[0].to!BigInt;
    debug {
        len.writeln();
        grade.writeln();
        base.writeln();
    }
    int[] tail;
    foreach(int idx; 0 .. len) {
        tail ~= grade[1][idx] - '0';
    }
    // tail.writeln();
    len = tail.length;
    int replaces = 0;
    foreach(int idx; 0 .. len) {
        if (tail[idx] > 4) {
            if (idx == 0) {
                base += 1;
                len = 0;
                replaces++;
                break;
            }
            else {
                tail[idx - 1] += 1;
                len = idx;
                replaces++;
                break;
            }
        }
    }
    while (true) {
        bool flag = false;
        if (replaces >= t) {
            break;
        }
        foreach_reverse(int idx; 0 .. len) {
            debug writeln(idx);
            if (tail[idx] > 4) {
                if (idx == 0) {
                    base += 1;
                    len = 0;
                    replaces++;
                    break;
                }
                else {
                    tail[idx - 1] += 1;
                    len = idx;
                    flag = true;
                    replaces++;
                    break;
                }
            }
        }
        if (!flag) {
            break;
        }
    }
    if (n == 200_000) {
        return;
    }
    string ans = base.to!string;
    if (len > 0) {
        ans ~= '.';
    }
    foreach(int x; 0 .. len) {
        ans ~= tail[x].to!string;
    }
    writeln(ans);
}
void main() {
    debug {
        char[200_000] x = '9';
        string a = x.dup;
        BigInt b = a.to!BigInt;
        "b".writeln();
        b += 1;
        "b + 1".writeln;
    }

    solve();
}

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

///solve
void solve() {
    int n, t;
    readf(" %s %s\n", &n, &t);
    auto grade = split(readln().strip(), '.');
    int len = n - 1 - grade[0].length;
    BigInt base = grade[0].to!BigInt;
    len.writeln();
    grade.writeln();
    base.writeln();
    int[] tail;
    foreach(int idx; 0 .. len) {
        tail ~= grade[1][idx] - '0';
    }
    // tail.writeln();
    len = tail.length;
    int replaces = 0;
    foreach(int idx; 0 .. len) {
        if (tail[idx] > 4) {
            if (idx == 0) {
                base += 1;
                len = 0;
                replaces++;
                break;
            }
            else {
                tail[idx - 1] += 1;
                len = idx;
                replaces++;
                break;
            }
        }
    }
    if (n == 200_000) {
        return;
    }
    while (true) {
        bool flag = false;
        if (replaces >= t) {
            break;
        }
        foreach_reverse(int idx; 0 .. len) {
            debug writeln(idx);
            if (tail[idx] > 4) {
                if (idx == 0) {
                    base += 1;
                    len = 0;
                    replaces++;
                    break;
                }
                else {
                    tail[idx - 1] += 1;
                    len = idx;
                    flag = true;
                    replaces++;
                    break;
                }
            }
        }
        if (!flag) {
            break;
        }
    }
    write(base);
    if (len > 0) {
        write('.');
    }
    foreach(int x; 0 .. len) {
        write(tail[x]);
    }
    writeln();
}
void main() {
    debug {
        char[200_000] x = '9';
        string a = x.dup;
        BigInt b = a.to!BigInt;
        "b".writeln();
        b += 1;
        "b + 1".writeln;
    }

    solve();
}

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

///solve
void solve() {
    int n, t;
    readf(" %s %s\n", &n, &t);
    auto grade = split(readln().strip(), '.');
    int len = n - 1 - grade[0].length;
    BigInt base = grade[0].to!BigInt;
    debug {
        len.writeln();
        grade.writeln();
        base.writeln();
    }
    int[] tail;
    foreach(int idx; 0 .. len) {
        tail ~= grade[1][idx] - '0';
    }
    // tail.writeln();
    len = tail.length;
    int replaces = 0;
    foreach(int idx; 0 .. len) {
        if (tail[idx] > 4) {
            if (idx == 0) {
                base += 1;
                len = 0;
                replaces++;
                break;
            }
            else {
                tail[idx - 1] += 1;
                len = idx;
                replaces++;
                break;
            }
        }
    }
    while (true) {
        bool flag = false;
        if (replaces >= t) {
            break;
        }
        foreach_reverse(int idx; 0 .. len) {
            debug writeln(idx);
            if (tail[idx] > 4) {
                if (idx == 0) {
                    base += 1;
                    len = 0;
                    replaces++;
                    break;
                }
                else {
                    tail[idx - 1] += 1;
                    len = idx;
                    flag = true;
                    replaces++;
                    break;
                }
            }
        }
        if (!flag) {
            break;
        }
    }
    if (n == 200_000) {
        return;
    }
    write(base);
    if (len > 0) {
        write('.');
    }
    foreach(int x; 0 .. len) {
        write(tail[x]);
    }
    writeln();
}
void main() {
    debug {
        char[200_000] x = '9';
        string a = x.dup;
        BigInt b = a.to!BigInt;
        "b".writeln();
        b += 1;
        "b + 1".writeln;
    }

    solve();
}

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

///solve
void solve() {
    int n, t;
    readf(" %s %s\n", &n, &t);
    auto grade = split(readln().strip(), '.');
    int len = n - 1 - grade[0].length;
    BigInt base = grade[0].to!BigInt;
    debug {
        len.writeln();
        grade.writeln();
        base.writeln();
    }
    int[] tail;
    foreach(int idx; 0 .. len) {
        tail ~= grade[1][idx] - '0';
    }
    // tail.writeln();
    len = tail.length;
    int replaces = 0;
    foreach(int idx; 0 .. len) {
        if (tail[idx] > 4) {
            if (idx == 0) {
                base += 1;
                len = 0;
                replaces++;
                break;
            }
            else {
                tail[idx - 1] += 1;
                len = idx;
                replaces++;
                break;
            }
        }
    }
    while (true) {
        bool flag = false;
        if (replaces >= t) {
            break;
        }
        foreach_reverse(int idx; 0 .. len) {
            debug writeln(idx);
            if (tail[idx] > 4) {
                if (idx == 0) {
                    base += 1;
                    len = 0;
                    replaces++;
                    break;
                }
                else {
                    tail[idx - 1] += 1;
                    len = idx;
                    flag = true;
                    replaces++;
                    break;
                }
            }
        }
        if (!flag) {
            break;
        }
    }
    string ans = base.to!string;
    if (len > 0) {
        ans ~= '.';
    }
    foreach(int x; 0 .. len) {
        ans ~= tail[x];
    }
    writeln(ans);
}
void main() {
    debug {
        char[200_000] x = '9';
        string a = x.dup;
        BigInt b = a.to!BigInt;
        "b".writeln();
        b += 1;
        "b + 1".writeln;
    }

    solve();
}

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

/// custom bigint
struct BigInt {
    ///value
    int[] value = [0];
    ///init
    this(string s) {
        value = [];
        foreach(char sym; s) {
            value ~= sym - '0';
        }
    }
    ///to_string
    string to_string() {
        string s = "";
        foreach(int sym; value) {
            s ~= sym.to!string();
        }
        return s;
    }
    ///plus_one
    void plus_one() {
        value[$ - 1] += 1;
        foreach_reverse(int idx; 1 .. value.length) {
            if (value[idx] == 10) {
                value[idx] = 0;
                value[idx - 1] += 1;
            }
        }
        if (value[0] == 10) {
            value[0] = 0;
            value = [1] ~ value;
        }
    }
}
unittest {
    BigInt b;
    foreach(int i; 0 .. 10) {
        b.plus_one();
        assert(b.value == [i + 1]);
        assert(b.to_string() == (i + 1).to!string());
    }
    //from_string
    b = BigInt("1234567890");
    assert(b.value == [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);
    //to_string
    assert(b.to_string() == "1234567890");

    // plus_one
    foreach(int i; 0 .. 100) {
        b.plus_one();
        int curr_val = 1_234_567_890 + i + 1;
        BigInt c = BigInt(curr_val.to!string());
        assert(b.value == c.value);
    }
}

///solve
void solve() {
    int n, t;
    readf(" %s %s\n", &n, &t);
    auto grade = split(readln().strip(), '.');
    int len = n - 1 - grade[0].length;
    BigInt base = BigInt(grade[0]);
    debug {
        len.writeln();
        grade.writeln();
        writeln(base.value);
    }
    int[] tail;
    foreach(int idx; 0 .. len) {
        tail ~= grade[1][idx] - '0';
    }
    // tail.writeln();
    len = tail.length;
    int replaces = 0;
    foreach(int idx; 0 .. len) {
        if (tail[idx] > 4) {
            if (idx == 0) {
                base.plus_one();
                len = 0;
                replaces++;
                break;
            }
            else {
                tail[idx - 1] += 1;
                len = idx;
                replaces++;
                break;
            }
        }
    }
    while (true) {
        bool flag = false;
        if (replaces >= t) {
            break;
        }
        foreach_reverse(int idx; 0 .. len) {
            debug writeln(idx);
            if (tail[idx] > 4) {
                if (idx == 0) {
                    base.plus_one();
                    len = 0;
                    replaces++;
                    break;
                }
                else {
                    tail[idx - 1] += 1;
                    len = idx;
                    flag = true;
                    replaces++;
                    break;
                }
            }
        }
        if (!flag) {
            break;
        }
    }
    string ans = "";
    write(base.to_string());
    if (n == 200_000) {
        return;
    }
    if (len > 0) {
        ans ~= '.';
    }
    foreach(int x; 0 .. len) {
        ans ~= tail[x].to!string;
    }
    writeln(ans);
}
void main() {
    debug {
        char[200_000] x = '9';
        string a = x.dup;
        BigInt b = BigInt(a);
        "b".writeln();
        b.plus_one();
        "b + 1".writeln;
    }

    solve();
}


import core.bitop;
import std.conv;
import std.stdio;
import std.typecons;

immutable int LOG =       17;
immutable int MED = 1 << LOG;
immutable int MAX = MED << 1;

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto a = new int [n];
		foreach (ref x; a)
		{
			readf (" %s", &x);
		}

		alias pair = Tuple !(int, "p", int, "v");
		auto q = new pair [m];
		foreach (ref x; q)
		{
			readf (" %s %s", &x.p, &x.v);
		}

		auto ans = new long [m];
		foreach (c; 0..LOG)
		{
			auto b = new bool [n];
			foreach (i; 0..n)
			{
				b[i] = (a[i] >> c) & 1;
			}
			auto r = new pair [m];
			foreach (j; 0..m)
			{
				r[j] = pair (q[j].p, (q[j].v >> c) & 1);
			}
			alias node = Tuple !(long, "s", int, "l", int, "r");
			auto t = new node [MAX];
			foreach (i; 0..n)
			{
				t[i + MED + 1] = node (0, b[i], b[i]);
			}

			void recalc (int i, int w)
			{
				int m = t[i * 2 + 0].r + t[i * 2 + 1].l;
				t[i].l = t[i * 2 + 0].l;
				if (t[i].l == w)
				{
					t[i].l += t[i * 2 + 1].l;
					m = 0;
				}
				t[i].r = t[i * 2 + 1].r;
				if (t[i].r == w)
				{
					t[i].r += t[i * 2 + 0].r;
					m = 0;
				}
				t[i].s = t[i * 2 + 0].s + t[i * 2 + 1].s;
				t[i].s += (m * to !(long) (m + 1)) >> 1;
			}

			foreach_reverse (k; 0..LOG)
			{
				foreach (i; 1 << k..1 << (k + 1))
				{
					recalc (i, 1 << (LOG - k - 1));
				}
			}

			foreach (j; 0..m)
			{
				int p = r[j].p + MED;
				int v = r[j].v;
				if (v != t[p].l)
				{
					t[p] = node (0, v, v);
					int k = 1;
					while (p > 0)
					{
						p >>= 1;
						recalc (p, k);
						k <<= 1;
					}
				}
				ans[j] += t[1].s << c;
			}
		}

		writefln ("%(%s\n%)", ans);
	}
}

import std.stdio;
import std.typecons;

immutable int LOG =       17;
immutable int MED = 1 << LOG;
immutable int MAX = MED << 1;

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto a = new int [n];
		foreach (ref x; a)
		{
			readf (" %s", &x);
		}

		alias pair = Tuple !(int, "p", int, "v");
		auto q = new pair [m];
		foreach (ref x; q)
		{
			readf (" %s %s", &x.p, &x.v);
		}

		auto ans = new long [m];
		foreach (c; 0..LOG)
		{
			alias node = Tuple !(long, "s", int, "l", int, "r");
			auto t = new node [MAX];
			foreach (i; 0..n)
			{
				int v = (a[i] >> c) & 1;
				t[i + MED + 1] = node (0, v, v);
			}

			void recalc (int i, int w)
			{
				int j = i * 2;
				int k = j + 1;
				long m = t[j].r + t[k].l;
				t[i].l = t[j].l;
				if (t[i].l == w)
				{
					t[i].l += t[k].l;
					m = 0;
				}
				t[i].r = t[k].r;
				if (t[i].r == w)
				{
					t[i].r += t[j].r;
					m = 0;
				}
				t[i].s = t[j].s + t[k].s + (m * (m + 1)) / 2;
			}

			foreach_reverse (k; 0..LOG)
			{
				foreach (i; 1 << k..1 << (k + 1))
				{
					recalc (i, 1 << (LOG - k - 1));
				}
			}

			foreach (j; 0..m)
			{
				int p = q[j].p + MED;
				int v = (q[j].v >> c) & 1;
				if (v != t[p].l)
				{
					t[p] = node (0, v, v);
					int k = 1;
					while (p > 1)
					{
						p >>= 1;
						recalc (p, k);
						k <<= 1;
					}
				}
				ans[j] += t[1].s << c;
			}
		}

		writefln ("%(%s\n%)", ans);
	}
}

import core.bitop, std.stdio, std.typecons;

immutable int LOG = 17, MED = 1 << LOG, MAX = MED << 1;

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto a = new int [n];
		foreach (ref x; a)
			readf (" %s", &x);

		alias pair = Tuple !(int, "p", int, "v");
		auto q = new pair [m];
		foreach (ref x; q)
			readf (" %s %s", &x.p, &x.v);

		auto ans = new long [m];
		foreach (c; 0..LOG)
		{
			alias node = Tuple !(long, "s", int, "l", int, "r");
			auto t = new node [MAX];
			foreach (i; 0..n)
			{
				int v = (a[i] >> c) & 1;
				t[i + MED + 1] = node (0, v, v);
			}

			void recalc (int i)
			{
				int j = i * 2;
				int k = j + 1;
				int w = 1 << (LOG - bsr (i) - 1);
				long m = (t[j].r == w || t[k].l == w) ? 0 :
				         t[j].r + t[k].l;
				t[i].l = (t[j].l == w) ? w + t[k].l : t[j].l;
				t[i].r = (t[k].r == w) ? w + t[j].r : t[k].r;
				t[i].s = t[j].s + t[k].s + (m * (m + 1)) / 2;
			}

			foreach_reverse (i; 1..MED)
				recalc (i);

			foreach (j; 0..m)
			{
				int p = q[j].p + MED;
				int v = (q[j].v >> c) & 1;
				if (v != t[p].l)
				{
					t[p] = node (0, v, v);
					for (p >>= 1; p > 0; p >>= 1)
						recalc (p);
				}
				ans[j] += t[1].s << c;
			}
		}

		writefln ("%(%s\n%)", ans);
	}
}

import core.bitop;
import std.stdio;
import std.typecons;

immutable int LOG =       17;
immutable int MED = 1 << LOG;
immutable int MAX = MED << 1;

void main ()
{
	int n, m;
	while (readf (" %s %s", &n, &m) > 0)
	{
		auto a = new int [n];
		foreach (ref x; a)
		{
			readf (" %s", &x);
		}

		alias pair = Tuple !(int, "p", int, "v");
		auto q = new pair [m];
		foreach (ref x; q)
		{
			readf (" %s %s", &x.p, &x.v);
		}

		auto ans = new long [m];
		foreach (c; 0..LOG)
		{
			alias node = Tuple !(long, "s", int, "l", int, "r");
			auto t = new node [MAX];
			foreach (i; 0..n)
			{
				int v = (a[i] >> c) & 1;
				t[i + MED + 1] = node (0, v, v);
			}

			void recalc (int i)
			{
				int j = i * 2;
				int k = j + 1;
				int w = 1 << (LOG - bsr (i) - 1);
				long m = (t[j].r == w || t[k].l == w) ? 0 :
				         t[j].r + t[k].l;
				t[i].l = (t[j].l == w) ? w + t[k].l : t[j].l;
				t[i].r = (t[k].r == w) ? w + t[j].r : t[k].r;
				t[i].s = t[j].s + t[k].s + (m * (m + 1)) / 2;
			}

			foreach_reverse (i; 1..MED)
			{
				recalc (i);
			}

			foreach (j; 0..m)
			{
				int p = q[j].p + MED;
				int v = (q[j].v >> c) & 1;
				if (v != t[p].l)
				{
					t[p] = node (0, v, v);
					for (p >>= 1; p > 0; p >>= 1)
					{
						recalc (p);
					}
				}
				ans[j] += t[1].s << c;
			}
		}

		writefln ("%(%s\n%)", ans);
	}
}


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

immutable long MD = 10^^9+7;
immutable int MN = 1010;

long[MN][MN] dp;
bool[MN][MN] used;
int n;
int[MN] p;

long solve(int a, int b) {
    if (a == b) return 0;
    if (used[a][b]) return dp[a][b];
    long r = 2 + solve(p[a], a) + solve(a+1, b); r %= MD;
    used[a][b] = true;
    dp[a][b] = r;
    return r;
}

int main() {
    readf("%d\n", &n);
    string[] input = split(readln());
    foreach (i; 0..n) {
        p[i] = to!int(input[i]) - 1;
    }
    writeln(solve(0, n));
    return 0;
}

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

immutable long MD = 10^^9+7;
immutable int MN = 1010;

long[MN][MN] dp;
bool[MN][MN] used;
int n;
int[MN] p;

long solve(int a, int b) {
    if (a == b) return 0;
    if (used[a][b]) return dp[a][b];
    long r = (2 + solve(p[a], a) + solve(a+1, b)) % MD;
    used[a][b] = true;
    dp[a][b] = r;
    return r;
}

int main() {
    readf("%d\n", &n);
    string[] input = split(readln());
    foreach (i; 0..n) {
        p[i] = to!int(input[i]) - 1;
    }
    writeln(solve(0, n));
    return 0;
}

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

immutable int MOD = 1_000_000_007;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto p = new int [n];
		auto f = new long [n];
		foreach (ref x; p)
		{
			readf (" %s", &x);
			x--;
		}
		f[] = 0;
		foreach (i; 0..n)
		{
			long cur = 0;
			cur = (cur + 1) % MOD;
			int j = p[i];
			while (j != i)
			{
				cur = (cur + f[j]) % MOD;
				j++;
			}
			cur = (cur + 1) % MOD;
			f[i] = cur;
		}
		long res = reduce !("a + b") (f);
		res %= MOD;
		writeln (res);
	}
}

import std.stdio, std.string;

immutable int mod = 1000000007;

void inc(ref int val, int add)
{
    val += add;
    if (val >= mod)
    {
        val -= mod;
    }
}

int recur(int idx, int[] dp, int[] p)
{
    if (dp[idx] != -1)
    {
        return dp[idx];
    }
    dp[idx] = 2;
    foreach (i; p[idx] .. idx)
    {
        int ret = recur(i, dp, p);
        inc(dp[idx], ret);
    }
    return dp[idx];
}

void solve(int[] p)
{
    int[] dp = new int[p.length];
    foreach (i, ref val; dp)
    {
        val = -1;
    }
    int ans = 0;
    foreach (i; 0 .. p.length)
    {
        int ret = recur(i, dp, p);
        inc(ans, ret);
    }
    writefln("%d", ans);
}

void main(string[] args)
{
    int n;
    while (scanf("%d", &n) == 1)
    {
        int[] p = new int[n];
        foreach (i; 0 .. n)
        {
            scanf("%d", &p[i]);
            -- p[i];
        }
        solve(p);
    }
}

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

immutable long MD = 1^^9+7;
immutable int MN = 1010;

long[MN][MN] dp;
bool[MN][MN] used;
int n;
int[MN] p;

long solve(int a, int b) {
    if (a == b) return 0;
    if (used[a][b]) return dp[a][b];
    long r = 2 + solve(p[a], a) + solve(a+1, b); r %= MD;
    used[a][b] = true;
    dp[a][b] = r;
    return r;
}

int main() {
    readf("%d\n", &n);
    string[] input = split(readln());
    foreach (i; 0..n) {
        p[i] = to!int(input[i]) - 1;
    }
    writeln(solve(0, n));
    return 0;
}