Mike has always been thinking about the harshness of social inequality. He's so obsessed with it that sometimes it even affects him while solving problems. At the moment, Mike has two sequences of positive integers A = [a1, a2, ..., an] and B = [b1, b2, ..., bn] of length n each which he uses to ask people some quite peculiar questions.To test you on how good are you at spotting inequality in life, he wants you to find an "unfair" subset of the original sequence. To be more precise, he wants you to select k numbers P = [p1, p2, ..., pk] such that 1 ≤ pi ≤ n for 1 ≤ i ≤ k and elements in P are distinct. Sequence P will represent indices of elements that you'll select from both sequences. He calls such a subset P "unfair" if and only if the following conditions are satisfied: 2·(ap1 + ... + apk) is greater than the sum of all elements from sequence A, and 2·(bp1 + ... + bpk) is greater than the sum of all elements from the sequence B. Also, k should be smaller or equal to  because it will be to easy to find sequence P if he allowed you to select too many elements!Mike guarantees you that a solution will always exist given the conditions described above, so please help him satisfy his curiosity!

The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the sequences.  On the second line there are n space-separated integers a1, ..., an (1 ≤ ai ≤ 109) — elements of sequence A. On the third line there are also n space-separated integers b1, ..., bn (1 ≤ bi ≤ 109) — elements of sequence B.

On the first line output an integer k which represents the size of the found subset. k should be less or equal to . On the next line print k integers p1, p2, ..., pk (1 ≤ pi ≤ n) — the elements of sequence P. You can print the numbers in any order you want. Elements in sequence P should be distinct.

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

void main()
{
	version(ONLINE_JUDGE){}
	else
	{
		assert(freopen("input.txt","r",core.stdc.stdio.stdin));
		assert(freopen("output.txt","w",core.stdc.stdio.stdout));
	}
	int n;
loop:while(read(n))
	{
		auto a=arread!(int),b=arread!int;
		if(n==2)
		{
			writeln("2\n1 2");
		}
		else if(n==1)writeln("1\n1");
		else
		{
			auto p=iota(0,n).array;
			sort!((int x,int y){return a[x]>a[y];})(p);
			int[] ans;
			auto st=new int[n],u=new bool[n];
			int pos;
			foreach(x;p)
			{
				if(pos==0)st[pos++]=x;
				else if(b[st[pos-1]]>b[x])
				{
					u[st[pos-1]]=u[x]=1;
					ans~=st[pos-1];
					pos--;
				}
				else st[pos++]=x;
			}
			int[] v;
			foreach(x;p)
			{
				if(!u[x])v~=x;
			}
			foreach(i;0..v.length)
			{
				if(i%2==0 || i==sz(v)-1)ans~=v[i];
			}
			writeln(ans.length);
			foreach(x;ans)write(x+1,' ');
		}
	}
}


You are planning to build housing on a street. There are $$$n$$$ spots available on the street on which you can build a house. The spots are labeled from $$$1$$$ to $$$n$$$ from left to right. In each spot, you can build a house with an integer height between $$$0$$$ and $$$h$$$.In each spot, if a house has height $$$a$$$, you can gain $$$a^2$$$ dollars from it.The city has $$$m$$$ zoning restrictions though. The $$$i$$$-th restriction says that if the tallest house from spots $$$l_i$$$ to $$$r_i$$$ is strictly more than $$$x_i$$$, you must pay a fine of $$$c_i$$$.You would like to build houses to maximize your profit (sum of dollars gained minus fines). Determine the maximum profit possible.

The first line contains three integers $$$n,h,m$$$ ($$$1 \leq n,h,m \leq 50$$$) — the number of spots, the maximum height, and the number of restrictions, respectively. Each of the next $$$m$$$ lines contains four integers $$$l_i, r_i, x_i, c_i$$$ ($$$1 \leq l_i \leq r_i \leq n$$$, $$$0 \leq x_i \leq h$$$, $$$1 \leq c_i \leq 5\,000$$$).

Print a single integer denoting the maximum profit you can make.

NoteIn the first example, it's optimal to build houses with heights $$$[1, 3, 2]$$$. We get a gain of $$$1^2+3^2+2^2 = 14$$$. We don't violate any restrictions, so there are no fees, so the total profit is $$$14 - 0 = 14$$$.In the second example, it's optimal to build houses with heights $$$[10, 8, 8, 10]$$$. We get a gain of $$$10^2+8^2+8^2+10^2 = 328$$$, and we violate the second restriction for a fee of $$$39$$$, thus the total profit is $$$328-39 = 289$$$. Note that even though there isn't a restriction on building $$$1$$$, we must still limit its height to be at most $$$10$$$.

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

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

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

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

class MaxFlow(Capa) {
  enum Capa wEPS = 0;
  enum Capa wINF = 10^^9;
  int n, m;
  int[][] g;
  int[] zu;
  Capa[] capa;
  Capa tof;
  int[] lev, see, que;
  this(int n) {
    this.n = n; m = 0; g = new int[][n]; zu = []; capa = [];
    lev = new int[n]; see = new int[n]; que = new int[n];
  }
  void addEdge(int u, int v, Capa w0, Capa w1 = 0) {
    g[u] ~= m; zu ~= v; capa ~= w0; ++m;
    g[v] ~= m; zu ~= u; capa ~= w1; ++m;
  }
  Capa augment(int src, int ink, Capa flo) {
    if (src == ink) return flo;
    foreach (i; g[src][see[src] .. $]) {
      if (capa[i] > wEPS && lev[src] < lev[zu[i]]) {
        Capa f = augment(zu[i], ink, min(flo, capa[i]));
        if (f > wEPS) { capa[i] -= f; capa[i ^ 1] += f; return f; }
      }
      ++see[src];
    }
    return 0;
  }
  bool dinic(int src, int ink, Capa flo = wINF) {
    for (tof = 0; tof + wEPS < flo; ) {
      int[] q;
      lev[] = -1;
     dinicBFS:
      for (lev[src] = 0, q ~= src; !q.empty; ) {
        int u = q.front; q.popFront;
        foreach (i; g[u]) {
          int v = zu[i];
          if (capa[i] > wEPS && lev[v] == -1) {
            lev[v] = lev[u] + 1; q ~= v;
            if (v == ink) break dinicBFS;
          }
        }
      }
      if (lev[ink] == -1) return false;
      see[] = 0;
      for (; ; ) {
        Capa f = augment(src, ink, flo - tof);
        if (f <= wEPS) break;
        tof += f;
      }
    }
    return true;
  }
}

int N, H, M;
int[] L, R, X, C;

void main() {
  try {
    for (; ; ) {
      N = readInt();
      H = readInt();
      M = readInt();
      L = new int[M];
      R = new int[M];
      X = new int[M];
      C = new int[M];
      foreach (i; 0 .. M) {
        L[i] = readInt() - 1;
        R[i] = readInt();
        X[i] = readInt();
        C[i] = readInt();
      }

      enum INF = 10^^9;
      auto mf = new MaxFlow!int(2 + M + N * (H + 1));
      int id(int j, int h) {
        return 2 + M + j * (H + 1) + h;
      }
      foreach (i; 0 .. M) {
        // if >= X[i], fine
        if (X[i] < H) {
          foreach (j; L[i] .. R[i]) {
            mf.addEdge(id(j, X[i] + 1), 2 + i, INF);
          }
          mf.addEdge(2 + i, 1, C[i]);
        }
      }
      foreach (j; 0 .. N) {
        foreach (h; 0 .. H) {
          mf.addEdge(id(j, h + 1), id(j, h), INF);
        }
        foreach (h; 0 .. H) {
          mf.addEdge(0, id(j, h + 1), (h + 1)^^2 - h^^2);
        }
        mf.addEdge(0, id(j, 0), INF);
      }
      mf.dinic(0, 1);

      int ans;
      foreach (j; 0 .. N) {
        ans += H^^2;
      }
      ans -= mf.tof;
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


Alyona has recently bought a miniature fridge that can be represented as a matrix with $$$h$$$ rows and $$$2$$$ columns. Initially there is only one shelf at the bottom of the fridge, but Alyona can install arbitrary number of shelves inside the fridge between any two rows. A shelf is two cells wide, does not occupy any space but separates the inside of the fridge to the lower and upper part.  An example of a fridge with $$$h = 7$$$ and two shelves. The shelves are shown in black. The picture corresponds to the first example. Alyona has $$$n$$$ bottles of milk that she wants to put in the fridge. The $$$i$$$-th bottle is $$$a_i$$$ cells tall and $$$1$$$ cell wide. She can put a bottle on some shelf if the corresponding space above the shelf is at least as tall as the bottle. She can not put a bottle on top of another bottle (if there is no shelf between them). Two bottles can not share a cell.Alyona is interested in the largest integer $$$k$$$ such that she can put bottles $$$1$$$, $$$2$$$, ..., $$$k$$$ in the fridge at the same time. Find this largest $$$k$$$.

The first line contains two integers $$$n$$$ and $$$h$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le h \le 10^9$$$) — the number of bottles and the height of the fridge. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le h$$$) — the heights of the bottles.

Print the single integer $$$k$$$ — the maximum integer such that Alyona can put the bottles $$$1$$$, $$$2$$$, ..., $$$k$$$ in the fridge at the same time. If Alyona can put all bottles in the fridge, print $$$n$$$. It is easy to see that Alyona can always put at least one bottle in the fridge.

NoteOne of optimal locations in the first example is shown on the picture in the statement.One of optimal locations in the second example is shown on the picture below.  One of optimal locations in the third example is shown on the picture below.

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

void main ()
{
	int n, h;
	while (readf (" %s %s", &n, &h) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		int res = 0;
		while (res <= n)
		{
			auto b = a[0..res];
			sort (b);
			long need = 0;
			for (int i = res - 1; i >= 0; i -= 2)
			{
				need += b[i];
			}
			debug {writeln (res, ": ", b, ", ", need);}
			if (need > h)
			{
				break;
			}
			res += 1;
		}
		writeln (res - 1);
	}
}

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

  int n, h;
  rd(n, h);
  auto a = readln.split.to!(int[]);

  a ~= (h + 1);
  int[] b;
  foreach (k, el; a) {
    b ~= el;
    b.sort;
    b.reverse;
    int cur_h = 0;
    bool ok = true;
    foreach (i; 0 .. b.length) {
      if (cur_h + b[i] > h) {
        ok = false;
        break;
      }
      if (i & 1) {
        cur_h += max(b[i - 1], b[i]);
      }
    }
    if (!ok) {
      writeln(k);
      break;
    }
  }

}

void rd(T...)(ref T x) {
  import std.stdio : readln;
  import std.string : split;
  import std.conv : to;

  auto l = readln.split;
  assert(l.length == x.length);
  foreach (i, ref e; x)
    e = l[i].to!(typeof(e));
}

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

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

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

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

int N;
long H;
long[] A;

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

      int lo = 0, hi = N + 1;
      for (; lo + 1 < hi; ) {
        const mid = (lo + hi) / 2;
        auto a = A[0 .. mid].dup;
        a.sort;
        long sum;
        for (int i = mid - 1; i >= 0; i -= 2) {
          sum += a[i];
        }
        (sum <= H) ? (lo = mid) : (hi = mid);
      }
      writeln(lo);
    }
  } catch (EOFException e) {
  }
}


You have an array $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ distinct integers. You are allowed to perform the following operation on it:  Choose two elements from the array $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) such that $$$\gcd(a_i, a_j)$$$ is not present in the array, and add $$$\gcd(a_i, a_j)$$$ to the end of the array. Here $$$\gcd(x, y)$$$ denotes greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Note that the array changes after each operation, and the subsequent operations are performed on the new array.What is the maximum number of times you can perform the operation on the array?

The first line consists of a single integer $$$n$$$ ($$$2 \le n \le 10^6$$$). The second line consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$). All $$$a_i$$$ are distinct.

Output a single line containing one integer — the maximum number of times the operation can be performed on the given array.

NoteIn the first example, one of the ways to perform maximum number of operations on the array is:   Pick $$$i = 1, j= 5$$$ and add $$$\gcd(a_1, a_5) = \gcd(4, 30) = 2$$$ to the array.  Pick $$$i = 2, j= 4$$$ and add $$$\gcd(a_2, a_4) = \gcd(20, 25) = 5$$$ to the array.  Pick $$$i = 2, j= 5$$$ and add $$$\gcd(a_2, a_5) = \gcd(20, 30) = 10$$$ to the array. It can be proved that there is no way to perform more than $$$3$$$ operations on the original array.In the second example one can add $$$3$$$, then $$$1$$$, then $$$5$$$, and $$$2$$$.

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

immutable int limit = 10 ^^ 6 + 3;

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		auto c = new bool [limit];
		foreach (ref x; a)
		{
			c[x] = true;
		}
		foreach_reverse (x; 1..limit)
		{
			if (!c[x])
			{
				int cur = 0;
				for (int y = x * 2; y < limit; y += x)
				{
					if (c[y])
					{
						cur = gcd (cur, y);
						if (cur == x)
						{
							break;
						}
					}
				}
				if (cur == x)
				{
					c[x] = true;
				}
			}
		}
		writeln (c.sum (0) - a.length.to !(int));
	}
}


The problem uses a simplified TCP/IP address model, please read the statement carefully.An IP address is a 32-bit integer, represented as a group of four decimal 8-bit integers (without leading zeroes), separated by commas. For example, record 0.255.1.123 shows a correct IP address and records 0.256.1.123 and 0.255.1.01 do not. In the given problem an arbitrary group of four 8-bit integers is a correct IP address.Our hero Polycarpus still works as a system administrator in some large corporation. He likes beautiful IP addresses. To check if some IP address is beautiful, he should do the following:  write out in a line four 8-bit numbers of the IP address, without the commas;  check if the resulting string is a palindrome. Let us remind you that a palindrome is a string that reads the same from right to left and from left to right.For example, IP addresses 12.102.20.121 and 0.3.14.130 are beautiful (as strings "1210220121" and "0314130" are palindromes), and IP addresses 1.20.20.1 and 100.4.4.1 are not.Polycarpus wants to find all beautiful IP addresses that have the given set of digits. Each digit from the set must occur in the IP address at least once. IP address must not contain any other digits. Help him to cope with this difficult task.

The first line contains a single integer n (1 ≤ n ≤ 10) — the number of digits in the set. The second line contains the set of integers a1, a2, ..., an (0 ≤ ai ≤ 9). It is guaranteed that all digits in the set are distinct.

In the first line print a single integer k — the number of beautiful IP addresses that contain the given set of digits. In the following k lines print the IP addresses, one per line in the arbitrary order.

import std.algorithm;
import std.container;
import std.exception;
import std.format;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

string [] res;
int [] c;
int b;

string num (int i, int j)
{
	if (c[i] == 0 && j - i > 1)
	{
		return "";
	}
	int f = 0;
	string res;
	for (int k = i; k < j; k++)
	{
		f = f * 10 + c[k];
		res ~= cast (char) (c[k] + '0');
	}
	if (f > 255)
	{
		return "";
	}
	return res;
}

void go (int i, int j, int k, int l)
{
	if (l - k < 1 || 3 < l - k)
	{
		return;
	}
	auto t1 = num (0, i);
	if (!t1.length)
	{
		return;
	}
	auto t2 = num (i, j);
	if (!t2.length)
	{
		return;
	}
	auto t3 = num (j, k);
	if (!t3.length)
	{
		return;
	}
	auto t4 = num (k, l);
	if (!t4.length)
	{
		return;
	}
	res ~= t1 ~ '.' ~ t2 ~ '.' ~ t3 ~ '.' ~ t4;
}

void build (int d)
{
	for (int i = d, j = d - 1; j >= 0; i++, j--)
	{
		c[i] = c[j];
	}
	for (int i = 1; i <= 3; i++)
	{
		for (int j = i + 1; j <= i + 3; j++)
		{
			for (int k = j + 1; k <= j + 3; k++)
			{
				go (i, j, k, d + d);
			}
		}
	}

	for (int i = d, j = d - 2; j >= 0; i++, j--)
	{
		c[i] = c[j];
	}
	for (int i = 1; i <= 3; i++)
	{
		for (int j = i + 1; j <= i + 3; j++)
		{
			for (int k = j + 1; k <= j + 3; k++)
			{
				go (i, j, k, d + d - 1);
			}
		}
	}
}

void recur (int d, int m)
{
	if (2 <= d && d <= 6 && m == b)
	{
		build (d);
	}
	if (d == 6)
	{
		return;
	}
	foreach (i; 0..10)
	{
		if (b & (1 << i))
		{
			c[d] = i;
			recur (d + 1, m | (1 << i));
		}
	}
}

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		b = 0;
		foreach (i; 0..n)
		{
			int d;
			readf (" %s", &d);
			b |= 1 << d;
		}
		res = null;
		c = new int [12];
		recur (0, 0);
		writeln (res.length);
		foreach (s; res)
		{
			writeln (s);
		}
//		writefln ("%(%s\n%)", res);
	}
}


Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the opposite poles will attract each other.Mike starts by laying one magnet horizontally on the table. During each following step Mike adds one more magnet horizontally to the right end of the row. Depending on how Mike puts the magnet on the table, it is either attracted to the previous one (forming a group of multiple magnets linked together) or repelled by it (then Mike lays this magnet at some distance to the right from the previous one). We assume that a sole magnet not linked to others forms a group of its own.  Mike arranged multiple magnets in a row. Determine the number of groups that the magnets formed.

The first line of the input contains an integer n (1 ≤ n ≤ 100000) — the number of magnets. Then n lines follow. The i-th line (1 ≤ i ≤ n) contains either characters "01", if Mike put the i-th magnet in the "plus-minus" position, or characters "10", if Mike put the magnet in the "minus-plus" position.

On the single line of the output print the number of groups of magnets.

NoteThe first testcase corresponds to the figure. The testcase has three groups consisting of three, one and two magnets.The second testcase has two groups, each consisting of two magnets.

import std.stdio;

void main() {
  int n; readf("%d\n", &n);
  string prev = "";
  int c = 0;
  for (int i = 0; i < n; i++) {
    string line; readf("%s\n", &line);
    if (line != prev) {
      //writef(line ~ " " ~ prev ~ "\n");
      c++;
      prev = line;
    }
  }
  writef("%d\n", c);
}

import std.stdio;
import core.stdc.stdio;

void main() {
    uint n, r = 1;
    scanf(`%u`, &n);

    uint l = 3;

	foreach(i; 0..n) {
		uint k;
		scanf(`%u`, &k);

		uint a = k / 10;
		uint b = k % 10;

		if(l == a) r++;
		l = b;
	}

	write(r);
}

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

void main(string[] args)
{
	int total = to!int(readln.strip);
	int countIclends, prevCode;
	for(; total > 0; --total){
		int code;
		readf(" %s", &code);
		if(code != prevCode){
			++countIclends;
			prevCode = code;
		}
	}
	writeln(countIclends);
}

import std.stdio;
import std.uni;
import std.string;
import core.stdc.stdio;
import std.array;
import std.algorithm;
import std.string;
import std.math;

int main(string[] argv)
{
	int n;
	int pm;
	scanf("%d %d", &n, &pm);
	int ng = 1;
	foreach (int i; 1..n)
	{
		int cm;
		scanf("%d", &cm);
		if (pm != cm) ng++;
		pm = cm;
	}
	printf("%d", ng);
	return 0;
}

module main;

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

void main(string[] args)
{
	readln;
	string former = "";
	int answer = 0;
	foreach(string line; stdin.lines) {
		if (line != former)
			answer++;
		former = line;
	}

	answer.writeln;
}

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

immutable int mod = 10^^9 + 7;

void main(){
    int n = readln.chomp.to!int;

    auto p = readln.chomp;

    int ans = 1;

    foreach(i ; 0 .. n - 1){
        auto magnet = readln.chomp;

        if (magnet != p) {
            ans++;
        }

        p = magnet;
    }

    writeln(ans);
}

void readVars(T...)(auto ref T args){
    auto line = readln.split;
    foreach(ref arg ; args){
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    if(!line.empty){
        writeln(line);
        throw new Exception("args num < input num");
    }
}

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

import std.stdio;

void main() {
  int n; readf("%d", &n);
  string prev = "";
  int c = 0;
  for (int i = 0; i < n; i++) {
    string line; readf("%s\n", &line);
    if (line != prev) {
      //writef(line ~ " " ~ prev ~ "\n");
      c++;
      prev = line;
    }
  }
  writef("%d\n", c);
}

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

immutable int mod = 10^^9 + 7;

void main(){
    int n = readln.chomp.to!int;

    auto p = readln.chomp;

    int ans = 1, value = 1;

    foreach(i ; 0 .. n - 1){
        auto magnet = readln.chomp;

        if (magnet == p) {
            value++;
            ans = max(ans, value);
        }
        else {
            value = 1;
        }

        p = magnet;
    }

    writeln(ans);
}

void readVars(T...)(auto ref T args){
    auto line = readln.split;
    foreach(ref arg ; args){
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    if(!line.empty){
        writeln(line);
        throw new Exception("args num < input num");
    }
}


You are given an array $$$a$$$ of $$$n$$$ elements. You can apply the following operation to it any number of times:  Select some subarray from $$$a$$$ of even size $$$2k$$$ that begins at position $$$l$$$ ($$$1\le l \le l+2\cdot{k}-1\le n$$$, $$$k \ge 1$$$) and for each $$$i$$$ between $$$0$$$ and $$$k-1$$$ (inclusive), assign the value $$$a_{l+k+i}$$$ to $$$a_{l+i}$$$. For example, if $$$a = [2, 1, 3, 4, 5, 3]$$$, then choose $$$l = 1$$$ and $$$k = 2$$$, applying this operation the array will become $$$a = [3, 4, 3, 4, 5, 3]$$$.Find the minimum number of operations (possibly zero) needed to make all the elements of the array equal.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 2 \cdot 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the array. The second line of each test case consists of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq n$$$) — the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case — the minimum number of operations needed to make equal all the elements of the array with the given operation.

NoteIn the first test, all elements are equal, therefore no operations are needed.In the second test, you can apply one operation with $$$k=1$$$ and $$$l=1$$$, set $$$a_1 := a_2$$$, and the array becomes $$$[1, 1]$$$ with $$$1$$$ operation.In the third test, you can apply one operation with $$$k=1$$$ and $$$l=4$$$, set $$$a_4 := a_5$$$, and the array becomes $$$[4, 4, 4, 4, 4]$$$.In the fourth test, you can apply one operation with $$$k=1$$$ and $$$l=3$$$, set $$$a_3 := a_4$$$, and the array becomes $$$[4, 2, 3, 3]$$$, then you can apply another operation with $$$k=2$$$ and $$$l=1$$$, set $$$a_1 := a_3$$$, $$$a_2 := a_4$$$, and the array becomes $$$[3, 3, 3, 3]$$$.In the fifth test, there is only one element, therefore no operations are needed.

import std;

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        int n;
        scanf("%d", &n);
        getchar();
        int[] a = readln.strip.split(" ").to!(int[]);
        int res = 0;
        while (a.uniq.array.length != 1)
        {
            // writeln(a);
            // writeln("len = ", a.uniq.array.length);
            int left_pad;
            int indx;
            for(int i = n - 1; i >= 0; i--)
            {
                if (a[i] == a[n-1])
                    left_pad++;
                else
                {
                    indx = i;
                    break;
                }
            }
            if (indx - left_pad + 1 > 0)
            {
                // writeln("changing from", indx - left_pad + 1, " to ", indx + 1);
                a[indx - left_pad + 1 .. indx + 1] = a[n - 1];
            }
            else
            {
                a[0 .. indx + 1] = a[n - 1];
            }
            res++;
        }
        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)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

//long mod = 10^^9 + 7;
long mod = 998_244_353;
//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 modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto t = RD!int;
	auto ans = new long[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA;

		long x = a[$-1];
		while (true)
		{
			int l = -1;
			foreach_reverse (i; 0..n)
			{
				if (a[i] != x)
				{
					l = i;
					break;
				}
			}
			if (l == -1) break;
			int len = n - l - 1;
			foreach (i; 0..len)
			{
				if (l - i < 0) break;
				a[l-i] = x;
			}
			++ans[ti];
		}
	}

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


You are given an undirected unrooted tree, i.e. a connected undirected graph without cycles.You must assign a nonzero integer weight to each vertex so that the following is satisfied: if any vertex of the tree is removed, then each of the remaining connected components has the same sum of weights in its vertices.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$3 \leq n \leq 10^5$$$) — the number of vertices of the tree. The next $$$n-1$$$ lines of each case contain each two integers $$$u, v$$$ ($$$1 \leq u,v \leq n$$$) denoting that there is an edge between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the given edges form a tree. The sum of $$$n$$$ for all test cases is at most $$$10^5$$$.

For each test case, you must output one line with $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$, where $$$a_i$$$ is the weight assigned to vertex $$$i$$$. The weights must satisfy $$$-10^5 \leq a_i \leq 10^5$$$ and $$$a_i \neq 0$$$. It can be shown that there always exists a solution satisfying these constraints. If there are multiple possible solutions, output any of them.

NoteIn the first case, when removing vertex $$$1$$$ all remaining connected components have sum $$$5$$$ and when removing vertex $$$3$$$ all remaining connected components have sum $$$2$$$. When removing other vertices, there is only one remaining connected component so all remaining connected components have the same sum.

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = new int [] [n];
		auto d = new int [n];
		foreach (i; 0..n - 1)
		{
			int u, v;
			readf !(" %s %s") (u, v);
			u -= 1;
			v -= 1;
			a[u] ~= v;
			a[v] ~= u;
			d[u] += 1;
			d[v] += 1;
		}
		readln;

		auto w = new int [n];

		void recur (int v, int p, int c)
		{
			w[v] = c * d[v];
			foreach (u; a[v])
			{
				if (u == p)
				{
					continue;
				}
				recur (u, v, -c);
			}
		}

		recur (0, -1, 1);
		writefln !("%(%s %)") (w);
	}
}


Vanya is doing his maths homework. He has an expression of form , where x1, x2, ..., xn are digits from 1 to 9, and sign  represents either a plus '+' or the multiplication sign '*'. Vanya needs to add one pair of brackets in this expression so that to maximize the value of the resulting expression.

The first line contains expression s (1 ≤ |s| ≤ 5001, |s| is odd), its odd positions only contain digits from 1 to 9, and even positions only contain signs  +  and  * .  The number of signs  *  doesn't exceed 15.

In the first line print the maximum possible value of an expression.

NoteNote to the first sample test. 3 + 5 * (7 + 8) * 4 = 303.Note to the second sample test. (2 + 3) * 5 = 25.Note to the third sample test. (3 * 4) * 5 = 60 (also many other variants are valid, for instance, (3) * 4 * 5 = 60).

import std.stdio;
import std.c.stdio;
import std.math;
import std.algorithm;
import std.conv;
import std.string;
import std.array;
import std.ascii;

long factor(string s, ref int p) {
  if (s[p] == '(') {
    p++;
    long r = expr(s, p);
    assert(s[p] == ')');
    p++;
    return r;
  } else if ('0' <= s[p] && s[p] <= '9') {
    long r = s[p] - '0';
    p++;
    return r;
  } else {
    assert(false);
  }
}

long term(string s, ref int p) {
  long r = factor(s, p);
  while (s[p] == '*') {
    p++;
    r *= factor(s, p);
  }
  return r;
}

long expr(string s, ref int p) {
  long r = term(s, p);
  while (s[p] == '+') {
    p++;
    r += term(s, p);
  }
  return r;
}

void main() {
  string s = readln().strip();
  s = "1*" ~ s ~ "*1$";
  int n = cast(int)s.length;
  long ans = 0;
  foreach (i; 0..n) {
    if (s[i] == '*') {
      foreach (j; i+1..n) {
        if (s[j] == '*') {
          int p = 0;
          p = 0;
          ans = max(ans, expr(s[0..i+1] ~ "(" ~ s[i+1..j] ~ ")" ~ s[j..$], p));
        }
      }
    }
  }
  writeln(ans);
}

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

long evalIt(ref string s,string sub){
	if(s.ptr==sub.ptr){
		auto l=sub.length;
		auto r=evalPlus(sub,null);
		s=s[l..$];
		return r;
	}
	long r=s[0]-'0';
	s=s[1..$];
	return r;
}

long evalMult(ref string s,string sub){
	long cur=evalIt(s,sub);
	while(s.length&&s[0]=='*'){
		s=s[1..$];
		cur*=evalIt(s,sub);
	}
	return cur;
}

long evalPlus(ref string s,string sub){
	long cur=evalMult(s,sub);
	while(s.length){
		assert(s[0]=='+');
		s=s[1..$];
		cur+=evalMult(s,sub);
	}
	return cur;
}

void main(){
	string it=readln.strip;
	string ott=it;
	long cand=evalPlus(ott,null);
	foreach(i;0..it.length){
		if(it[i]=='*'){
			foreach(j;i+2..it.length+1){
				if(j==it.length||it[j]=='+'||it[j]=='*'){
					string ot=it;
					cand=max(cand,evalPlus(ot,it[i+1..j]));
				}
			}
			foreach(j;0..i){
				if(it[j]!='+'&&it[j]!='*'){
					string ot=it;
					cand=max(cand,evalPlus(ot,it[j..i]));
				}
			}
		}
	}
	writeln(cand);
}

import std.stdio;
import std.c.stdio;
import std.math;
import std.algorithm;
import std.conv;
import std.string;
import std.array;
import std.ascii;

long factor(string s, ref int p) {
  if (s[p] == '(') {
    p++;
    long r = expr(s, p);
    assert(s[p++] == ')');
    return r;
  } else if (s[p].isDigit()) {
    return s[p++] - '0';
  } else {
    assert(false);
  }
}

long term(string s, ref int p) {
  long r = factor(s, p);
  while (s[p] == '*') {
    p++;
    r *= factor(s, p);
  }
  return r;
}

long expr(string s, ref int p) {
  long r = term(s, p);
  while (s[p] == '+') {
    p++;
    r += term(s, p);
  }
  return r;
}

void main() {
  string s = readln().strip();
  s = "1*" ~ s ~ "*1$";
  int n = cast(int)s.length;
  long ans = 0;
  foreach (i; 0..n) {
    if (s[i] == '*') {
      foreach (j; i+1..n) {
        if (s[j] == '*') {
          int p = 0;
          ans = max(ans, expr(s[0..i+1] ~ "(" ~ s[i+1..j] ~ ")" ~ s[j..$], p));
        }
      }
    }
  }
  writeln(ans);
}

import std.stdio;
import std.c.stdio;
import std.math;
import std.algorithm;
import std.conv;
import std.string;
import std.array;
import std.ascii;

long factor(string s, ref int p) {
  if (s[p] == '(') {
    p++;
    long r = expr(s, p);
    assert(s[p++] == ')');
    return r;
  } else if ('0' <= s[p] && s[p] <= '9') {
    return s[p++] - '0';
  } else {
    assert(false);
  }
}

long term(string s, ref int p) {
  long r = factor(s, p);
  while (s[p] == '*') {
    p++;
    r *= factor(s, p);
  }
  return r;
}

long expr(string s, ref int p) {
  long r = term(s, p);
  while (s[p] == '+') {
    p++;
    r += term(s, p);
  }
  return r;
}

void main() {
  string s = readln().strip();
  s = "1*" ~ s ~ "*1$";
  int n = cast(int)s.length;
  long ans = 0;
  foreach (i; 0..n) {
    if (s[i] == '*') {
      foreach (j; i+1..n) {
        if (s[j] == '*') {
          int p = 0;
          ans = max(ans, expr(s[0..i+1] ~ "(" ~ s[i+1..j] ~ ")" ~ s[j..$], p));
        }
      }
    }
  }
  writeln(ans);
}

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

long evalIt(ref string s,string sub){
	if(s.ptr==sub.ptr){
		auto l=sub.length;
		auto r=evalPlus(sub,null);
		s=s[l..$];
		return r;
	}
	long r=s[0]-'0';
	s=s[1..$];
	return r;
}

long evalMult(ref string s,string sub){
	long cur=evalIt(s,sub);
	while(s.length&&s[0]=='*'){
		s=s[1..$];
		cur*=evalIt(s,sub);
	}
	return cur;
}

long evalPlus(ref string s,string sub){
	long cur=evalMult(s,sub);
	while(s.length){
		assert(s[0]=='+');
		s=s[1..$];
		if(s.ptr==sub.ptr) cur+=evalIt(s,sub);
		else cur+=evalMult(s,sub);
	}
	return cur;
}

void main(){
	string it=readln.strip;
	string ott=it;
	long cand=evalPlus(ott,null);
	foreach(i;0..it.length){
		if(it[i]=='*'){
			foreach(j;i+1..it.length){
				if(it[j]=='+'||it[j]=='*'){
					string ot=it;
					cand=max(cand,evalPlus(ot,it[i+1..j]));
				}
			}
			foreach(j;0..i-1){
				if(it[j]!='+'&&it[j]!='*'){
					string ot=it;
					cand=max(cand,evalPlus(ot,it[j..i]));
				}
			}
		}
	}
	writeln(cand);
}

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

long evalIt(ref string s,string sub){
	if(s.ptr==sub.ptr){
		auto l=sub.length;
		auto r=evalPlus(sub,null);
		s=s[l..$];
		return r;
	}
	long r=s[0]-'0';
	s=s[1..$];
	return r;
}

long evalMult(ref string s,string sub){
	long cur=evalIt(s,sub);
	while(s.length&&s[0]=='*'){
		s=s[1..$];
		cur*=evalIt(s,sub);
	}
	return cur;
}

long evalPlus(ref string s,string sub){
	long cur=evalMult(s,sub);
	while(s.length){
		assert(s[0]=='+');
		s=s[1..$];
		if(s.ptr==sub.ptr) cur+=evalIt(s,sub);
		else cur+=evalMult(s,sub);
	}
	return cur;
}

void main(){
	string it=readln.strip;
	string ott=it;
	long cand=evalPlus(ott,null);
	foreach(i;0..it.length){
		if(it[i]=='*'){
			foreach(j;i+2..it.length){
				if(it[j]=='+'||it[j]=='*'){
					string ot=it;
					cand=max(cand,evalPlus(ot,it[i+1..j]));
				}
			}
			foreach(j;0..i-1){
				if(it[j]!='+'&&it[j]!='*'){
					string ot=it;
					cand=max(cand,evalPlus(ot,it[j..i]));
				}
			}
		}
	}
	writeln(cand);
}

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

long evalIt(ref string s,string sub){
	if(s.ptr==sub.ptr){
		auto l=sub.length;
		auto r=evalPlus(sub,null);
		s=s[l..$];
		return r;
	}
	long r=s[0]-'0';
	s=s[1..$];
	return r;
}

long evalMult(ref string s,string sub){
	long cur=evalIt(s,sub);
	while(s.length&&s[0]=='*'){
		s=s[1..$];
		cur*=evalIt(s,sub);
	}
	return cur;
}

long evalPlus(ref string s,string sub){
	long cur=evalMult(s,sub);
	while(s.length){
		assert(s[0]=='+');
		s=s[1..$];
		if(s.ptr==sub.ptr) cur+=evalIt(s,sub);
		else cur+=evalMult(s,sub);
	}
	return cur;
}

void main(){
	string it=readln.strip;
	string ott=it;
	long cand=evalPlus(ott,null);
	foreach(i;0..it.length){
		if(it[i]=='*'){
			foreach(j;i+2..it.length+1){
				if(j==it.length||it[j]=='+'||it[j]=='*'){
					string ot=it;
					cand=max(cand,evalPlus(ot,it[i+1..j]));
				}
			}
			foreach(j;0..i-1){
				if(it[j]!='+'&&it[j]!='*'){
					string ot=it;
					cand=max(cand,evalPlus(ot,it[j..i]));
				}
			}
		}
	}
	writeln(cand);
}

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

long evalIt(ref string s,string sub){
	if(s.ptr==sub.ptr){
		auto l=sub.length;
		auto r=evalPlus(sub,null);
		s=s[l..$];
		return r;
	}
	long r=s[0]-'0';
	s=s[1..$];
	return r;
}

long evalMult(ref string s,string sub){
	long cur=evalIt(s,sub);
	while(s.length&&s[0]=='*'){
		s=s[1..$];
		cur*=evalIt(s,sub);
	}
	return cur;
}

long evalPlus(ref string s,string sub){
	long cur=evalMult(s,sub);
	while(s.length){
		assert(s[0]=='+');
		s=s[1..$];
		if(s.ptr==sub.ptr) cur+=evalIt(s,sub);
		else cur+=evalMult(s,sub);
	}
	return cur;
}

void main(){
	string it=readln.strip;
	string ott=it;
	long cand=evalPlus(ott,null);
	foreach(i;0..it.length){
		if(it[i]=='*'){
			foreach(j;i+2..it.length+1){
				if(j==it.length||it[j]=='+'||it[j]=='*'){
					string ot=it;
					cand=max(cand,evalPlus(ot,it[i+1..j]));
				}
			}
			foreach(j;0..i){
				if(it[j]!='+'&&it[j]!='*'){
					string ot=it;
					cand=max(cand,evalPlus(ot,it[j..i]));
				}
			}
		}
	}
	writeln(cand);
}

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

long evalIt(ref string s,string sub){
	if(s.ptr==sub.ptr){
		auto l=sub.length;
		auto r=evalPlus(sub,null);
		s=s[l..$];
		return r;
	}
	long r=s[0]-'0';
	s=s[1..$];
	return r;
}

long evalMult(ref string s,string sub){
	long cur=evalIt(s,sub);
	while(s.length&&s[0]=='*'){
		s=s[1..$];
		cur*=evalIt(s,sub);
	}
	return cur;
}

long evalPlus(ref string s,string sub){
	long cur=evalMult(s,sub);
	while(s.length){
		assert(s[0]=='+');
		s=s[1..$];
		cur+=evalMult(s,sub);
	}
	return cur;
}

void main(){
	string it=readln.strip;
	string ott=it;
	long cand=evalPlus(ott,null);
	foreach(i;0..it.length){
		if(it[i]=='*'){
			foreach(j;i+1..it.length){
				if(it[j]=='+'||it[j]=='*'){
					string ot=it;
					cand=max(cand,evalPlus(ot,it[i+1..j]));
				}
			}
			foreach(j;0..i-1){
				if(it[j]!='+'&&it[j]!='*'){
					string ot=it;
					cand=max(cand,evalPlus(ot,it[j..i]));
				}
			}
		}
	}
	writeln(cand);
}


The city administration of IT City decided to fix up a symbol of scientific and technical progress in the city's main square, namely an indicator board that shows the effect of Moore's law in real time.Moore's law is the observation that the number of transistors in a dense integrated circuit doubles approximately every 24 months. The implication of Moore's law is that computer performance as function of time increases exponentially as well.You are to prepare information that will change every second to display on the indicator board. Let's assume that every second the number of transistors increases exactly 1.000000011 times.

The only line of the input contains a pair of integers n (1000 ≤ n ≤ 10 000) and t (0 ≤ t ≤ 2 000 000 000) — the number of transistors in the initial time and the number of seconds passed since the initial time.

Output one number — the estimate of the number of transistors in a dence integrated circuit in t seconds since the initial time. The relative error of your answer should not be greater than 10 - 6.

import std.stdio;
import std.math;

void main()
{
	int n, t;

	scanf("%d%d", &n, &t);
	printf("%.10f\n", n * pow(1.000000011, t));
}

import std.math;
import std.stdio;

void main ()
{
	real n, t;
	while (readf (" %s %s", &n, &t) > 0)
	{
		writefln ("%.20f", n * 1.000000011L ^^ t);
	}
}


New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows $$$h$$$ hours and $$$m$$$ minutes, where $$$0 \le hh < 24$$$ and $$$0 \le mm < 60$$$. We use 24-hour time format!Your task is to find the number of minutes before the New Year. You know that New Year comes when the clock shows $$$0$$$ hours and $$$0$$$ minutes.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1439$$$) — the number of test cases. The following $$$t$$$ lines describe test cases. The $$$i$$$-th line contains the time as two integers $$$h$$$ and $$$m$$$ ($$$0 \le h < 24$$$, $$$0 \le m < 60$$$). It is guaranteed that this time is not a midnight, i.e. the following two conditions can't be met at the same time: $$$h=0$$$ and $$$m=0$$$. It is guaranteed that both $$$h$$$ and $$$m$$$ are given without leading zeros.

For each test case, print the answer on it — the number of minutes before the New Year.

import std.stdio, std.conv, std.string, std.array, std.math, std.regex, std.range, std.ascii, std.numeric, std.random;
import std.typecons, std.functional, std.traits,std.concurrency;
import std.algorithm, std.container;
import core.bitop, core.time, core.memory;
import std.datetime;
import std.bitmanip;
import std.regex;

void main()
{
    auto N = scanElem;
    foreach (e; scanElem!(long,long)(N))
    {
        writeln(60*(24-e[0]-1)+60-e[1]);
    }
}

//辞書順順列はiota(1,N),nextPermituionを使う

enum INF = long.max/3;
enum MOD = 10L^^9+7;

T binarySearch(alias F, T)(T ok, T ng, long iter=100)
{
    alias FF = unaryFun!F;
    foreach(_;0..iter)
    {
        auto n = (ok+ng)/2;
        if(FF(n)){
            ok = n;
        }else{
            ng = n;
        }
        static if(isIntegral!T){
            if(abs(ok-ng)==1)return ok;
        }
    }
    return ok;
}

//最小を返す
real ternarySearch(alias F)(real l, real r, long iter=200)
{
    alias FF = unaryFun!F;
    foreach(_;0..iter)
    {
        auto nl = lerp(l, r, 1/real(3));
        auto nr = lerp(l, r, 2/real(3));
        if(FF(nl)<FF(nr)){
            r = nr;
        }else{
            l = nl;
        }
    }
    return FF(l);
}
long ternarySearch(alias F)(long l, long r, long iter=200)
{
    alias FF = unaryFun!F;
    foreach(_;0..iter)
    {
        auto nl = lerp(l, r, 1/real(3)).to!long;
        auto nr = lerp(l, r, 2/real(3)).to!long;
        if(FF(nl)<FF(nr)){
            r = nr;
        }else{
            l = nl;
        }
        if(r-l<4)break;
    }
    long res=INF;
    foreach(i;l..r+1)
    {
        res = min(FF(i), res);
    }
    return res;
}

real lerp(real a, real b, real t) pure
{
    return (b-a)*t+a;
}

struct Vector{
    real x, y;

    real magnitude()pure
    {
        return sqrt(sqrMagnitude);
    }
    real sqrMagnitude()pure
    {
        return x*x+y*y;
    }

    Vector opBinary(string op, T)(inout T v)
    if(isNumeric!T)
    {
        return Vector(mixin("x"~op~"v"), mixin("y"~op~"v"));
    }
    Vector opBinary(string op)(inout Vector v)
    {
        return Vector(mixin("x"~op~"v.x"), mixin("y"~op~"v.y"));
    }
    void opOpAssign(string op, T)(inout T v)
    {
        this = mixin("this"~op~"v");
    }

    static Vector lerp(Vector a, Vector b, real t)pure
    {
        return (b-a)*t+a;
    }
    static Vector normalized(Vector a)pure
    {
        auto r = a.magnitude();
        return Vector(a.x / r, a.y / r);
    }
    static real distance(Vector a, Vector b)pure
    {
        return (a-b).magnitude;
    }
    static real dot(Vector a, Vector b)pure
    {
        return a.x*b.x+a.y*b.y;
    }
    static real cross(Vector a, Vector b)pure
    {
        return a.x*b.y-b.x*a.y;
    }
}

//ascii文字のみ
long[] suffixArray(Char)(const(Char)[] s) pure
if(isSomeChar!Char)
// in{assert(s.all!"0<=a&&a<127");}
// do
{
    s ~= '\0';
    long[] p = new long[s.length];
    long[] c = new long[s.length];
    {
        long[127] cnt;
        foreach(i;0..s.length)cnt[s[i]]++;
        foreach(i;1..cnt.length)cnt[i] += cnt[i-1];
        foreach(i;0..s.length)p[--cnt[s[i]]] = i;
        long classes=1;
        foreach(i;1..p.length){
            classes += s[p[i]]!=s[p[i-1]]?1:0;
            c[p[i]] = classes-1;
        }
    }
    long[] pn = new long[s.length];
    long[] cn = new long[s.length];
    for(long n=0;(1L<<n) < s.length;n++)
    {
        p.map!(a=>mod(a-(1L<<n), s.length)).copy(pn);
        long[127] cnt;
        foreach(i;0..pn.length)cnt[c[pn[i]]]++;
        foreach(i;1..cnt.length)cnt[i] += cnt[i-1];
        foreach_reverse(i;0..pn.length)p[--cnt[c[pn[i]]]] = pn[i];
        long classes=1;
        for(long i=1;i<c.length;i++)
        {
            if(
                tuple(c[p[i]], c[(p[i]+(1L<<n))%s.length]) !=
                tuple(c[p[i-1]], c[(p[i-1]+(1L<<n))%s.length])
            ) {
                classes++;
            }
            cn[p[i]] = classes - 1;
        }
        cn.copy(c);
    }
    return p[1..$];
}

struct BiparticeMatching{
    int N;
    int[][] path;
    int[] match;
    this(long n)
    {
        N = n.to!int;
        path.length = N;
        match.length = N;
    }
    void addEdge(long u, long v){
        addEdge(u.to!int, v.to!int);
    }
    void addEdge(int u, int v){
        path[u] ~= v;
        path[v] ~= u;
    }
    long calc(){
        auto used = new bool[N];
        bool dfs(int v){
            used[v] = true;
            foreach(u; path[v]){
                int w = match[u];
                if(w==-1||(!used[w]&&dfs(w))){
                    match[v]=u;
                    match[u]=v;
                    return true;
                }
            }
            return false;
        }
        match[] = -1;
        long res = 0;
        foreach(int v; 0..N){
            if(match[v] == -1){
                used[] = false;
                if(dfs(v)){
                    res++;
                }
            }
        }
        return res;
    }
}

// int max_flow(int s, int t){
//     struct edge{
//         int to, cap,  rev;
//     }
//     edge[][MAX_V] G;
//     bool[MAX_V] used;
//     void add_edge(int from, int to, int cap){
//         G[from] ~= edge(to, cap, G[to].length);
//         G[to] ~= edge(from, 0, G[from].length-1);
//     }
//     int dfs(int v, int t, int f)
//     {
//         if(v==t)return f;
//         used[v] = true;
//         foreach(i;0..G[v].length)
//         {
//             edge e = G[v][i];
//             if(!used[e.to] && e.cap > 0){
//                 int d = dfs(e.to, t, min(f, e.cap));
//                 if(d>0){
//                     e.cap -= d;
//                     G[e.to][e.rev].cap +=d ;
//                     return d;
//                 }
//             }
//         }
//         return 0;
//     }
//     int flow = 0;
//     for(;;){
//         int f = dfs(s,t,INF);
//         if(f==0)return flow;
//         flow += f;
//     }
// }

struct CombTable2(long MOD)
{
    static long[] fac;
    static long[] finv;
    static long[] inv;
    this(long n)
    {
        fac = new long[n];
        finv = new long[n];
        inv = new long[n];

        fac[0] = fac[1] = 1;
        finv[0] = finv[1] = 1;
        inv[1] = 1;
        foreach(i;2..n){
            fac[i] = fac[i - 1] * i % MOD;
            inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;
            finv[i] = finv[i - 1] * inv[i] % MOD;
        }
    }

    long comb(long n, long k)
    {
        if (n < k) return 0;
        if (n < 0 || k < 0) return 0;
        return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
    }
}
struct CombTable(long MOD, long n)
{
    static long[n] fac;
    static long[n] finv;
    static long[n] inv;
    static this()
    {
        fac[0] = fac[1] = 1;
        finv[0] = finv[1] = 1;
        inv[1] = 1;
        foreach(i;2..n){
            fac[i] = fac[i - 1] * i % MOD;
            inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;
            finv[i] = finv[i - 1] * inv[i] % MOD;
        }
    }

    static long comb(long n, long k)
    {
        if (n < k) return 0;
        if (n < 0 || k < 0) return 0;
        return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
    }
}

void outLine(List...)(List list)
{
    foreach(i, v;list)
    {
        static if(isFloatingPoint!(typeof(v)))
        {
            writef("%.12f", v);
        }else{
            write(v);
        }
        if(i+1!=list.length)write(' ');
    }
    writeln;
}

void end(List...)(List list)
{
    outLine(list);
    end;
}
void end()
{
    import core.stdc.stdlib;
    exit(0);
}

long sequenceSum(long n) pure
{
    return n*(n+1)/2;
}

//HL分解
struct HeavyLightDecomposition
{
    immutable int root = 1;

    int[][] edge;
    int[] vid;
    int[] invid;
    int[] parent;
    int[] depth;
    int[] subCount;
    int[] head;

    this(long n, long root = 1)
    {
        this(n.to!int, root.to!int);
    }
    this(int n, int root = 1)
    {
        this.root = root;
        n++;
        edge.length = n;
        vid.length = n;
        invid.length = n;
        parent.length = n; parent[] = -1;
        depth.length = n;
        head.length = n; head[root] = root;
        subCount.length = n; subCount[] = 1;
    }

    void addEdge(long u, long v)
    {
        addEdge(u.to!int, v.to!int);
    }
    void addEdge(int u, int v)
    {
        edge[u] ~= v;
        edge[v] ~= u;
    }

    void build()
    {
        void dfs(int v){
            foreach(ref u; edge[v])
            {
                if(u==parent[v]) continue;
                parent[u] = v;
                depth[u] = depth[v] + 1;
                dfs(u);
                subCount[v] += subCount[u];
                if(edge[v][0]==parent[v]||subCount[u]>subCount[edge[v][0]])
                    swap(u, edge[v][0]);
            }
        }
        void dfsHead(int v, ref int pos){
            invid[pos] = v;
            vid[v] = pos;
            pos++;
            foreach(ref u; edge[v])
            {
                if(u==parent[v]) continue;

                head[u] = u == edge[v][0] ? head[v] : u;
                dfsHead(u, pos);
            }
        }
        dfs(root);
        int pos;
        dfsHead(root, pos);
    }

    long lca(long u, long v)
    {
        return lca(u.to!int, v.to!int);
    }
    int lca(int u, int v)
    {
        while(true){
            if(vid[u]>vid[v]) swap(u,v);
            if(head[u]==head[v]) return u;
            v = parent[head[v]];
        }
    }

    long distance(long u, long v) { return distance(u.to!int, v.to!int); }
    long distance(int u, int v) { return depth[u] + depth[v] - 2 * depth[lca(u,v)]; }

    //idxのn個上の親を返す
    //バグあるかも
    long nParent(long n, long idx){
        return nParent(n.to!int, idx.to!int);
    }
    int nParent(int n, int idx){
        auto u = 0;
        auto v = idx;
        while(true)
        {
            if(vid[u]>vid[v]) swap(u,v);

            immutable _u = max(vid[head[v]], vid[u]);
            immutable _v = vid[v] + 1;
            if(_v<=_u+n){
                n -= _v-_u;
            }else{
                return invid[_v-n-1];
            }

            if(head[u]==head[v]) return -1;
            v = parent[head[v]];
        }
    }

    void each(long u, long v, void delegate(long u, long v) pred)
    {
        each(u.to!int, v.to!int, pred);
    }
    void each(int u, int v, void delegate(int u, int v) pred)
    {
        while(true)
        {
            if(vid[u]>vid[v]) swap(u,v);
            pred(max(vid[head[v]], vid[u]), vid[v] + 1);
            if(head[u]==head[v]) return;
            v = parent[head[v]];
        }
    }

    void each(alias pred)(long u, long v)
    if(is(typeof(binaryFun!pred(0L,0L))))
    {
        while(true)
        {
            if(vid[u]>vid[v]) swap(u,v);
            binaryFun!pred(max(vid[head[v]], vid[u]), vid[v] + 1);
            if(head[u]==head[v]) return;
            v = parent[head[v]];
        }
    }
}

// struct HLD{

//     long[][] G;
//     long[] vid, head, sub, par, dep, inv, type;

//     void dfs_sz(long v) {
//         foreach(ref u; G[v])
//             if(u==par[v]) swap(u,G[v].back());
//         if(~par[v]) G[v].popBack;

//         foreach(ref u; G[v]){
//             par[u]=v;
//             dep[u]=dep[v]+1;
//             dfs_sz(u);
//             sub[v]+=sub[u];
//             if(sub[u]>sub[G[v][0]]) swap(u,G[v][0]);
//         }
//     }

//     void dfs_hld(long v,long c,ref long pos) {
//         vid[v]=pos++;
//         inv[vid[v]]=v;
//         type[v]=c;
//         foreach(u; G[v]){
//             if(u==par[v]) continue;
//             head[u]=(u==G[v][0]?head[v]:u);
//             dfs_hld(u,c,pos);
//         }
//     }

//     this(long n){
//         G = new long[][n];
//         vid = new long[n]; vid[] = -1;
//         head = new long[n];
//         sub = new long[n]; sub[] = 1;
//         par = new long[n]; par[] = -1;
//         dep = new long[n];
//         inv = new long[n];
//         type = new long[n];
//     }

//     void add_edge(long u,long v) {
//         G[u] ~= v;
//         G[v] ~= u;
//     }

//     void build(long[] rs = [0]) {
//         long c=0,pos=0;
//         foreach(r; rs){
//             dfs_sz(r);
//             head[r]=r;
//             dfs_hld(r,c++,pos);
//         }
//     }

//     long lca(long u,long v){
//         while(1){
//             if(vid[u]>vid[v]) swap(u,v);
//             if(head[u]==head[v]) return u;
//             v=par[head[v]];
//         }
//     }

//     long distance(long u,long v){
//         return dep[u]+dep[v]-2*dep[lca(u,v)];
//     }

//     // for_each(vertex)
//     // [l, r) <- attention!!
//     void for_each(F)(long u, long v, F f) {
//         while(1){
//             if(vid[u]>vid[v]) swap(u,v);
//             f(max(vid[head[v]],vid[u]),vid[v]+1);
//             if(head[u]!=head[v]) v=par[head[v]];
//             else break;
//         }
//     }

//     T for_each(T, Q, F)(long u,long v,T ti,Q q,F f)
//     {
//         T l=ti,r=ti;
//         while(1){
//             if(vid[u]>vid[v]){
//                 swap(u,v);
//                 swap(l,r);
//             }
//             l=f(l,q(max(vid[head[v]],vid[u]),vid[v]+1));
//             if(head[u]!=head[v]) v=par[head[v]];
//                 else break;
//         }
//         return f(l,r);
//     }

//     // for_each(edge)
//     // [l, r) <- attention!!
//     void for_each_edge(F)(long u, long v,F f) {
//         while(1){
//             if(vid[u]>vid[v]) swap(u,v);
//             if(head[u]!=head[v]){
//                 f(vid[head[v]],vid[v]+1);
//                 v=par[head[v]];
//             }else{
//                 if(u!=v) f(vid[u]+1,vid[v]+1);
//                 break;
//             }
//         }
//     }
// }

struct SegTree(T, T UNIT, alias pred){
    int n;
    long size;
    T* arr;
    alias F = binaryFun!pred;

    this(long size)
    {
        this.size = size;
        n=1;
        while(n<size) n<<=1;
        arr = new T[n<<1].ptr;
        arr[0..n<<1] = UNIT;
    }

    void set(long k,T x)
    {
        assert(k>=0&&k<size);

        arr[k+=n]=x;
        while(k>>=1)
            arr[k]=F(arr[(k<<1)|0],arr[(k<<1)|1]);
    }

    T query(long a, long b)
    {
        assert(a>=0&&a<size);
        assert(b>=1&&b<=size);

        T vl=UNIT,vr=UNIT;
        for(long l=a+n,r=b+n;l<r;l>>=1,r>>=1)
        {
            if(l&1) vl=F(vl,arr[l++]);
            if(r&1) vr=F(arr[--r],vr);
        }
        return F(vl,vr);
    }
}

bool isInf(Num)(Num v) pure @nogc
{
    return v>=INF/2;
}

long mod(long n, long mod) pure @nogc
{
    return (n%mod+mod)%mod;
}

long pow(long a, long n) {
    long res = 1;
    while (n > 0) {
        if (n & 1) res = res * a;
        a = a * a;
        n >>= 1;
    }
    return res;
}
long powmod(long a, long n, long mod) {
    long res = 1;
    while (n > 0) {
        if (n & 1) res = res * a % mod;
        a = a * a % mod;
        n >>= 1;
    }
    return res;
}

alias MInt = ModInt!MOD;

struct ModInt(alias Mod)
if(isIntegral!(typeof(Mod)) && isPrime(Mod))
{
    long value;

    this(ModInt!Mod v)
    {
        value = v.value;
    }
    this(long v)
    {
        value = mod(v, Mod);
    }

    ModInt!Mod opBinaryRight(string op, T)(inout T v) const
    if((op=="+"||op=="-"||op=="*")&&isIntegral!T)
    {
        return typeof(this)(mixin("v"~op~"value"));
    }
    ModInt!Mod opBinary(string op, T)(inout T v) const
    if((op=="+"||op=="-"||op=="*")&&(is(T==ModInt!Mod)||isIntegral!T))
    {
        return typeof(this)(mixin("value"~op~"v"));
    }

    ModInt!Mod opBinaryRight(string op, T)(inout T v) const
    if((op=="/")&&isIntegral!T)
    {
        return v * (this^^(Mod-2));
    }
    ModInt!Mod opBinary(string op, T)(inout T v) const
    if((op=="/")&&(is(T==ModInt!Mod)||isIntegral!T))
    {
        return this * (typeof(this)(v)^^(Mod-2));
    }

    ModInt!Mod opBinaryRight(string op, T)(inout T v) const
    if((op=="^^")&&isIntegral!T)
    {
        return typeof(this)(powmod(v, value, Mod));
    }
    ModInt!Mod opBinary(string op, T)(inout T v) const
    if((op=="^^")&&(is(T==ModInt!Mod)||isIntegral!T))
    {
        return typeof(this)(powmod(value, v, Mod));
    }

    void opAssign(T)(inout T v)
    if(isIntegral!T)
    {
        this = typeof(this)(v);
    }

    void opOpAssign(string op, T)(inout T v)
    {
        this = mixin("this"~op~"v");
    }

    bool opEquals(T)(const T v) const
    if(is(T==ModInt!Mod)||isIntegral!T)
    {
        return value == typeof(this)(v).value;
    }

    long opCast() const {
        return value;
    }

    string toString() const {
        return value.to!string;
    }
}
unittest
{
    assert(is(ModInt!MOD));
    assert(is(ModInt!17));
    assert(!is(ModInt!0));
    assert(!is(ModInt!10));
}

unittest
{
    alias MInt = ModInt!13;
    MInt value;
    value = MInt(14) + MInt(18);
    assert(value==6);
    value = 14 - MInt(28);
    assert(value==12);
    value = MInt(17) * -19;
    assert(value==2);

    value = MInt(7) / 4;
    assert(value==5);
    value = 8 / MInt(4);
    assert(value==2);
    value = 9;
    value /= 4;
    assert(value==12);

    assert(MInt(3) ^^ 9 == 1);
    assert(MInt(54) ^^ MInt(9) == 5);

    value = 29-MInt(16);
    assert(value==0);
    value = MInt(13)*5;
    assert(value==0);
    value = 0;
    assert(value==0);

    value = 3;
    value += MInt(11);
    assert(value==1);
    value -= 7;
    assert(value==7);
    value *= MInt(4);
    assert(value==2);
    value = 23;
    assert(value == cast(long)value);
}
unittest
{
    ModInt!MOD value;
    value = MOD-1;
    assert(value==MOD-1);
    value = MOD;
    assert(value==0);
}

struct Grid(T){
    private T[] grid;
    size_t width, height;
    private size_t stride;

    private this(T[] g, size_t w, size_t h, size_t s)
    {
        grid = g;
        width = w;
        height = h;
        stride = s;
    }

    this(long w, long h, T init = T.init)
    {
        auto arr = new T[(w*h).to!int];
        arr[] = init;
        this(arr, w.to!size_t, h.to!size_t, w.to!size_t);
    }

    // void fill(T elem){
    //     grid[] = elem;
    // }

    bool isInRange(long x, long y) const nothrow
    {
        return
            x>=0 &&
            x<width &&
            y>=0 &&
            y<height;
    }

    int opApply(scope int delegate(ref T) dg)
    {
        int result = 0;

        foreach(y;0..height)
        foreach(x;0..width)
        {
            result = dg(this[x,y]);
            if (result)
                break;
        }
        return result;
    }
    int opApply(scope int delegate(long i, ref T) dg)
    {
        int result = 0;

        long idx;
        foreach(y;0..height)
        foreach(x;0..width)
        {
            result = dg(idx++, this[x,y]);
            if (result)
                break;
        }
        return result;
    }
    int opApply(scope int delegate(long x, long y, ref T) dg)
    {
        int result = 0;

        foreach(y;0..height)
        foreach(x;0..width)
        {
            result = dg(x, y, this[x,y]);
            if (result)
                break;
        }
        return result;
    }

    ref T opIndex(long x, long y)
    {
        assert(isInRange(x,y));
        return (grid.ptr)[(x+stride*y).to!size_t];
    }

    Grid!T opIndex(long[2] r1, long[2] r2)
    {
        auto startOffset = (r1[0] + r2[0]*stride).to!size_t;
        auto endOffset = (r1[1] + (r2[1] - 1)*stride).to!size_t;

        auto resGrid = grid[startOffset .. endOffset];
        auto resStride = stride;
        auto resWidth = (r1[1] - r1[0]).to!size_t;
        auto resHeight = (r2[1] - r2[0]).to!size_t;
        return Grid!T(resGrid, resWidth, resHeight, resStride);
    }

    Grid!T opIndex(long[2] r1, long j) { return opIndex(r1, [j, j+1]); }
    Grid!T opIndex(long i, long[2] r2) { return opIndex([i, i+1], r2); }

    long[2] opSlice(long dim)(long start, long end)
    if (dim == 0 || dim == 1)
    // in { assert(start >= 0 && end <= this.opDollar!dim); }
    body{
        return [start, end];
    }

    Grid!T transpose(){
        auto grid = Grid!T(height, width);

        foreach(w; 0..width)
        foreach(h; 0..height)
        {
            grid[h, w] = this[w, h];
        }
        return grid;
    }

    long opDollar(long dim : 0)() const { return width; }
    long opDollar(long dim : 1)() const { return height; }

    string toString() pure {
        long count;
        foreach(y; 0..height)
        {
            foreach(x; 0..width)
            {
                long eCount = this[x, y].to!string.length;
                static if(is(typeof(this[x,y].isInf)))
                {
                    if(this[x,y].isInf)
                    {
                        eCount = 1;
                    }
                }
                static if(is(typeof(this[x,y])==bool))
                {
                    eCount = 1;
                }
                count = max(count, eCount);
            }
        }
        count++;

        string res = "\n";
        foreach(y; 0..height)
        {
            foreach(x; 0..width)
            {
                string joinStr = this[x, y].to!string;
                static if(is(typeof(this[x,y].isInf)))
                {
                    if(this[x,y].isInf)
                    {
                        joinStr = "*";
                    }
                }
                static if(is(typeof(this[x,y])==bool))
                {
                    joinStr = this[x,y]?"+":"-";
                }
                foreach(i;0..count-joinStr.length)
                {
                    res ~= ' ';
                }
                res ~= joinStr;
            }
            res ~= '\n';
        }
        return res;
    }
}

struct UnionFind{
    private int[] arr;
    int rootCount;

    @disable this();
    this(long n){
        arr.length = n.to!int;
        arr[] = -1;
        rootCount = n.to!int;
    }

    void merge(long a, long b)
    {
        merge(a.to!int, b.to!int);
    }
    void merge(int a, int b)
    {
        if(same(a,b)) return;
        arr[root(a)] = root(b);
        rootCount--;
    }

    bool same(long a, long b)
    {
        return same(a.to!int, b.to!int);
    }
    bool same(int a, int b)
    {
        return root(a)==root(b);
    }

    private int root(int i)
    {
        if(arr[i] == -1) return i;
        return arr[i] = root(arr[i]);
    }
}

unittest{
    assert(is(typeof(UnionFind(10))));
    assert(!is(typeof(UnionFind())));

    auto uf = UnionFind(10);
    uf.merge(2,3);
    assert(uf.same(2,3));
    uf.merge(3,4);
    uf.merge(1,5);
    uf.merge(5,6);
    uf.merge(6,7);
    assert(!uf.same(4,7));
    uf.merge(1,2);
    assert(uf.same(4,7));
}

void debugPrint(List...)()
{
    void _debugPrintElem(alias elem, float rad)()
    {
        import std.experimental.color;
        import std.experimental.color.lab;
        import std.experimental.color.rgb;
        import std.experimental.color.xyz;

        enum color = LCh!float(80f, 100f, rad);
        enum rgb = color.convertColor!(Lab!float).convertColor!(XYZ!float).convertColor!(RGB8).tristimulus;
        enum r = rgb[0].value;
        enum g = rgb[1].value;
        enum b = rgb[2].value;

        stderr.writef!"\033[38;2;%s;%s;%sm"(r, g, b);
        static if(isSomeFunction!elem)
        {
            stderr.write("elem: ", elem(), " ");
        }else{
            enum name =  __traits(identifier, elem);
            stderr.write(name, ": ");
            stderr.write(elem, " ");
        }
    }
    void _debugPrint(int i, float rad, List...)()
    {
        _debugPrintElem!(List[0], i * rad)();
        static if(List.length>1)
        {
            _debugPrint!(i+1, rad, List[1..$])();
        }
    }

    debug(Local)
    {
        _debugPrint!(0, 360f/List.length, List)();
        stderr.writeln("\033[0m");
    }
}

struct Stack(Elem){
    private Elem[] array;
    private size_t endIdx;

    void insertBack(Elem e)
    {
        if(endIdx==array.length){
            array.length = array.length*2+10;
        }
        (array.ptr)[endIdx++] = e;
    }

    void insertBack(Range)(Range range)
    if(is(typeof(array[0] = range.popFront)))
    {
        if(endIdx+range.length>array.length){
            array.length = (endIdx+range.length)*2+10;
        }
        foreach(ref e;range)
        {
            (array.ptr)[endIdx++] = e;
        }
    }

    Elem[] opSlice(){
        return array[0..endIdx];
    }

    void popBack()
    {
        assert(endIdx!=0);
        endIdx--;
    }

    ref Elem back()
    {
        assert(endIdx!=0);
        return (array.ptr)[endIdx-1];
    }

    size_t count() const
    {
        return endIdx;
    }

    bool empty() const
    {
        return endIdx==0;
    }

    void clear()
    {
        endIdx = 0;
    }
}

Grid!T scanGrid(T=long)(long w, long h, dchar t='.')
{
    auto grid = Grid!T(w,h);
    foreach(y;0..h)
    {
        foreach(x;0..w)
        {
            grid[x, y] = scanElem!T;
        }
    }

    return grid;
}

Grid!bool scanGridBool(long w, long h, dchar t='.')
{
    auto grid = Grid!bool(w,h);
    foreach(y;0..h.to!size_t)
    {
        auto line = scanString;
        foreach(x;0..w.to!size_t)
        {
            grid[x, y] = line[x.to!size_t]==t;
        }
    }

    return grid;
}

T[] scanLineArray(T = long)()
{
    static char[] scanBuf;
    readln(scanBuf);
    return scanBuf.split.to!(T[]);
}

char scanChar()
{
    int c = ' ';
    while (isWhite(c) && c != -1)
    {
        c = getchar;
    }
    return cast(char)c;
}

T[] scanElem(T=long)(long size)
{
    T[] list = new T[size.to!size_t];
    foreach(i;0..size.to!size_t)
    {
        list[i] = scanElem!T;
    }
    return list;
}

T scanElem(T)()
if(is(T==struct))
{
    T res;
    foreach(ref field; res.tupleof){
        field = scanElem!(typeof(field));
    }
    return res;
}

Tuple!List[] scanElem(List...)(long size)
{
    auto list = new Tuple!List[size.to!size_t];
    foreach(i;0..size.to!size_t)
    {
        list[i] = scanElem!List;
    }
    return list;
}
Tuple!List scanElem(List...)()
{
    List res;
    foreach(i, e; List){
        res[i] = scanElem!e;
    }
    return tuple(res);
}

T scanElem(T = long)()
if(isBasicType!T||isSomeString!T)
{
    import core.stdc.stdlib;
    static auto scanBuf = appender!(char[])([]);

    scanBuf.clear;

    int c = ' ';
    while (isWhite(c) && c != -1)
    {
        c = getchar;
    }
    while (!isWhite(c) && c != -1)
    {
        scanBuf ~= cast(char) c;
        c = getchar;
    }
    return scanBuf.data.to!T;
}

string scanString(){
    return scanElem!string;
}

CommonType!(A,B) gcd(A,B)(A a, B b) pure
if(isIntegral(A)&&isIntegral(B))
{
    if(b==0)return a;
    return gcd(b, a % b);
}

CommonType!(A,B) lcm(A,B)(A a, B b) pure
if(isIntegral(A)&&isIntegral(B))
{
    return a / gcd(a, b) * b;
}

struct Factor
{
    long n;
    long c;
}

//素因数分解
Factor[] factors(long n) pure
{
    Factor[] res;
    for (long i = 2; i ^^ 2 <= n; i++)
    {
        if (n % i != 0)
            continue;

        long c;
        while (n % i == 0)
        {
            n = n / i;
            c++;
        }
        res ~= Factor(i, c);
    }
    if (n != 1)
        res ~= Factor(n, 1);

    return res;
}
//約数をすべて列挙
long[] divisors(long n) pure
{
    long[] list;
    void func(Factor[] fs, long n)
    {
        if(fs.empty){
            list ~= n;
            return;
        }

        foreach(c; 0..fs[0].c+1)
        {
            func(fs[1..$], n * (fs[0].n ^^ c));
        }
    }

    func(factors(n), 1);
    sort(list);
    return list;
}
//nまでの素数のリスト
long[] primes(long n) pure
{
    if(n<2)return [];

    auto table = new long[cast(size_t)n+1];

    long[] res;
    for(size_t i = 2;i<=n;i++)
    {
        if(table[i]==-1) continue;
        for(size_t a = i;a<table.length;a+=i)
        {
            table[a] = -1;
        }
        res ~= i;
    }
    return res;
}
//素数判定
bool isPrime(long n) pure
{
    if (n <= 1)
        return false;
    if (n == 2)
        return true;
    if (n % 2 == 0)
        return false;
    for (long i = 3; i ^^ 2 <= n; i += 2)
        if (n % i == 0)
            return false;
    return true;
}

//桁を数える
long digitCount(long n, long base=10) pure
{
    long res;
    do{
        n/=base;
        res++;
    }while(n!=0);

    return res;
}

module _template;
import std.stdio;
import std.string;
import std.algorithm;
import std.container;
import std.range;
import std.math;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

struct IO {
        string read_string() {
                while (tokens.empty) {
                tokens = readln.split;
        }
        auto token = tokens.front;
                tokens.popFront;
                return token;
        }

        int read_int() {
                return read_string.to!int;
        }

        double read_double() {
                return read_string.to!double;
        }

        string[] tokens;
}

void main() {
        IO cin;
        int t = 1;
        t = cin.read_int;
        while (t--) {
                int hh, mm;
                hh = cin.read_int;
                mm = cin.read_int;
                writeln((24 - hh - 1) * 60 + (60 - mm));
        }
}

// unihernandez22
// https://codeforces.com/contest/1283/problem/A
// implementation

import std.stdio;
void main() {
	int t;
	"%d\n".readf(&t);
	foreach(_; 0..t) {
		int h, m;
		"%d %d\n".readf(&h, &m);
		writeln((24-h)*60 - m);
	}
}

import std.stdio;
int main()
{
	int t=0;
	readf(" %d", &t);
	for (int i=0; i<t; i++)
	{
		int a=0;
		int b=0;
		readf(" %d", &a);
		readf(" %d", &b);
		writeln(1440-(a*60+b));
	}
	return 0;
}


Mike and Joe are playing a game with some stones. Specifically, they have $$$n$$$ piles of stones of sizes $$$a_1, a_2, \ldots, a_n$$$. These piles are arranged in a circle.The game goes as follows. Players take turns removing some positive number of stones from a pile in clockwise order starting from pile $$$1$$$. Formally, if a player removed stones from pile $$$i$$$ on a turn, the other player removes stones from pile $$$((i\bmod n) + 1)$$$ on the next turn.If a player cannot remove any stones on their turn (because the pile is empty), they lose. Mike goes first.If Mike and Joe play optimally, who will win?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 50$$$)  — the number of piles. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)  — the size of the piles.

For each test case print the winner of the game, either "Mike" or "Joe" on its own line (without quotes).

NoteIn the first test case, Mike just takes all $$$37$$$ stones on his first turn.In the second test case, Joe can just copy Mike's moves every time. Since Mike went first, he will hit $$$0$$$ on the first pile one move before Joe does so on the second pile.

// cheese-cracker [2022-07-01]

void solve(){
    int n = scan!int;
    auto arr = scanArray;
    if(n % 2){
        writeln("Mike");
    }else{
        long minn = 1000_000_000;
        long minpos = 0;
        for(int i = 0; i < n; ++i){
            if(arr[i] < minn){
                minn = arr[i];
                minpos = i;
            }
        }
        if(minpos % 2){
            writeln("Mike");
        }else{
            writeln("Joe");
        }
    }
}

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

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm;
import std.container, std.math, std.numeric, std.functional;
string[] tk; alias tup = Tuple!(long, long);
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; } }

// cheese-cracker [2022-07-01]

void solve(){
    int n = scan!int;
    auto arr = scanArray;
    if(n % 2){
        writeln("Mike");
    }else{
        long tot = arr.sum;
        long evsum = 0;
        for(int i = 0; i < n; i += 2){
            evsum += arr[i];
        }
        long osum = tot - evsum;
        if(evsum > osum){
            writeln("Mike");
        }else{
            writeln("Joe");
        }
    }
}

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

/*_________________________*That's All Folks!*__________________________*/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm;
import std.container, std.math, std.numeric, std.functional;
string[] tk; alias tup = Tuple!(long, long);
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; } }


Vasya plays the LionAge II. He was bored of playing with a stupid computer, so he installed this popular MMORPG, to fight with his friends. Vasya came up with the name of his character — non-empty string s, consisting of a lowercase Latin letters. However, in order not to put up a front of friends, Vasya has decided to change no more than k letters of the character name so that the new name sounded as good as possible. Euphony of the line is defined as follows: for each pair of adjacent letters x and y (x immediately precedes y) the bonus c(x, y) is added to the result. Your task is to determine what the greatest Euphony can be obtained by changing at most k letters in the name of the Vasya's character.

The first line contains character's name s and an integer number k (0 ≤ k ≤ 100). The length of the nonempty string s does not exceed 100. The second line contains an integer number n (0 ≤ n ≤ 676) — amount of pairs of letters, giving bonus to the euphony. The next n lines contain description of these pairs «x y c», which means that sequence xy gives bonus c (x, y — lowercase Latin letters,  - 1000 ≤ c ≤ 1000). It is guaranteed that no pair x y mentioned twice in the input data.

Output the only number — maximum possible euphony оf the new character's name.

abcdef 1
5
a b -10
b c 5
c d 5
d e 5
e f 5

NoteIn the first example the most euphony name will be looser. It is easy to calculate that its euphony is 36.

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

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

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

    int[Tuple!(dchar, dchar)] mp;
    foreach (i; 0 .. n) {
        dchar c1, c2;
        int v;
        readf("%s %s %s", &c1, &c2, &v);
        readln;

        mp[tuple(c1, c2)] = v;
    }

    immutable int INF = 10 ^^ 9;
    auto dp = new int[][][] (s.length, k+1, 300);
    foreach (ref rw1; dp) {
        foreach (ref rw2; rw1) {
            rw2[] = -INF;
        }
    }

    if (k > 0) {
        foreach (ltr; 'a' .. 'z' + 1) { dp[0][1][ltr] = 0; }
    }
    dp[0][0][s[0]] = 0;

    foreach (i; 1 .. s.length) {
        foreach (kk; 0 .. min(i+1, k) + 1) {
            foreach (prvlt; 'a' .. 'z' + 1) {
                foreach (nxtlt; 'a' .. 'z' + 1) {
                    int v = mp.get(tuple(prvlt.to!dchar, nxtlt.to!dchar), 0);
                    if (nxtlt == s[i]) {
                        dp[i][kk][nxtlt] = max(dp[i][kk][nxtlt], dp[i-1][kk][prvlt] + v);
                    } else if (kk > 0) {
                        dp[i][kk][nxtlt] = max(dp[i][kk][nxtlt], dp[i-1][kk-1][prvlt] + v);
                    }
                }
            }
        }
    }

    int ans = -INF;
    foreach (arr; dp[s.length-1]) {
        ans = max(ans, arr.maxElement);
    }

    ans.writeln;
}


Innovation technologies are on a victorious march around the planet. They integrate into all spheres of human activity!A restaurant called "Dijkstra's Place" has started thinking about optimizing the booking system. There are n booking requests received by now. Each request is characterized by two numbers: ci and pi — the size of the group of visitors who will come via this request and the total sum of money they will spend in the restaurant, correspondingly.We know that for each request, all ci people want to sit at the same table and are going to spend the whole evening in the restaurant, from the opening moment at 18:00 to the closing moment.Unfortunately, there only are k tables in the restaurant. For each table, we know ri — the maximum number of people who can sit at it. A table can have only people from the same group sitting at it. If you cannot find a large enough table for the whole group, then all visitors leave and naturally, pay nothing.Your task is: given the tables and the requests, decide which requests to accept and which requests to decline so that the money paid by the happy and full visitors was maximum.

The first line of the input contains integer n (1 ≤ n ≤ 1000) — the number of requests from visitors. Then n lines follow. Each line contains two integers: ci, pi (1 ≤ ci, pi ≤ 1000) — the size of the group of visitors who will come by the i-th request and the total sum of money they will pay when they visit the restaurant, correspondingly. The next line contains integer k (1 ≤ k ≤ 1000) — the number of tables in the restaurant. The last line contains k space-separated integers: r1, r2, ..., rk (1 ≤ ri ≤ 1000) — the maximum number of people that can sit at each table.

In the first line print two integers: m, s — the number of accepted requests and the total money you get from these requests, correspondingly. Then print m lines — each line must contain two space-separated integers: the number of the accepted request and the number of the table to seat people who come via this request. The requests and the tables are consecutively numbered starting from 1 in the order in which they are given in the input. If there are multiple optimal answers, print any of them.

import std.stdio;
import std.algorithm.sorting;

struct Group {
    int index;
    int size;
    int value;
}

struct Table {
    int index;
    int size;
    bool taken;
}

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

    int n;
    readf(" %s\n", &n);
    Group[] groups = new Group[n];
    foreach (i; 0 .. n) {
        readf(" %s %s\n", &groups[i].size, &groups[i].value);
        groups[i].index = i + 1;
    }
    int k;
    readf(" %s\n", &k);
    Table[] tables = new Table[k];
    foreach (i; 0 .. k) {
        readf(" %s", &tables[i].size);
        tables[i].index = i + 1;
    }

    int m = 0, s = 0;
    int[] reqnum;
    int[] tabnum;

    groups.sort!"a.value > b.value";
    auto st = tables.sort!"a.size < b.size";

    Table dummytab = Table(0, 0, false);
    foreach (g; groups) {
        dummytab.size = g.size;
        auto idx = st.lowerBound(dummytab).length;
        foreach (i; idx .. tables.length) {
            if (tables[i].taken == false) {
                tables[i].taken = true;
                m += 1;
                s += g.value;
                reqnum ~= g.index;
                tabnum ~= tables[i].index;
                break;
            }
        }
    }
    writeln(m, " ", s);
    foreach (i; 0 .. reqnum.length) {
        writeln(reqnum[i], " ", tabnum[i]);
    }

    return 0;
}

import std.stdio;
import std.algorithm.sorting;
import std.container.rbtree;

struct Group {
    int index;
    int size;
    int value;
}

struct Table {
    int index;
    int size;
    bool taken;
}

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

    int n;
    readf(" %s\n", &n);
    Group[] groups = new Group[n];
    foreach (i; 0 .. n) {
        readf(" %s %s\n", &groups[i].size, &groups[i].value);
        groups[i].index = i + 1;
    }
    int k;
    readf(" %s\n", &k);
    auto tableTree = new RedBlackTree!(Table, "a.size < b.size", true);
    //Table[] tables = new Table[k];
    foreach (i; 0 .. k) {
        Table t;
        readf(" %s", &t.size);
        t.index = i + 1;
        tableTree.insert(t);
    }

    int m = 0, s = 0;
    int[] reqnum;
    int[] tabnum;

    groups.sort!"a.value > b.value";

    Table t = Table(0, 0, false);
    foreach (g; groups) {
        t.size = g.size;
        t.taken = false;
        auto er = tableTree.equalRange(t);
        if (!er.empty) {
            t = er.front;
            t.taken = true;
        }
        else {
            auto ur = tableTree.upperBound(t);
            if(!ur.empty) {
                t = ur.front;
                t.taken = true;
            }
        }
        if (t.taken) {
            tableTree.removeKey(t);
            m += 1;
            s += g.value;
            reqnum ~= g.index;
            tabnum ~= t.index;
        }
    }

    writeln(m, " ", s);
    foreach (i; 0 .. reqnum.length) {
        writeln(reqnum[i], " ", tabnum[i]);
    }

    return 0;
}


A way to make a new task is to make it nondeterministic or probabilistic. For example, the hard task of Topcoder SRM 595, Constellation, is the probabilistic version of a convex hull.Let's try to make a new task. Firstly we will use the following task. There are n people, sort them by their name. It is just an ordinary sorting problem, but we can make it more interesting by adding nondeterministic element. There are n people, each person will use either his/her first name or last name as a handle. Can the lexicographical order of the handles be exactly equal to the given permutation p?More formally, if we denote the handle of the i-th person as hi, then the following condition must hold: .

The first line contains an integer n (1 ≤ n ≤ 105) — the number of people. The next n lines each contains two strings. The i-th line contains strings fi and si (1 ≤ |fi|, |si| ≤ 50) — the first name and last name of the i-th person. Each string consists only of lowercase English letters. All of the given 2n strings will be distinct. The next line contains n distinct integers: p1, p2, ..., pn (1 ≤ pi ≤ n).

If it is possible, output "YES", otherwise output "NO".

3
gennady korotkevich
petr mitrichev
gaoyuan chen
1 2 3

3
gennady korotkevich
petr mitrichev
gaoyuan chen
3 1 2

2
galileo galilei
nicolaus copernicus
2 1

10
rean schwarzer
fei claussell
alisa reinford
eliot craig
laura arseid
jusis albarea
machias regnitz
sara valestin
emma millstein
gaius worzel
1 2 3 4 5 6 7 8 9 10

10
rean schwarzer
fei claussell
alisa reinford
eliot craig
laura arseid
jusis albarea
machias regnitz
sara valestin
emma millstein
gaius worzel
2 4 9 6 5 7 1 3 8 10

NoteIn example 1 and 2, we have 3 people: tourist, Petr and me (cgy4ever). You can see that whatever handle is chosen, I must be the first, then tourist and Petr must be the last.In example 3, if Copernicus uses "copernicus" as his handle, everything will be alright.

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

void main ()
{
	int n;
	while (readf (" %s ", &n) > 0)
	{
		string [2] [] a;
		foreach (i; 0..n)
		{
			auto s = readln ().split ();
			string u = s.front.dup;
			s.popFront ();
			string v = s.front.dup;
			a ~= [u, v];
		}
		debug {writeln (a);}

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

		auto f = new bool [2] [n];
		f[0][0] = f[0][1] = true;
		foreach (i; 1..n)
		{
			f[i][0] = (f[i - 1][0] && a[p[i - 1]][0] < a[p[i]][0]) ||
			          (f[i - 1][1] && a[p[i - 1]][1] < a[p[i]][0]);
			f[i][1] = (f[i - 1][0] && a[p[i - 1]][0] < a[p[i]][1]) ||
			          (f[i - 1][1] && a[p[i - 1]][1] < a[p[i]][1]);
		}
		writeln ((f[n - 1][0] || f[n - 1][1]) ? "YES" : "NO");
	}
}

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

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

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

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

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

int N;
string[][] A;
int[] P;

void main(string[] args) {
	try {
	for (; ; ) {
		N = readInt;
		A = new string[][](N, 2);
		foreach (i; 0 .. N) foreach (j; 0 .. 2) {
			A[i][j] = readToken;
		}
		P = new int[N];
		foreach (i; 0 .. N) {
			P[i] = readInt - 1;
		}

		bool[][] dp = new bool[][](N + 1, 2);
		dp[1][] = true;
		foreach (i; 1 .. N) {
			foreach (j; 0 .. 2) if (dp[i][j]) {
				foreach (k; 0 .. 2) {
					if (A[P[i - 1]][j] <= A[P[i]][k]) {
						dp[i + 1][k] = true;
					}
				}
			}
		}
		writeln((dp[N][0] || dp[N][1]) ? "YES" : "NO");
	}
	} catch (EOFException) {}
}