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

void solve(){
    auto n = scan!int;
    auto a = scanArray;
    auto b = scanArray;
    tup[] zipp;
    for(int i = 0; i < n; ++i){
        zipp ~= tup(a[i], b[i], i);
    }
    zipp.sort;
    /* long[] mxf; */
    /* long mx = 0; */
    /* for(int i = 0; i < n; ++i){ */
    /*     mx = max(mx, b[i]); */
    /*     mxf ~= mx; */
    /* } */
    /* long[] mxr = new long[](n); */
    /* mx = 0; */
    /* for(int i = n-1; i >= 0; --i){ */
    /*     mx = max(mx, b[i]); */
    /*     mxr[i] = mx; */
    /* } */
    /* show(mxf, mxr); */
    dchar[] res = new dchar[](n);
    res[] = '0';
    dchar cr = '0';
    long last = zipp[n-1][1];

    long lef = 0;
    b.sort;
    long[int] bvals;
    for(int i = n-1; i >= 0; --i){
        bvals[b[i].to!int] = lef++;
    }
    long left = 0;
    long c = 0;
    for(int i = n-1; i >= 0; --i){
        left = max(left, bvals[zipp[i][1].to!int]);
        res[zipp[i][2]] = '1';
        show(left, i);
        if(left - c == 0){
            break;
        }
        ++c;
    }

    /* /1* for(int i = 0; i < n; ++i){ *1/ */
    /*     /1* if(mxf[i] >= mxr[i]){ *1/ */
    /*     if(zipp[i][1] >= zipp[n-1][1]){ */
    /*         cr = '1'; */
    /*         /1* res[zipp[i][2]] = '1'; *1/ */
    /*     }else{ */
    /*     } */
    /*     res[zipp[i][2]] = cr; */
    /* } */
    writeln(res);
}

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

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

// Not my code! Taken from https://codeforces.com/contest/1608/submission/138747137
// Added a @trusted readln wrapper, removed assumeSafeAppend and marked everything as @safe
// Then commented out safe.

//@safe:
import std.algorithm;
import std.container;
import std.conv;
import std.range;
import std.stdio;
import std.string;

auto readln() @trusted { return std.stdio.readln; }

void main ()
{
    auto tests = readln.strip.to !(int);
    foreach (test; 0..tests)
    {
	auto n = readln.strip.to !(int);
	auto a0 = readln.splitter.map !(to !(int)).array;
	auto b0 = readln.splitter.map !(to !(int)).array;
	auto answer = new int [n];

	void solve (const ref int [] a, const ref int [] b)
	{
	    auto s = redBlackTree !((i, j) => a[i] < a[j], int);
	    auto t = redBlackTree !((i, j) => b[i] < b[j], int);
	    foreach (i; 0..n)
	    {
		s.insert (i);
		t.insert (i);
	    }
	    auto p = n.iota.array;
	    p.sort !((i, j) => a[i] < a[j]);

	    foreach (i; p)
	    {
		auto q = [i];
		while (!q.empty)
		{
		    auto j = q.front;
		    q.popFront ();

		    while (true)
		    {
			auto slo = s.lowerBound (j);
			if (slo.empty)
			{
			    break;
			}
			auto k = slo.front;
			s.removeKey (k);
			t.removeKey (k);
			q ~= k;
		    }

		    while (true)
		    {
			auto tlo = t.lowerBound (j);
			if (tlo.empty)
			{
			    break;
			}
			auto k = tlo.front;
			s.removeKey (k);
			t.removeKey (k);
			q ~= k;
		    }
		}

		auto left = s.upperBound (i);
		if (left.empty)
		{
		    answer[i] = 1;
		}
	    }
	}

	solve (a0, b0);
	solve (b0, a0);
	writefln !("%(%s%)") (answer);
    }
}

// Not my code! Taken from https://codeforces.com/contest/1608/submission/138747137
// Added a @trusted readln wrapper, removed assumeSafeAppend and marked everything as @safe

@safe:
import std.algorithm;
import std.container;
import std.conv;
import std.range;
import std.stdio;
import std.string;

auto readln() @trusted { return std.stdio.readln; }

void main ()
{
    auto tests = readln.strip.to !(int);
    foreach (test; 0..tests)
    {
	auto n = readln.strip.to !(int);
	auto a0 = readln.splitter.map !(to !(int)).array;
	auto b0 = readln.splitter.map !(to !(int)).array;
	auto answer = new int [n];

	void solve (const ref int [] a, const ref int [] b)
	{
	    auto s = redBlackTree !((i, j) => a[i] < a[j], int);
	    auto t = redBlackTree !((i, j) => b[i] < b[j], int);
	    foreach (i; 0..n)
	    {
		s.insert (i);
		t.insert (i);
	    }
	    auto p = n.iota.array;
	    p.sort !((i, j) => a[i] < a[j]);

	    foreach (i; p)
	    {
		auto q = [i];
		while (!q.empty)
		{
		    auto j = q.front;
		    q.popFront ();

		    while (true)
		    {
			auto slo = s.lowerBound (j);
			if (slo.empty)
			{
			    break;
			}
			auto k = slo.front;
			s.removeKey (k);
			t.removeKey (k);
			q ~= k;
		    }

		    while (true)
		    {
			auto tlo = t.lowerBound (j);
			if (tlo.empty)
			{
			    break;
			}
			auto k = tlo.front;
			s.removeKey (k);
			t.removeKey (k);
			q ~= k;
		    }
		}

		auto left = s.upperBound (i);
		if (left.empty)
		{
		    answer[i] = 1;
		}
	    }
	}

	solve (a0, b0);
	solve (b0, a0);
	writefln !("%(%s%)") (answer);
    }
}

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

void solve() {
    int N = read!int;
    auto A = readarray!int;
    auto B = readarray!int;
    auto IDX = iota(N).array.sort!((i, j) => B[i] > B[j]).array;
    int limA = A[IDX[0]];
    char[] ans = new char[N]; ans[] = '0';
    ans[IDX[0]] = '1';
    auto M = new int[N];
    M[N-1] = A[IDX[N-1]];
    for (int i = N - 2; i >= 0; i--) {
        M[i] = max(M[i+1], A[IDX[i]]);
    }
    for (int i = 1; i < N; i++) {
        int k = IDX[i];
        /*
        writeln([i, k]);
        writeln("M[k]: ", M[k]);
        writeln("limA: ", limA);
        */
        if (M[i] > limA) {
            ans[k] = '1';
            limA = min(limA, A[k]);
        }
    }
    writeln(ans);
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a0 = readln.splitter.map !(to !(int)).array;
		auto b0 = readln.splitter.map !(to !(int)).array;
		auto answer = new int [n];

		void solve (const ref int [] a, const ref int [] b)
		{
			auto s = redBlackTree !((i, j) => a[i] < a[j], int);
			auto t = redBlackTree !((i, j) => b[i] < b[j], int);
			foreach (i; 0..n)
			{
				s.insert (i);
				t.insert (i);
			}
			auto p = n.iota.array;
			p.sort !((i, j) => a[i] < a[j]);

			foreach (i; p)
			{
				auto q = [i];
				while (!q.empty)
				{
					auto j = q.front;
					q.popFront ();
					q.assumeSafeAppend ();

					while (true)
					{
						auto slo = s.lowerBound (j);
						if (slo.empty)
						{
							break;
						}
						auto k = slo.front;
						s.removeKey (k);
						t.removeKey (k);
						q ~= k;
					}

					while (true)
					{
						auto tlo = t.lowerBound (j);
						if (tlo.empty)
						{
							break;
						}
						auto k = tlo.front;
						s.removeKey (k);
						t.removeKey (k);
						q ~= k;
					}
				}

				auto left = s.upperBound (i);
				if (left.empty)
				{
					answer[i] = 1;
				}
			}
		}

		solve (a0, b0);
		solve (b0, a0);
		writefln !("%(%s%)") (answer);
	}
}

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

void solve(){
    auto n = scan!int;
    auto a = scanArray;
    auto b = scanArray;
    tup[] zipp;
    for(int i = 0; i < n; ++i){
        zipp ~= tup(a[i], b[i], i);
    }
    zipp.sort;
    /* long[] mxf; */
    /* long mx = 0; */
    /* for(int i = 0; i < n; ++i){ */
    /*     mx = max(mx, b[i]); */
    /*     mxf ~= mx; */
    /* } */
    /* long[] mxr = new long[](n); */
    /* mx = 0; */
    /* for(int i = n-1; i >= 0; --i){ */
    /*     mx = max(mx, b[i]); */
    /*     mxr[i] = mx; */
    /* } */
    /* show(mxf, mxr); */
    dchar[] res = new dchar[](n);
    res[] = '0';
    dchar cr = '0';
    long last = zipp[n-1][1];

    long lef = 0;
    b.sort;
    long[int] bvals;
    for(int i = n-1; i >= 0; --i){
        bvals[b[i].to!int] = ++lef;
    }
    long left = 0;
    long c = 0;
    for(int i = n-1; i >= 0; --i){
        left = max(left, bvals[zipp[i][1].to!int]) - c;
        res[zipp[i][2]] = '1';
        show(left, i);
        if(left == 0){
            break;
        }
        ++c;
    }

    /* /1* for(int i = 0; i < n; ++i){ *1/ */
    /*     /1* if(mxf[i] >= mxr[i]){ *1/ */
    /*     if(zipp[i][1] >= zipp[n-1][1]){ */
    /*         cr = '1'; */
    /*         /1* res[zipp[i][2]] = '1'; *1/ */
    /*     }else{ */
    /*     } */
    /*     res[zipp[i][2]] = cr; */
    /* } */
    writeln(res);
}

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

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

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

void solve(){
    auto n = scan!int;
    auto a = scanArray;
    auto b = scanArray;
    tup[] zipp;
    for(int i = 0; i < n; ++i){
        zipp ~= tup(a[i], b[i], i);
    }
    zipp.sort;
    /* long[] mxf; */
    /* long mx = 0; */
    /* for(int i = 0; i < n; ++i){ */
    /*     mx = max(mx, b[i]); */
    /*     mxf ~= mx; */
    /* } */
    /* long[] mxr = new long[](n); */
    /* mx = 0; */
    /* for(int i = n-1; i >= 0; --i){ */
    /*     mx = max(mx, b[i]); */
    /*     mxr[i] = mx; */
    /* } */
    /* show(mxf, mxr); */
    dchar[] res = new dchar[](n);
    dchar cr = '0';
    for(int i = 0; i < n; ++i){
        /* if(mxf[i] >= mxr[i]){ */
        if(zipp[i][1] >= zipp[n-1][1]){
            cr = '1';
            /* res[zipp[i][2]] = '1'; */
        }else{
        }
        res[zipp[i][2]] = cr;
    }
    writeln(res);
}

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

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

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

void solve(){
    auto n = scan!int;
    auto a = scanArray;
    auto b = scanArray;
    tup[] zipp;
    for(int i = 0; i < n; ++i){
        zipp ~= tup(a[i], b[i], i);
    }
    zipp.sort;
    long[] mxf;
    long mx = 0;
    for(int i = 0; i < n; ++i){
        mx = max(mx, b[i]);
        mxf ~= mx;
    }
    long[] mxr = new long[](n);
    mx = 0;
    for(int i = n-1; i >= 0; --i){
        mx = max(mx, b[i]);
        mxr[i] = mx;
    }
    show(mxf, mxr);
    dchar[] res = new dchar[](n);
    for(int i = 0; i < n; ++i){
        if(mxf[i] >= mxr[i]){
            res[zipp[i][2]] = '1';
        }else{
            res[zipp[i][2]] = '0';
        }
    }
    writeln(res);
}

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

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

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

void solve() {
    int N = read!int;
    auto A = readarray!int;
    auto B = readarray!int;
    auto IDX = iota(N).array.sort!((i, j) => B[i] > B[j]).array;
    int limA = A[IDX[0]];
    char[] ans = new char[N]; ans[] = '0';
    ans[IDX[0]] = '1';
    auto M = new int[N];
    M[N-1] = A[IDX[N-1]];
    for (int i = N - 2; i >= 0; i--) {
        M[i] = max(M[i+1], A[IDX[i]]);
    }
    for (int i = 1; i < N; i++) {
        int k = IDX[i];
        if (M[k] > limA) {
            ans[k] = '1';
            limA = min(limA, A[k]);
        }
    }
    writeln(ans);
}

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

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

void solve() {
    int N = read!int;
    auto A = readarray!int;
    auto B = readarray!int;
    auto IDX = iota(N).array.sort!((i, j) => B[i] > B[j]).array;
    int limA = A[IDX[0]];
    char[] ans = new char[N]; ans[] = '0';
    ans[IDX[0]] = '1';
    for (int i = 1; i < N; i++) {
        int k = IDX[i];
        if (A[k] > limA) {
            ans[k] = '1';
        }
    }
    writeln(ans);
}

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a0 = readln.splitter.map !(to !(int)).array;
		auto b0 = readln.splitter.map !(to !(int)).array;
		auto answer = new int [n];

		void solve (const ref int [] a, const ref int [] b)
		{
			auto s = redBlackTree !((i, j) => a[i] < a[j], int);
			auto t = redBlackTree !((i, j) => b[i] < b[j], int);
			foreach (i; 0..n)
			{
				s.insert (i);
				t.insert (i);
			}
			auto p = n.iota.array;
			p.sort !((i, j) => a[i] < a[j]);

			foreach (i; p)
			{
				auto lo = t.lowerBound (i).array;
				foreach (j; lo)
				{
					s.removeKey (j);
					t.removeKey (j);
				}
				auto left = s.upperBound (i);
				if (left.empty)
				{
					answer[i] = 1;
				}
			}
		}

		solve (a0, b0);
		solve (b0, a0);
		writefln !("%(%s%)") (answer);
	}
}


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

alias type = multi;
struct TestCase
{
  mixin prettyPrinting;

  long n;
  @Dim("n") Tuple!(long, long)[] enemies;

  void solve(long tc = -1)
  {
    auto reqbull = iota(0, n).map!(i => (enemies.at(pmod(i - 1, n))[1] >= enemies.at(i)[0])?
                                   0 : enemies.at(i)[0] - enemies.at(pmod(i - 1, n))[1]).array;
    auto reqbulls = reqbull.sum;
    writeln(iota(0, n).map!(i => reqbulls - reqbull.at(i) + enemies.at(i)[0]).fold!min);
  }
}

struct Interval
{
  long l, h;

  bool empty()
  {
    return l > h;
  }
}

Interval intersect(Interval a, Interval b)
{
  return Interval(max(a.l, b.l), min(a.h, b.h));
}

struct If
{
  string condition;
}
enum ignore = If("false");
struct Dim
{
  string dimensions;
  int levels;
  this(string dimensions)
  {
    this.dimensions = dimensions;
    levels = cast(int)dimensions.count(",") + 1;
  }
}

template getArrayLevel(W)
{
  static if (isDynamicArray!W && !is(W == string))
    enum getArrayLevel = 1 + getArrayLevel!(removeArray!(W, 1));
  else
    enum getArrayLevel = 0;
}

static foreach(fieldName; 'a' .. cast(char)('z' + 1))
  {
    static if (fieldName != 'o')
      mixin("enum d", fieldName, " = Dim(\"", fieldName, "\");");
  }

mixin template prettyPrinting()
{
  string toString()
  {
    alias structType = typeof(this);
    auto res = appender!(string)();
    res.put(structType.stringof);
    res.put("(");
    static foreach(fieldName; FieldNameTuple!structType)
      {
        res.put(text(" ", fieldName, ": ", mixin(fieldName)));
      }
    res.put(" )");
    res.put("\n");
    return res[];
  }
}

struct Graph(N)
{
  size_t size;
  this(S)(S size)
  {
    adjacencyList.length = cast(size_t) size;
    this.size = cast(size_t) size;
    this.visited = makeSlice!bool(size);
  }
  N[][] adjacencyList;
  alias ne = neighbours;
  N[] neighbours(N n)
  {
    return adjacencyList.at(n);
  }
  alias bcon = biconnect;
  void biconnect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
    adjacencyList.at(b) ~= a;
  }
  alias con = connect;
  void connect(N a, N b)
  {
    adjacencyList.at(a) ~= b;
  }
  void connect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        connect(edge[0], edge[1]);
      }
  }
  void biconnect(R)(R edges)
  {
    foreach(ref edge; edges)
      {
        biconnect(edge[0], edge[1]);
      }
  }
  alias deg = degree!long;
  auto degree(T)(N a)
  {
    return cast(T) adjacencyList.at(a).length;
  }

  auto visited = new bool[0];
  void dfs(Visitor)(long startNode)
  {
    auto visitor = Visitor.init;
    void internalDfs(long node)
    {
      visited.set(node, true);
      static if (is(typeof({visitor.n = node;})))
        visitor.n = node;
      static if (is(typeof({visitor.pre;})))
        visitor.pre;
      foreach(w; ne(node))
        if (!visited.at(w))
          {
            static if (is(typeof({visitor.w = w;})))
              visitor.w = w;
            static if (is(typeof(visitor.pren)))
              visitor.pren;
            internalDfs(w);
            static if (is(typeof(visitor.postn)))
              visitor.postn;
          }
      static if (is(typeof(visitor.post)))
        visitor.post;
    }
    internalDfs(startNode);
  }
  void dfs(long startNode)
  {
    struct DefVisitor {}
    dfs!DefVisitor(startNode);
  }
}

DList!string _words;

template removeArray(W, int times)
{
  static if (times == 0)
    alias removeArray = W;
  else static if (times == 1)
    alias removeArray = typeof(function(){W w; return w[0];}());
  else
    {
      static assert(isDynamicArray!W);
      alias removeArray = removeArray!(removeArray!(W, 1), times - 1);
    }
}

template baseType(W)
{
  static if (isDynamicArray!W && !is(W == string))
    alias baseType = baseType!(typeof((delegate() {W w; return w[0];})()));
  else
    alias baseType = W;
}

auto makeSlice(E, W, T...)(W size, T otherSizes)
{
  static if (T.length == 0)
    {
      E[] res;
      res.length = cast(size_t) size;
      return res;
    }
  else
    {
      typeof(makeSlice!E(otherSizes))[] res;
      res.length = cast(size_t) size;
      foreach(ref row; res)
        row = makeSlice!E(otherSizes);
      return res;
    }
}

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

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

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

size_t ind(T)(T t)
{
  return cast(size_t)t;
}

ref auto at(R, I)(ref R r, I i)
{
  return r[cast(size_t)i];
}

void set(R, I, V)(ref R r, I i, V v)
{
  r[cast(size_t)i] = v;
}

import std.conv;
import std.traits;
import std.meta;
int _loglevel = -1;
void _log(string functionName, argSeq...)()
{
  foreach(i; 0 .. _loglevel * 4)
    write(' ');
  write(functionName);
  static foreach(arg; argSeq)
    {
      write(" ", arg.stringof, " = ", arg);
    }
  writeln;
}
enum logCall =
  q{
    debug
    {
     {
     _loglevel++;
     alias _parameterTuple = ParameterIdentifierTuple!(mixin(split(__FUNCTION__, ".").back));
     static if (_parameterTuple.length > 0)
       mixin(`_log!(__FUNCTION__, `, [_parameterTuple].joiner(", ").array, `);`);
     else
       _log!(__FUNCTION__);
      }
     foreach(i; 0 .. _loglevel * 4) write(' ');
     writeln('{');
     scope(exit)
       {
         foreach(i; 0 .. _loglevel * 4) write(' ');
         writeln('}');
         _loglevel--;
       }
    }
};

void logSym(S...)(int line = __LINE__, string file = __FUNCTION__)
{
  debug
    {
      foreach(i; 0 .. _loglevel * 4) write(' ');
      write(file, "(", line, "):");
      static foreach(s; S)
        write(" ", s.stringof, " = ", s);
      writeln;

    }
}

Array!E makeArray(E, S)(S size, lazy E value)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  foreach(ref ai; a)
    ai = value();
  return a;
}
Array!E makeArray(E, S)(S size)
{
  auto a = Array!E();
  a.length = cast(size_t) size;
  return a;
}

template mem(alias F)
{
  ReturnType!F[Tuple!(Parameters!F)] table;
  ReturnType!F mem(Parameters!F args)
  {
    return table.require(tuple(args), F(args));
  }
}

string input(string names, string type = "long")
{
  return text(type, " ", names, "; read(", names, ");");
}

auto pmod(T, W)(T t, W w)
{
  return (t%w + w) % w;
}

void rep(S, F)(F f, S times)
{
  static if (is(typeof(f(i))))
    foreach(i; 0 .. times)
      f(i);
  else
    foreach(i; 0 .. times)
      f();
}

void multi()
{
  foreach(tc; 0 .. next!long)
    next!TestCase.solve(tc);
}

void single()
{
  auto tc = next!TestCase;
  tc.solve;
}

void main()
{
  type;
}

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

void main ()
{
	int tests;
	readf !(" %s") (tests);
	foreach (test; 0..tests)
	{
		int n;
		readf !(" %s") (n);
		auto a = new long [n];
		auto b = new long [n];
		foreach (i; 0..n)
		{
			readf !(" %s %s") (a[i], b[i]);
		}

		long cur = 0;
		foreach (i; 0..n)
		{
			long temp = a[i];
			if (i > 0)
			{
				temp = max (0L, temp - b[i - 1]);
			}
			cur += temp;
		}

		long res = cur;
		foreach (i; 0..n)
		{
			auto prev = (i + n - 1) % n;
			auto next = (i + 1) % n;
			cur -= a[i];
			cur -= max (0L, a[next] - b[i]);
			cur += a[next];
			cur += max (0L, a[i] - b[prev]);
			res = min (res, cur);
		}
		writeln (res);
	}
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto ab = new long[][](n);
		foreach (i; 0..n)
		{
			ab[i] = [RD, RD];
		}
		auto d = new long[](n);
		foreach (i; 0..n-1)
		{
			d[i+1] = min(ab[i][1], ab[i+1][0]);
		}
		d[0] = min(ab[$-1][1], ab[0][0]);

		auto pos = d.MIN_POS;
		foreach (i; 0..n)
		{
			ans[ti] += ab[i][0];
			ans[ti] -= d[i];
		}
		debug writeln(ans);
		ans[ti] += d[pos];
		debug writeln(ab);
		debug writeln(d);
		debug writeln("pos:", pos);
	}

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


import core.bitop, std.algorithm, std.bigint, std.compiler, std.container,
	std.bitmanip, std.conv, std.math;
import std.numeric : Fft, fft, gcd, inverseFft;
import std.random, std.range, std.regex, std.stdio, std.string, std.traits,
	std.typecons, std.uni;

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
const int mod = 10 ^^ 9 + 7, mod2 = mod + 2;
public
{
	pure nothrow
	{
		///make_pair
		pair!(X, Y) make_pair(X, Y)(in X x_, in Y y_)
		{
			return tuple!(X, "fi", Y, "se")(x_, y_);
		}
		///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))
		{
			return assumeSorted(a).lowerBound(g).length;
		}
		///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))
		{
			return a.length - assumeSorted(a).upperBound(g).length;
		}
		///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 assumeSorted(a).contains(g);
		}
	}
	static if (version_minor >= 74)
	{
		///read without format
		bool input(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			return readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
		}
		///readln without format
		bool read(T...)(auto ref T ptrs) if (ptrs.length > 0)
		{
			const bool fl = readf!(replicate(" %s", ptrs.length))(ptrs) == ptrs.length;
			readln;
			return fl;
		}
	}
	else
	{
		///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)
	{
		assert(freopen("input.txt", "r", core.stdc.stdio.stdin));
	}
	struct node
	{
		bool leaf;
		int cnt;
		int[26] go;
	}

	node[] tr;
	tr.length = 2;
	long gans;
	void add(string s)
	{
		int ans;
		bool fl;
		int len;
		int v = 1;
		tr[v].cnt++;
		foreach (int i; 0 .. cast(int) s.length)
		{
			char c = s[i];
			assert(isAlpha(c));
			// debug enter(c);
			if (tr[v].go[c - 'a'] == 0)
			{
				if (fl && tr[v].leaf && len < i)
				{
					ans -= i;
					ans += len + 1;
				}
				fl = 0;
				tr[v].go[c - 'a'] = cast(int) tr.length;
				tr.length++;
			}
			v = tr[v].go[c - 'a'];
			if (tr[v].cnt == 1 && len == 0)
			{
				fl = 1;
				len = i + 1;
			}
			ans++;
		}
		if (fl && tr[v].leaf && len < cast(int) s.length)
		{
			ans -= s.length;
			ans += len + 1;
		}
		gans += ans;
		if (!tr[v].leaf)
		{
			tr[v].leaf = 1;
			v = 1;
			foreach (c; s)
			{
				tr[v].cnt++;
				v = tr[v].go[c - 'a'];
			}
			tr[v].cnt++;
		}
		debug write(ans, ' ', s, '\n');
	}

	bool sep(char c)
	{
		return c == '\n' || c == ' ' || c == '.' || c == ',' || c == '\''
			|| c == '?' || c == '!' || c == '-';
	}
	//38
	string buf;
	int k;
	while (true)
	{
		buf = readln.strip;
		if (buf.length == 0)
			break;
		k++;
		foreach (c; buf)
		{
			if (sep(c))
				gans++;
		}
		auto a = buf.splitter(ctRegex!(`[.,' ?!-]`)).filter!(x => !x.empty);
		foreach (x; a)
		{
			add(x);
		}
	}
	// debug writeln(k, ' ', gans);
	writeln(gans + k);
}

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;

string text;
string nextWord()
{
  string res = null;
  while(!text.empty && text[0].isAlpha)
    {
      res ~= text[0];
      text = text[1 .. $];
    }
  return res;
}
string nextNonWord()
{
  string res = null;
  while(!text.empty && !text[0].isAlpha)
    {
      res ~= text[0];
      text = text[1 .. $];
    }
  return res;
}

class ptNode
{
  ptNode[26] chTrans;
  bool isTerminal;
  int noTerminalDescendants;
}

int insert(ptNode root, string str)
{
  int surelyInserted = 0;
  int probablyCompleted = 0;
  ptNode node = root;
  auto nodePath = new ptNode[](1);
  nodePath[0] = root;
  auto origstr = str;
  bool isnew = false;
  bool iscompleted = false;
  while(!str.empty)
    {
      if (node.chTrans[str[0] - 'a'] is null)
	{
	  node.chTrans[str[0] - 'a'] = new ptNode;
	}
      node = node.chTrans[str[0] - 'a'];
      str = str[1 .. $];
      nodePath ~= node;
    }
  isnew = !nodePath[$ - 1].isTerminal;
  str = origstr;
  int lc = int.max;
  int hc = int.min;
  foreach(i, pnode; nodePath)
    {
      if (pnode.noTerminalDescendants == 1 && pnode !is root)
	{
	  lc = min(cast(int) i, lc);
	  hc = max(cast(int) i, hc);
	}
      if (isnew) pnode.noTerminalDescendants++;
    }
  int res = 0;
  debug writeln("doing ", str);
  if (lc != int.max && nodePath[hc].isTerminal)
    {
      assert(hc >= lc);
      if (hc - lc > 1)
	{
	  debug writeln("for word ", str, " saved ", hc - lc - 1);
	  debug writeln("from ", lc, " - ", hc);
	  res = cast(int) str.length - (hc - lc) + 1;
	}
      else
	res = cast(int) str.length;
    }
  else
    {
      res = cast(int) str.length;
    }
  nodePath[$ - 1].isTerminal = true;
  return res;
}

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  inputFile.readf!"%s"(text);
  ptNode root = new ptNode;
  int cost = 0;
  while(true)
    {
      auto nonWord = nextNonWord();
      auto word = nextWord();
      if (nonWord is null && word is null) break;
      if (nonWord !is null) { cost += nonWord.length; debug writeln(nonWord.length); }
      if (word !is null)
	{
	  auto pcost = root.insert(word);
	  debug writeln(pcost);
	  cost += pcost;
	}
    }
  cost.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;
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;

string text;
string nextWord()
{
  int len = 0;
  auto ntext = text;
  while(!ntext.empty && ntext[0].isAlpha)
    {
      ntext = ntext[1 .. $];
      len++;
    }
  auto res = text[0 .. len];
  text = ntext;
  return res;
}
string nextNonWord()
{
  int len = 0;
  auto ntext = text;
  while(!ntext.empty && !ntext[0].isAlpha)
    {
      ntext = ntext[1 .. $];
      len++;
    }
  auto res = text[0 .. len];
  text = ntext;
  return res;
}

class ptNode
{
  ptNode[26] chTrans;
  bool isTerminal;
  int noTerminalDescendants;
}

int insert(ptNode root, string str)
{
  ptNode node = root;
  auto nodePath = new ptNode[](1);
  nodePath[0] = root;
  auto origstr = str;
  bool isnew = false;
  while(!str.empty)
    {
      if (node.chTrans[str[0] - 'a'] is null)
	node.chTrans[str[0] - 'a'] = new ptNode;
      node = node.chTrans[str[0] - 'a'];
      str = str[1 .. $];
      nodePath ~= node;
    }
  isnew = !nodePath[$ - 1].isTerminal;
  str = origstr;
  int lc = -1;
  int hc = -1;
  foreach(i, pnode; nodePath)
    {
      if (pnode.noTerminalDescendants == 1 && pnode !is root)
	{
	  if (lc == -1)
	    {
	      lc = cast(int)i;
	      hc = cast(int)i;
	    }
	  else
	    {
	      hc = cast(int)i;
	    }
	}
      if (isnew) pnode.noTerminalDescendants++;
    }
  int res = 0;
  if (lc != -1 && nodePath[hc].isTerminal && hc - lc > 1)
    res = cast(int) str.length - (hc - lc) + 1;
  else
    res = cast(int) str.length;
  nodePath[$ - 1].isTerminal = true;
  return res;
}

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  inputFile.readf!"%s"(text);
  ptNode root = new ptNode;
  int cost = 0;
  while(true)
    {
      auto nonWord = nextNonWord();
      auto word = nextWord();
      debug writeln(nonWord, "|", word);
      if (nonWord.length == 0 && word.length == 0) break;
      if (nonWord.length > 0) { cost += nonWord.length; debug writeln(nonWord.length); }
      if (word.length > 0)
	{
	  auto pcost = root.insert(word);
	  debug writeln(pcost);
	  cost += pcost;
	}
    }
  cost.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;
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;

string text;
string nextWord()
{
  string res = null;
  while(!text.empty && text[0].isAlpha)
    {
      res ~= text[0];
      text = text[1 .. $];
    }
  return res;
}
string nextNonWord()
{
  string res = null;
  while(!text.empty && !text[0].isAlpha)
    {
      res ~= text[0];
      text = text[1 .. $];
    }
  return res;
}

class ptNode
{
  ptNode[30] chTrans;
  bool isTerminal;
  int noTerminalDescendants;
}

int insert(ptNode root, string str)
{
  int surelyInserted = 0;
  int probablyCompleted = 0;
  ptNode node = root;
  auto nodePath = new ptNode[](1);
  nodePath[0] = root;
  auto origstr = str;
  bool isnew = false;
  bool iscompleted = false;
  while(!str.empty)
    {
      if (node.chTrans[str[0] - 'a'] is null)
	{
	  node.chTrans[str[0] - 'a'] = new ptNode;
	}
      node = node.chTrans[str[0] - 'a'];
      str = str[1 .. $];
      nodePath ~= node;
    }
  isnew = !nodePath[$ - 1].isTerminal;
  str = origstr;
  int lc = int.max;
  int hc = int.min;
  foreach(i, pnode; nodePath)
    {
      if (pnode.noTerminalDescendants == 1 && pnode !is root)
	{
	  lc = min(cast(int) i, lc);
	  hc = max(cast(int) i, hc);
	}
      if (isnew) pnode.noTerminalDescendants++;
    }
  int res = 0;
  debug writeln("doing ", str);
  if (lc != int.max && nodePath[hc].isTerminal)
    {
      assert(hc >= lc);
      if (hc - lc > 1)
	{
	  debug writeln("for word ", str, " saved ", hc - lc - 1);
	  debug writeln("from ", lc, " - ", hc);
	  res = cast(int) str.length - (hc - lc) + 1;
	}
      else
	res = cast(int) str.length;
    }
  else
    {
      res = cast(int) str.length;
    }
  nodePath[$ - 1].isTerminal = true;
  return res;
}

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  inputFile.readf!"%s"(text);
  ptNode root = new ptNode;
  int cost = 0;
  while(true)
    {
      auto nonWord = nextNonWord();
      auto word = nextWord();
      if (nonWord is null && word is null) break;
      if (nonWord !is null) { cost += nonWord.length; debug writeln(nonWord.length); }
      if (word !is null)
	{
	  auto pcost = root.insert(word);
	  debug writeln(pcost);
	  cost += pcost;
	}
    }
  cost.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;
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;

string text;
string nextWord()
{
  int len = 0;
  auto ntext = text;
  while(!ntext.empty && ntext[0].isAlpha)
    {
      ntext = ntext[1 .. $];
      len++;
    }
  auto res = text[0 .. len];
  text = ntext;
  return res;
}
string nextNonWord()
{
  int len = 0;
  auto ntext = text;
  while(!ntext.empty && !ntext[0].isAlpha)
    {
      ntext = ntext[1 .. $];
      len++;
    }
  auto res = text[0 .. len];
  text = ntext;
  return res;
}

class ptNode
{
  ptNode[26] chTrans;
  bool isTerminal;
  int noTerminalDescendants;
}

int insert(ptNode root, string str)
{
  ptNode node = root;
  auto nodePath = new ptNode[](1);
  nodePath[0] = root;
  auto origstr = str;
  bool isnew = false;
  while(!str.empty)
    {
      if (node.chTrans[str[0] - 'a'] is null)
	node.chTrans[str[0] - 'a'] = new ptNode;
      node = node.chTrans[str[0] - 'a'];
      str = str[1 .. $];
      nodePath ~= node;
    }
  isnew = !nodePath[$ - 1].isTerminal;
  str = origstr;
  int lc = int.max;
  int hc = int.min;
  foreach(i, pnode; nodePath)
    {
      if (pnode.noTerminalDescendants == 1 && pnode !is root)
	{
	  lc = min(cast(int) i, lc);
	  hc = max(cast(int) i, hc);
	}
      if (isnew) pnode.noTerminalDescendants++;
    }
  int res = 0;
  if (lc != int.max && nodePath[hc].isTerminal && hc - lc > 1)
    res = cast(int) str.length - (hc - lc) + 1;
  else
    res = cast(int) str.length;
  nodePath[$ - 1].isTerminal = true;
  return res;
}

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  inputFile.readf!"%s"(text);
  ptNode root = new ptNode;
  int cost = 0;
  while(true)
    {
      auto nonWord = nextNonWord();
      auto word = nextWord();
      debug writeln(nonWord, "|", word);
      if (nonWord.length == 0 && word.length == 0) break;
      if (nonWord.length > 0) { cost += nonWord.length; debug writeln(nonWord.length); }
      if (word.length > 0)
	{
	  auto pcost = root.insert(word);
	  debug writeln(pcost);
	  cost += pcost;
	}
    }
  cost.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;
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;

string text;
string nextWord()
{
  string res = null;
  while(!text.empty && text[0].isAlpha)
    {
      res ~= text[0];
      text = text[1 .. $];
    }
  return res;
}
string nextNonWord()
{
  string res = null;
  while(!text.empty && !text[0].isAlpha)
    {
      res ~= text[0];
      text = text[1 .. $];
    }
  return res;
}

class ptNode
{
  ptNode[30] chTrans;
  bool isTerminal;
  int noTerminalDescendants;
}

int insert(ptNode root, string str)
{
  int surelyInserted = 0;
  int probablyCompleted = 0;
  ptNode node = root;
  auto nodePath = new ptNode[](1);
  nodePath[0] = root;
  auto origstr = str;
  bool isnew = false;
  bool iscompleted = false;
  while(!str.empty)
    {
      if (node.chTrans[str[0] - 'a'] is null)
	{
	  isnew = true;
	  node.chTrans[str[0] - 'a'] = new ptNode;
	}
      node = node.chTrans[str[0] - 'a'];
      str = str[1 .. $];
      nodePath ~= node;
    }
  str = origstr;
  int lc = int.max;
  int hc = int.min;
  foreach(i, pnode; nodePath)
    {
      if (pnode.noTerminalDescendants == 1 && pnode !is root)
	{
	  lc = min(cast(int) i, lc);
	  hc = max(cast(int) i, hc);
	}
      if (isnew) pnode.noTerminalDescendants++;
    }
  int res = 0;
  debug writeln("doing ", str);
  if (lc != int.max && nodePath[hc].isTerminal)
    {
      assert(hc >= lc);
      if (hc - lc > 1)
	{
	  debug writeln("for word ", str, " saved ", hc - lc - 1);
	  debug writeln("from ", lc, " - ", hc);
	  res = cast(int) str.length - (hc - lc) + 1;
	}
      else
	res = cast(int) str.length;
    }
  else
    {
      res = cast(int) str.length;
    }
  nodePath[$ - 1].isTerminal = true;
  return res;
}

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  inputFile.readf!"%s"(text);
  ptNode root = new ptNode;
  int cost = 0;
  while(true)
    {
      auto nonWord = nextNonWord();
      auto word = nextWord();
      if (nonWord is null && word is null) break;
      if (nonWord !is null) { cost += nonWord.length; debug writeln(nonWord.length); }
      if (word !is null)
	{
	  auto pcost = root.insert(word);
	  debug writeln(pcost);
	  cost += pcost;
	}
    }
  cost.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;
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;

string text;
string nextWord()
{
  string res = text[0 .. 0];
  while(!text.empty && text[0].isAlpha)
    {
      res.length++;
      text = text[1 .. $];
    }
  return res;
}
string nextNonWord()
{
  string res = text[0 .. 0];
  while(!text.empty && !text[0].isAlpha)
    {
      res.length++;
      text = text[1 .. $];
    }
  return res;
}

class ptNode
{
  ptNode[26] chTrans;
  bool isTerminal;
  int noTerminalDescendants;
}

int insert(ptNode root, string str)
{
  ptNode node = root;
  auto nodePath = new ptNode[](1);
  nodePath[0] = root;
  auto origstr = str;
  bool isnew = false;
  while(!str.empty)
    {
      if (node.chTrans[str[0] - 'a'] is null)
	node.chTrans[str[0] - 'a'] = new ptNode;
      node = node.chTrans[str[0] - 'a'];
      str = str[1 .. $];
      nodePath ~= node;
    }
  isnew = !nodePath[$ - 1].isTerminal;
  str = origstr;
  int lc = int.max;
  int hc = int.min;
  foreach(i, pnode; nodePath)
    {
      if (pnode.noTerminalDescendants == 1 && pnode !is root)
	{
	  lc = min(cast(int) i, lc);
	  hc = max(cast(int) i, hc);
	}
      if (isnew) pnode.noTerminalDescendants++;
    }
  int res = 0;
  if (lc != int.max && nodePath[hc].isTerminal && hc - lc > 1)
    res = cast(int) str.length - (hc - lc) + 1;
  else
    res = cast(int) str.length;
  nodePath[$ - 1].isTerminal = true;
  return res;
}

void main(string[] args)
{
  inputFile = stdin;
  debug inputFile = File(args[1]);
  inputFile.readf!"%s"(text);
  ptNode root = new ptNode;
  int cost = 0;
  while(true)
    {
      auto nonWord = nextNonWord();
      auto word = nextWord();
      if (nonWord.length == 0 && word.length == 0) break;
      if (nonWord.length > 0) { cost += nonWord.length; debug writeln(nonWord.length); }
      if (word.length > 0)
	{
	  auto pcost = root.insert(word);
	  debug writeln(pcost);
	  cost += pcost;
	}
    }
  cost.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.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto s = readln.strip;
		auto b = s.dup;
		sort (representation (b));
		writeln (b);
	}
}

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

void main() {
    readln;
    auto s = readln.chomp.to!(dchar[]).sort();
    writeln(s);
}

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

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

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


module cf_63A;

import std.stdio;
import std.algorithm;

struct Member {
    string name, type;

    int opCmp(ref const Member other) {
        int[string] TYPE_PRIORITY = [
            "rat": 1, "woman": 2, "child": 2, "man": 3, "captain": 4
        ];

        return TYPE_PRIORITY[type] - TYPE_PRIORITY[other.type];
    }
}

void main() {
    int n;
    Member[] crew;

    readf("%d", &n);
    crew = new Member[n];
    for (int i = 0; i < n; ++i) {
        readf(" %s %s\n", &crew[i].name, &crew[i].type);
    }

    sort!("a < b", SwapStrategy.stable)(crew);
    for (int i = 0; i < crew.length; ++i) {
        writeln(crew[i].name);
    }
}

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

void main() {
    int n; readf("%d\n", &n);
    string[] ns = new string[n];
    string[] ks = new string[n];
    foreach (i; 0 .. n) {
        string name, kind; readf("%s %s\n", &name, &kind);
        ns[i] = name;
        ks[i] = kind;
    }
    foreach (i; 0 .. n) {
        if (ks[i] == "rat") {
            writeln(ns[i]);
        }
    }
    foreach (i; 0 .. n) {
        if (ks[i] == "woman" || ks[i] == "child") {
            writeln(ns[i]);
        }
    }
    foreach (i; 0 .. n) {
        if (ks[i] == "man") {
            writeln(ns[i]);
        }
    }
    foreach (i; 0 .. n) {
        if (ks[i] == "captain") {
            writeln(ns[i]);
        }
    }
}


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

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

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

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

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

immutable MO = 1000000007L;

int N;
int[] P;
int[] X;
int[][] G;

long[] solve(int u) {
	long[] dp = new long[2];
	dp[X[u]] += 1;
	foreach (v; G[u]) {
		long[] res = solve(v);
		dp[1] = (dp[1] * (res[0] + res[1]) + dp[0] * res[1]) % MO;
		dp[0] = (dp[0] * (res[0] + res[1])                 ) % MO;
	}
debug{
writeln(u," ",dp);
}
	return dp;
}

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		P = new int[N];
		X = new int[N];
		P[0] = -1;
		foreach (u; 1 .. N) {
			P[u] = readInt;
		}
		foreach (u; 0 .. N) {
			X[u] = readInt;
		}

		G = new int[][N];
		foreach (u; 1 .. N) {
			G[P[u]] ~= u;
		}

		const res = solve(0);
		long ans = (res[1] % MO + MO) % MO;
		writeln(ans);
	}
	} catch (EOFException) {}
}

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

immutable int MOD = 1_000_000_007;
immutable int NA = -1;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		auto a = new int [] [n];
		for (int i = 1; i < n; i++)
		{
			int j;
			readf (" %s", &j);
			a[j] ~= i;
			a[i] ~= j;
		}

		auto b = new int [n];
		foreach (ref x; b)
		{
			readf (" %s", &x);
		}

		auto f = new int [2] [n];

		void recur (int v, int p)
		{
			f[v][0] = 1;
			f[v][1] = 0;

			foreach (u; a[v])
			{
				if (u == p)
				{
					continue;
				}

				recur (u, v);

				long c0 = f[u][0] + f[u][1];
				if (c0 >= MOD)
				{
					c0 -= MOD;
				}
				long c1 = f[u][1];

				int n0 = (c0 * f[v][0]) % MOD;
				int n1 = (c1 * f[v][0] + c0 * f[v][1]) % MOD;
				f[v][0] = n0;
				f[v][1] = n1;
			}

			if (b[v])
			{
				f[v][1] = f[v][0];
				f[v][0] = 0;
			}
		}

		recur (0, NA);
		writeln (f[0][1]);
	}
}


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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (i; 0..t)
	{
		auto a = RD!int;
		auto b = RD!int;
		if (min(a, b)*2 < max(a, b))
			ans[i] = false;
		else
			ans[i] = (a+b) % 3 == 0;
	}

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

import std.stdio;

void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]))
      foreach(ref e; args[i])
	read(e);
    else
      readf!" %s"(args[i]);
}
alias r = read;
alias w = writeln;

int main()
{
  int t;
  r(t);
  while(t--)
    {
      long a, b;
      r(a, b);
      long r = 2 * b - a;
      if (r % 3 == 0 && r >= 0 && (b - 2 * r / 3) >= 0)
	{
	  w("YES");
	}
      else
	{
	  w("NO");
	}
    }
  return 0;
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); }
void log()(){ writeln(""); } void log(T, A ...)(T t, lazy A a){ if(DEBUG) write(t, " "), log(a); } bool DEBUG = 0;
string rstring(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T rtype(T)(){ return rstring.to!T; } alias rint = rtype!int, rlong = rtype!long, rreal = rtype!real;
T[] rtypes(T)(int n){ return n.iota.map!(i => rtype!T()).array; } alias rint = rtypes!int, rlong = rtypes!long, rreal = rtypes!real;
T[][] rtypess(T)(int n, int m){ return n.iota.map!(i => rtypes!T(m)).array; } alias rint = rtypess!int, rlong = rtypess!long, rreal = rtypess!real;
T chmin(T)(ref T x, T y){ if(x > y) x = y; return x; } T chmax(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
	int t = rint;
	foreach(_; 0 .. t){
		long a = rlong, b = rlong;
		string ans = "YES";
		if((a + b) % 3 != 0) ans = "NO";
		if(a < (a + b) / 3) ans = "NO";
		if(b < (a + b) / 3) ans = "NO";
		ans.writeln;
	}
}

import std.stdio;

void read(T...)(ref T args)
{
  import std.traits;
  static foreach(i; 0 .. T.length)
    static if(isArray!(T[i]))
      foreach(ref e; args[i])
	read(e);
    else
      readf!" %s"(args[i]);
}
alias r = read;
alias w = writeln;

int main()
{
  int t;
  r(t);
  while(t--)
    {
      long a, b;
      r(a, b);
      long r = 2 * b - a;
      if (r % 3 == 0)
	{
	  w("YES");
	}
      else
	{
	  w("NO");
	}
    }
  return 0;
}

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

string FMT_F = "%.10f";

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

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

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

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

void main()
{
	auto t = RD!int;
	auto ans = new bool[](t);
	foreach (i; 0..t)
	{
		auto a = RD!int;
		auto b = RD!int;
		ans[i] = (a+b) % 3 == 0;
	}

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


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

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

    immutable int MXD = 10 ^^ 6;
    immutable int INFINT = 10 ^^ 9 + 23;
    immutable long INF = 10L ^^ 18 + 23;

    alias rbt = RedBlackTree!(int, "a < b", true);
    auto arrival = new int[] (n+1);
    auto depart = new rbt[] (n+1);
    foreach (i; 0 .. n+1) {
        arrival[i] = INFINT;
        depart[i] = make!(rbt);
    }

    alias pr = Tuple!(int, int);
    auto flightsIn = new pr[][] (MXD + 1);
    auto flightsOut = new pr[][] (MXD + 1);
    long curv = 0;
    foreach (_; 0 .. m) {
        int d, f, t, c;
        readf("%s %s %s %s", &d, &f, &t, &c);
        readln;

        if (f != 0) {
            flightsIn[d] ~= tuple(f, c);
        } else {
            flightsOut[d] ~= tuple(t, c);
            if (!depart[t].empty()) { curv -= depart[t].front; }
            depart[t].insert(c);
            curv += depart[t].front;
        }

    }

    if (depart.dropOne.any!(c => c.empty())) {
        writeln(-1);
        return;
    }

    int badSets = n;
    long ans = INF;
    outer: foreach (rborder; 0 .. MXD+1 - k) {
        foreach (t; flightsOut[rborder]) {
            curv -= depart[t[0]].front;
            depart[t[0]].removeKey(t[1]);

            if (depart[t[0]].empty()) { break outer; }

            curv += depart[t[0]].front;
        }

        if (rborder < k) { continue; }

        foreach (t; flightsIn[rborder-k]) {
            if (arrival[t[0]] == INFINT) { badSets -= 1; }
            else { curv -= arrival[t[0]]; }

            arrival[t[0]] = min(arrival[t[0]], t[1]);
            curv += arrival[t[0]];
        }

        if (badSets == 0) { ans = min(ans, curv); }
    }

    writeln(ans != INF ? ans : -1);
}

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;

immutable long INF = 1L << 59;

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

    auto go = new Tuple!(int, long)[][](N);
    auto back = new Tuple!(int, long)[][](N);

    foreach (_; 0..M) {
        s = readln.split.map!(to!int);
        if (s[2] == 0)
            go[s[1]-1] ~= tuple(s[0], s[3].to!long);
        else
            back[s[2]-1] ~= tuple(s[0], s[3].to!long);
    }

    foreach (i; 0..N)
        go[i].sort!"a[0] < b[0]"();
    foreach (i; 0..N)
        back[i].sort!"a[0] < b[0]"();

    if (go.map!(g => g.length == 0).any ||
        back.map!(b => b.length == 0).any) {
        writeln(-1);
        return;
    }

    foreach (i; 0..N)
        foreach (j; 1..go[i].length)
            go[i][j][1] = min(go[i][j][1], go[i][j-1][1]);

    foreach (i; 0..N)
        for (int j = back[i].length.to!int - 1; j >= 1; --j)
            back[i][j-1][1] = min(back[i][j-1][1], back[i][j][1]);

    auto q1 = new BinaryHeap!(Array!(Tuple!(int, int, long)), "a[0] > b[0]");
    auto q2 = new BinaryHeap!(Array!(Tuple!(int, int, long)), "a[0] > b[0]");

    foreach (i; 0..N)
        foreach (j; 0..go[i].length)
            q1.insert(tuple(go[i][j][0], i, go[i][j][1]));
    foreach (i; 0..N)
        foreach (j; 0..back[i].length)
            q2.insert(tuple(back[i][j][0], i, (j + 1 == back[i].length ? INF : back[i][j+1][1])));

    int used_cnt = 0;
    auto used = new bool[](N);
    auto ans1 = new long[](N);
    auto ans2 = new long[](N);
    foreach (i; 0..N)
        ans2[i] = back[i][0][1];
    long sum1 = 0;
    long sum2 = ans2.sum;
    long ans = INF;
    bool end = false;

    while (!q1.empty && !end) {
        auto t = q1.front;
        auto d = t[0];
        auto n = t[1];
        auto c = t[2];
        q1.removeFront;
        sum1 -= ans1[n];
        ans1[n] = c;
        sum1 += ans1[n];
        if (!used[n]) {
            used_cnt += 1;
            used[n] = true;
        }

        if (used_cnt < N)
            continue;

        while (!q2.empty && q2.front()[0] <= d + K) {
            t = q2.front;
            n = t[1];
            c = t[2];
            q2.removeFront;

            if (c == INF) {
                end = true;
                break;
            }

            sum2 -= ans2[n];
            ans2[n] = c;
            sum2 += ans2[n];
        }

        if (!end)
            ans = min(ans, sum1 + sum2);
    }

    if (ans >= INF)
        ans = -1;
    ans.writeln;
}

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

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

    alias rbt = RedBlackTree!(int, "a < b", true);
    auto arrivals = new rbt[] (n+1);
    auto depart = new rbt[] (n+1);
    foreach (i; 0 .. n+1) {
        arrivals[i] = make!(rbt);
        depart[i] = make!(rbt);
    }

    immutable int MXD = 10 ^^ 6;

    alias pr = Tuple!(int, int);
    auto flightsIn = new pr[][] (MXD + 1);
    auto flightsOut = new pr[][] (MXD + 1);
    long curv = 0;
    foreach (_; 0 .. m) {
        int d, f, t, c;
        readf("%s %s %s %s", &d, &f, &t, &c);
        readln;

        if (f != 0) {
            flightsIn[d] ~= tuple(f, c);
        } else {
            flightsOut[d] ~= tuple(t, c);
            if (!depart[t].empty()) { curv -= depart[t].front; }
            depart[t].insert(c);
            curv += depart[t].front;
        }

    }

    if (depart.dropOne.any!(c => c.empty())) {
        writeln(-1);
        return;
    }

    immutable long INF = 10L ^^ 18 + 23;
    int badSets = n;
    long ans = INF;
    outer: foreach (rborder; 0 .. MXD+1 - k) {
        foreach (t; flightsOut[rborder]) {
            curv -= depart[t[0]].front;
            depart[t[0]].removeKey(t[1]);

            if (depart[t[0]].empty()) { break outer; }

            curv += depart[t[0]].front;
        }

        if (rborder < k) { continue; }

        foreach (t; flightsIn[rborder-k]) {
            if (arrivals[t[0]].empty()) { badSets -= 1; }
            else { curv -= arrivals[t[0]].front; }

            arrivals[t[0]].insert(t[1]);
            curv += arrivals[t[0]].front;
        }

        if (badSets == 0) { ans = min(ans, curv); }
    }

    writeln(ans != INF ? ans : -1);
}

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

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

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

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

enum INF = 10L^^13;

void main() {
  try {
    for (; ; ) {
      const N = readInt();
      const M = readInt();
      const K = readInt();
      auto D = new int[M];
      auto S = new int[M];
      auto T = new int[M];
      auto C = new long[M];
      foreach (i; 0 .. M) {
        D[i] = readInt();
        S[i] = readInt() - 1;
        T[i] = readInt() - 1;
        C[i] = readLong();
      }

      const dLim = (M == 0) ? 1 : (D.maxElement + 1);
      auto iss = new int[][dLim];
      foreach (i; 0 .. M) {
        iss[D[i]] ~= i;
      }

      auto ls = new long[dLim];
      auto rs = new long[dLim];

      long now;
      auto mns = new long[N];

      mns[] = INF;
      now = N * INF;
      foreach (d; 0 .. dLim) {
        foreach (i; iss[d]) {
          if (T[i] == -1) {
            now -= mns[S[i]];
            chmin(mns[S[i]], C[i]);
            now += mns[S[i]];
          }
        }
        ls[d] = now;
      }

      mns[] = INF;
      now = N * INF;
      foreach_reverse (d; 0 .. dLim) {
        foreach (i; iss[d]) {
          if (S[i] == -1) {
            now -= mns[T[i]];
            chmin(mns[T[i]], C[i]);
            now += mns[T[i]];
          }
        }
        rs[d] = now;
      }

      long ans = INF;
      foreach (d; 0 .. dLim - K - 1) {
        chmin(ans, ls[d] + rs[d + K + 1]);
      }
      writeln((ans >= INF) ? -1 : ans);
    }
  } catch (EOFException e) {
  }
}

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

immutable long INF = 1L << 59;

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

    auto go = new Tuple!(int, long)[][](N);
    auto back = new Tuple!(int, long)[][](N);

    foreach (_; 0..M) {
        s = readln.split.map!(to!int);
        if (s[2] == 0)
            go[s[1]-1] ~= tuple(s[0], s[3].to!long);
        else
            back[s[2]-1] ~= tuple(s[0], s[3].to!long);
    }

    foreach (i; 0..N)
        go[i].sort!"a[0] < b[0]"();
    foreach (i; 0..N)
        back[i].sort!"a[0] < b[0]"();

    if (go.map!(g => g.length == 0).any ||
        back.map!(b => b.length == 0).any) {
        writeln(-1);
        return;
    }

    foreach (i; 0..N)
        foreach (j; 1..go[i].length)
            go[i][j][1] = min(go[i][j][1], go[i][j-1][1]);

    foreach (i; 0..N)
        for (int j = back[i].length.to!int - 1; j >= 1; --j)
            back[i][j-1][1] = min(back[i][j-1][1], back[i][j][1]);

    auto q1 = new BinaryHeap!(Array!(Tuple!(int, int, long)), "a[0] > b[0]");
    auto q2 = new BinaryHeap!(Array!(Tuple!(int, int, long)), "a[0] > b[0]");

    foreach (i; 0..N)
        foreach (j; 0..go[i].length)
            q1.insert(tuple(go[i][j][0], i, go[i][j][1]));
    foreach (i; 0..N)
        foreach (j; 0..back[i].length)
            q2.insert(tuple(back[i][j][0], i, (j + 1 == back[i].length ? INF : back[i][j+1][1])));

    int used_cnt = 0;
    auto used = new bool[](N);
    auto ans1 = new long[](N);
    auto ans2 = new long[](N);
    foreach (i; 0..N)
        ans2[i] = back[i][0][1];
    long sum1 = 0;
    long sum2 = ans2.sum;
    long ans = INF;

    while (!q1.empty) {
        auto t = q1.front;
        auto d = t[0];
        auto n = t[1];
        auto c = t[2];
        q1.removeFront;
        sum1 -= ans1[n];
        ans1[n] = c;
        sum1 += ans1[n];
        if (!used[n]) {
            used_cnt += 1;
            used[n] = true;
        }

        if (used_cnt < N)
            continue;

        while (!q2.empty && q2.front()[0] <= d + K) {
            t = q2.front;
            n = t[1];
            c = t[2];
            q2.removeFront;
            sum2 -= ans2[n];
            ans2[n] = c;
            sum2 += ans2[n];
        }

        ans = min(ans, sum1 + sum2);
    }

    if (ans >= INF)
        ans = -1;
    ans.writeln;
}

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

immutable long INF = 1L << 59;

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

    auto go = new Tuple!(int, long)[][](N);
    auto back = new Tuple!(int, long)[][](N);

    foreach (_; 0..M) {
        s = readln.split.map!(to!int);
        if (s[2] == 0)
            go[s[1]-1] ~= tuple(s[0], s[3].to!long);
        else
            back[s[2]-1] ~= tuple(s[0], s[3].to!long);
    }

    foreach (i; 0..N)
        go[i].sort!"a[0] < b[0]"();
    foreach (i; 0..N)
        back[i].sort!"a[0] < b[0]"();

    if (go.map!(g => g.length == 0).any ||
        back.map!(b => b.length == 0).any) {
        writeln(-1);
        return;
    }

    foreach (i; 0..N)
        foreach (j; 1..go[i].length)
            go[i][j][1] = min(go[i][j][1], go[i][j-1][1]);

    foreach (i; 0..N)
        for (int j = back[i].length.to!int - 1; j >= 1; --j)
            back[i][j-1][1] = min(back[i][j-1][1], back[i][j][1]);

    auto q1 = new BinaryHeap!(Array!(Tuple!(int, int, long)), "a[0] > b[0]");
    auto q2 = new BinaryHeap!(Array!(Tuple!(int, int, long)), "a[0] > b[0]");

    foreach (i; 0..N)
        foreach (j; 0..go[i].length)
            q1.insert(tuple(go[i][j][0], i, go[i][j][1]));
    foreach (i; 0..N)
        foreach (j; 0..back[i].length)
            q2.insert(tuple(back[i][j][0], i, (j + 1 == back[i].length ? INF : back[i][j+1][1])));

    int used_cnt = 0;
    auto used = new bool[](N);
    auto ans1 = new long[](N);
    auto ans2 = new long[](N);
    foreach (i; 0..N)
        ans2[i] = back[i][0][1];
    long sum1 = 0;
    long sum2 = ans2.sum;
    long ans = INF;

    while (!q1.empty) {
        auto t = q1.front;
        auto d = t[0];
        auto n = t[1];
        auto c = t[2];
        q1.removeFront;
        sum1 -= ans1[n];
        ans1[n] = c;
        sum1 += ans1[n];
        if (!used[n]) {
            used_cnt += 1;
            used[n] = true;
        }

        if (used_cnt < N)
            continue;

        while (!q2.empty && q2.front()[0] <= d + K) {
            t = q2.front;
            d = t[0];
            n = t[1];
            c = t[2];
            q2.removeFront;
            sum2 -= ans2[n];
            ans2[n] = c;
            sum2 += ans2[n];
        }

        ans = min(ans, sum1 + sum2);
    }

    if (ans >= INF)
        ans = -1;
    ans.writeln;
}