Vasya has got three integers $$$n$$$, $$$m$$$ and $$$k$$$. He'd like to find three integer points $$$(x_1, y_1)$$$, $$$(x_2, y_2)$$$, $$$(x_3, y_3)$$$, such that $$$0 \le x_1, x_2, x_3 \le n$$$, $$$0 \le y_1, y_2, y_3 \le m$$$ and the area of the triangle formed by these points is equal to $$$\frac{nm}{k}$$$.Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.

If there are no such points, print "NO". Otherwise print "YES" in the first line. The next three lines should contain integers $$$x_i, y_i$$$ — coordinates of the points, one point per line. If there are multiple solutions, print any of them. You can print each letter in any case (upper or lower).

NoteIn the first example area of the triangle should be equal to $$$\frac{nm}{k} = 4$$$. The triangle mentioned in the output is pictured below:   In the second example there is no triangle with area $$$\frac{nm}{k} = \frac{16}{7}$$$.

import core.stdc.stdio;
import std.algorithm;
int n,m,k;
int gcd(int p,int q)
{
	if (q==0)
	{
		return p;
	}
	return gcd(q,p%q);
}
void main()
{
    int i,x,y;
	scanf("%d%d%d",&n,&m,&k);
	if (cast(long)2*n*m%k!=0)
	{
		printf("NO\n");
		return;
	}
	printf("YES\n");
	if (k%2==0)
	{
		k/=2;
		x=gcd(n,k);
		y=k/x;
		printf("0 0\n");
		printf("%d 0\n",n/x);
		printf("0 %d\n",m/y);
		return;
	}
	x=gcd(n,k);
	y=k/x;
	printf("0 0\n");
	printf("%d 0\n",n/x*(x>1?2:1));
	printf("0 %d\n",m/y*(x>1?1:2));
}

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

immutable int MD = 998244353;

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

    if (n.to!long * m * 2 % k != 0) {
        writeln("NO");
        return;
    }

    auto r = 2*n;
    auto c = m;

    auto q = gcd(r, k);
    r /= q;
    k /= q;

    c /= k;

    if (r > n) r /= 2, c *= 2;
    if (c > m) {
        writeln("NOdf");
        return;
    }

    auto p1 = tuple(0, 0);
    auto p2 = tuple(r, 0);
    auto p3 = tuple(0, c);

    writeln("YES");
    [p1, p2, p3].each!(t => writeln(t[0], ' ', t[1]));
}

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

immutable int MD = 998244353;

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

    if (n.to!long * m * 2 % k != 0) {
        writeln("NO");
        return;
    }

    auto r = 2*n;
    auto c = m;

    auto q = gcd(r, k);
    r /= q;
    k /= q;

    c /= k;

    if (r > n) r /= 2, c *= 2;

    auto p1 = tuple(0, 0);
    auto p2 = tuple(r, 0);
    auto p3 = tuple(0, c);

    writeln("YES");
    [p1, p2, p3].each!(t => writeln(t[0], ' ', t[1]));
}

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

  long n, m, k;
  rd(n, m, k);
  if (n * m * 2 % k != 0) {
    writeln("NO");
    return;
  }

  writeln("YES");
  bool odd = true;
  if (k % 2 == 0) {
    k /= 2;
    odd = false;
  }
  import std.numeric : gcd;

  auto g = gcd(n, k), a = n / g;
  k /= g;
  auto b = m / k;
  if (odd) {
    if (a == n) {
      b *= 2;
    } else {
      a *= 2;
    }
  }
  writeln(0, " ", 0);
  writeln(a, " ", 0);
  writeln(0, " ", b);

}

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 core.bitop;
import std.algorithm;
import std.array;
import std.bitmanip;
import std.container;
import std.conv;
import std.functional;
import std.math;
import std.numeric;
import std.range;
import std.stdio;
import std.string;
import std.typecons;
import std.range.interfaces;

immutable int MD = 998244353;

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

    if (n.to!long * m % (2*k) != 0) {
        writeln("NO");
        return;
    }

    auto q = gcd(n, k);
    auto r = n / q;
    k /= q;

    auto c = m / k;
    // k /= k;

    if (r * 2 <= n) r *= 2;
    else if (c * 2 <= m) c *= 2;
    else {
        writeln("NO");
        return;
    }

    auto p1 = tuple(0, 0);
    auto p2 = tuple(r, 0);
    auto p3 = tuple(0, c);

    writeln("YES");
    [p1, p2, p3].each!(t => writeln(t[0], ' ', t[1]));
}

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

immutable int MD = 998244353;

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

    if (n.to!long * m % k != 0) {
        writeln("NO");
        return;
    }

    auto r = 2*n;
    auto c = m;

    auto q = gcd(r, k);
    r /= q;
    k /= q;

    c /= k;

    if (r > n) r /= 2, c *= 2;
    if (c > m) {
        writeln("NO");
        return;
    }

    auto p1 = tuple(0, 0);
    auto p2 = tuple(r, 0);
    auto p3 = tuple(0, c);

    writeln("YES");
    [p1, p2, p3].each!(t => writeln(t[0], ' ', t[1]));
}

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

  long n, m, k;
  rd(n, m, k);
  if (n * m * 2 % k != 0) {
    writeln("NO");
    return;
  }

  writeln("YES");
  if (k % 2 == 0)
    k /= 2;
  import std.numeric : gcd;

  auto g = gcd(n, k), a = n / g;
  k /= g;
  auto b = m / k;
  if (a * b / 2 != n * m * k) {
    if (a == n) {
      b *= 2;
    } else {
      a *= 2;
    }
  }
  writeln(0, " ", 0);
  writeln(a, " ", 0);
  writeln(0, " ", b);

}

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

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

  long n, m, k;
  rd(n, m, k);
  if (n * m * 2 % k != 0) {
    writeln("NO");
    return;
  }

  writeln("YES");
  if (k % 2 == 0)
    k /= 2;
  import std.numeric : gcd;

  auto g = gcd(n, k), a = n / g;
  k /= g;
  auto b = m / k;
  if (a == n) {
    b *= 2;
  } else {
    a *= 2;
  }
  writeln(0, " ", 0);
  writeln(a, " ", 0);
  writeln(0, " ", b);

}

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

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

  import std.bigint;

  BigInt n, m, k;
  rd(n, m, k);

  BigInt ansx, ansy;
  bool enough(BigInt x) { // x>0
    // x*y*0.5 = nm/k -> xy*k = 2nm
    auto y = m * n * 2 / k / x;
    if (y <= 0)
      return true;
    ansx = x;
    ansy = y;
    return x * y * k >= m * n * 2;
  }

  BigInt ng = 0, ok = n + 1;
  while (ok - ng > 1) {
    auto mid = (ng + ok) / 2;
    if (enough(mid))
      ok = mid;
    else
      ng = mid;
  }
  if (0 <= ok && ok <= n) {
    if (ansx * ansy * k == 2 * n * m) {
      writeln("YES");
      writeln(0, " ", 0);
      writeln(ansx, " ", 0);
      writeln(0, " ", ansy);
    } else {
      writeln("NO");
    }
  } else {
    writeln("NO");
  }
}

void rd(T...)(ref T x) {
  import std.stdio, std.string, std.conv;

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


You are given a string $$$a$$$, consisting of $$$n$$$ characters, $$$n$$$ is even. For each $$$i$$$ from $$$1$$$ to $$$n$$$ $$$a_i$$$ is one of 'A', 'B' or 'C'.A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.You want to find a string $$$b$$$ that consists of $$$n$$$ characters such that:   $$$b$$$ is a regular bracket sequence;  if for some $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) $$$a_i=a_j$$$, then $$$b_i=b_j$$$. In other words, you want to replace all occurrences of 'A' with the same type of bracket, then all occurrences of 'B' with the same type of bracket and all occurrences of 'C' with the same type of bracket.Your task is to determine if such a string $$$b$$$ exists.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The only line of each testcase contains a string $$$a$$$. $$$a$$$ consists only of uppercase letters 'A', 'B' and 'C'. Let $$$n$$$ be the length of $$$a$$$. It is guaranteed that $$$n$$$ is even and $$$2 \le n \le 50$$$.

For each testcase print "YES" if there exists such a string $$$b$$$ that:    $$$b$$$ is a regular bracket sequence;  if for some $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) $$$a_i=a_j$$$, then $$$b_i=b_j$$$.  Otherwise, print "NO". You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first testcase one of the possible strings $$$b$$$ is "(())()".In the second testcase one of the possible strings $$$b$$$ is "()()".

// Vicfred
// https://codeforces.com/contest/1494/problem/A
// brute force
import std.array;
import std.stdio;

bool check(string s) {
    int c = 0;
    foreach(p; s) {
        if(p == '(')
            c += 1;
        else
            c -= 1;
        if(c < 0)
            return false;
    }
    return c == 0;
}

string generate(string t) {
    string p = "()";
    for(int i = 0; i < 2; i++) {
        for(int j = 0; j < 2; j++) {
            for(int k = 0; k < 2; k++) {
                string s = t
                    .replace('A', p[i])
                    .replace('B', p[j])
                    .replace('C', p[k]);

                if(check(s)) {
                    return "YES";
                }
            }
        }
    }
    return "NO";
}

void main() {
    long t;
    readf("%s\n", &t);

while(t--) {
    string a;
    readf("%s\n", &a);
    generate(a).writeln;
}
}

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

string FMT_F = "%.10f";

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

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

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

//long mod = 10^^9 + 7;
long mod = 998_244_353;
//long mod = 1_000_003;
void moda(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 bool[](t);
	foreach (ti; 0..t)
	{
		auto a = RD!string;

		foreach (i; 0..2^^3)
		{
			auto arr = new int[](3);
			arr[0] = i & 0b100;
			arr[1] = i & 0b010;
			arr[2] = i & 0b001;
			long cnt;
			bool ok = true;
			foreach (c; a)
			{
				auto num = c - 'A';
				if (arr[num])
					++cnt;
				else
					--cnt;
				if (cnt < 0)
				{
					ok = false;
					break;
				}
			}
			if (!ok) continue;
			if (cnt == 0)
			{
				ans[ti] = true;
				break;
			}
		}
	}

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

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

bool isGood (R) (R s)
{
	int balance = 0;
	foreach (c; s)
	{
		balance += c ? +1 : -1;
		if (balance < 0)
		{
			return false;
		}
	}
	return balance == 0;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto s = readln.strip;
		bool ok = false;
		foreach (i; 0..8)
		{
			int [char] t;
			t['A'] = (i >> 0) & 1;
			t['B'] = (i >> 1) & 1;
			t['C'] = (i >> 2) & 1;
			ok |= isGood (s.byChar.map !(c => t[c]));
		}
		writeln (ok ? "YES" : "NO");
	}
}


Vasya has been playing Plane of Tanks with his friends the whole year. Now it is time to divide the participants into several categories depending on their results. A player is given a non-negative integer number of points in each round of the Plane of Tanks. Vasya wrote results for each round of the last year. He has n records in total.In order to determine a player's category consider the best result obtained by the player and the best results of other players. The player belongs to category:   "noob" — if more than 50% of players have better results;  "random" — if his result is not worse than the result that 50% of players have, but more than 20% of players have better results;  "average" — if his result is not worse than the result that 80% of players have, but more than 10% of players have better results;  "hardcore" — if his result is not worse than the result that 90% of players have, but more than 1% of players have better results;  "pro" — if his result is not worse than the result that 99% of players have.  When the percentage is calculated the player himself is taken into account. That means that if two players played the game and the first one gained 100 points and the second one 1000 points, then the first player's result is not worse than the result that 50% of players have, and the second one is not worse than the result that 100% of players have.Vasya gave you the last year Plane of Tanks results. Help Vasya determine each player's category.

The first line contains the only integer number n (1 ≤ n ≤ 1000) — a number of records with the players' results. Each of the next n lines contains a player's name and the amount of points, obtained by the player for the round, separated with a space. The name contains not less than 1 and no more than 10 characters. The name consists of lowercase Latin letters only. It is guaranteed that any two different players have different names. The amount of points, obtained by the player for the round, is a non-negative integer number and does not exceed 1000.

Print on the first line the number m — the number of players, who participated in one round at least. Each one of the next m lines should contain a player name and a category he belongs to, separated with space. Category can be one of the following: "noob", "random", "average", "hardcore" or "pro" (without quotes). The name of each player should be printed only once. Player names with respective categories can be printed in an arbitrary order.

5
vasya 100
vasya 200
artem 100
kolya 200
igor 250

4
artem noob
igor pro
kolya random
vasya random

NoteIn the first example the best result, obtained by artem is not worse than the result that 25% of players have (his own result), so he belongs to category "noob". vasya and kolya have best results not worse than the results that 75% players have (both of them and artem), so they belong to category "random". igor has best result not worse than the result that 100% of players have (all other players and himself), so he belongs to category "pro".In the second example both players have the same amount of points, so they have results not worse than 100% players have, so they belong to category "pro".

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

void main()
{
	auto n = readln().chomp().to!int();
	int[string] plys;

	foreach (i; 0 .. n) {
		auto data = readln().split();
		plys[data[0]] = max(plys.get(data[0], 0), data[1].to!int());
	}

	plys.length.writeln();

	foreach (key; plys.keys.sort) {
		int cnt = 0;
		auto score = plys[key];
		foreach (skey; plys.keys) {
			if (key == skey) continue;
			if (plys[key] < plys[skey]) cnt++;
		}
		string ss;
		cnt *= 100;

		if (cnt > plys.length * 50) ss = "noob";
		else if (cnt > plys.length * 20) ss = "random";
		else if (cnt >  plys.length * 10) ss = "average";
		else if (cnt > plys.length) ss = "hardcore";
		else ss = "pro";
		writeln(key, " ", ss);
	}
}

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

void main()
{
	auto n = readln().chomp().to!int();
	int[string] plys;

	foreach (i; 0 .. n) {
		auto data = readln().split();
		plys[data[0]] = max(plys.get(data[0], 0), data[1].to!int());
	}

	plys.length.writeln();

	foreach (key; plys.keys.sort) {
		int cnt = 0;
		auto score = plys[key];
		foreach (skey; plys.keys) {
			if (key == skey) continue;
			if (plys[key] < plys[skey]) cnt++;
		}
		string ss;
		auto per = to!double(cnt)/n;

		if (per >= 0.5) ss = "noob";
		else if (per >= 0.2) ss = "random";
		else if (per >= 0.1) ss = "average";
		else if (per >= 0.01) ss = "hardcore";
		else ss = "pro";
		writeln(key, " ", ss);
	}
}


Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.You have to find the minimum number of digits in which these two numbers can differ.

The first line contains integer k (1 ≤ k ≤ 109). The second line contains integer n (1 ≤ n < 10100000). There are no leading zeros in n. It's guaranteed that this situation is possible.

Print the minimum number of digits in which the initial number and n can differ.

NoteIn the first example, the initial number could be 12.In the second example the sum of the digits of n is not less than k. The initial number could be equal to n.

// tested by Hightail - https://github.com/dj3500/hightail
import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.math, std.typecons, std.container, core.bitop;
import std.datetime, std.bigint;

int k;
string n;

void main() {
    scan(k);
    n = readln.chomp;

    int len = n.length.to!int;
    auto dig = new int[](len);

    foreach (i, d ; n) {
        dig[i] = d - '0';
    }

    int nsum = dig.sum();

    if (nsum >= k) {
        writeln(0);
        return;
    }

    dig.sort();

    debug {
        writeln(dig);
    }

    foreach (i ; 0 .. len) {
        nsum += 9 - dig[i];

        if (nsum >= k) {
            writeln(i + 1);
            return;
        }
    }
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

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


Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.

The first line contains a newspaper heading s1. The second line contains the letter text s2. s1 и s2 are non-empty lines consisting of spaces, uppercase and lowercase Latin letters, whose lengths do not exceed 200 symbols. The uppercase and lowercase letters should be differentiated. Vasya does not cut spaces out of the heading.

If Vasya can write the given anonymous letter, print YES, otherwise print NO

Instead of dogging Your footsteps it disappears but you dont notice anything
where is your dog

Instead of dogging Your footsteps it disappears but you dont notice anything
Your dog is upstears

Instead of dogging your footsteps it disappears but you dont notice anything
Your dog is upstears

module main;
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.variant,
	std.stdio,std.bitmanip;
import core.stdc.stdio : freopen;
alias RedBlackTree Rbt;
alias redBlackTree rbt;
alias BigInt big;
alias pair!(int,int) pii;
alias pair!(long,long) pll;
alias boyerMooreFinder strfind;
alias make_pair mp;
alias binary_search bins;
alias pair(X,Y)=Tuple!(X,q{fi},Y,q{se});
pair!(X,Y) make_pair(X,Y)(in X x_,in Y y_)
{
	pair!(X,Y) pp;
	pp.fi=x_;
	pp.se=y_;
	return pp;
}
immutable int mod=10^^9+7;
pure nothrow
{
	T lcm (T)(auto ref T a,auto ref T b)
	{
		return a/gcd(a,b)*b;
	}
	@property X sqr(X)(in X a_) {return a_*a_;}
	@property X cub(X)(in X a_) {return a_*a_*a_;}
	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))
	{
		size_t l=0,r=a.length;
		while(r-l>1)
		{
			auto m=(l+r)>>1;
			if(g<a[m])r=m;
			else l=m;
		}
		return (g<a[l])?l:r;
	}
	size_t binf(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 (g==a[l])?l: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,in size_t m) if(isRandomAccessRange!X)
{
	foreach(i;0..n)
	{
		foreach(j;0..m)write(a[i][j],' ');
		writeln;
	}
}
bool getarr(X)(X a,in size_t n) if(hasSlicing!X)
{bool b=1; foreach(ref i;a[0..n])b=input(&i);return b;}
bool input(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length), ptrs)==ptrs.length;}
bool read(T...)(T ptrs) if (ptrs.length > 0)
{return readf(replicate(" %s", ptrs.length)~'\n', ptrs)==ptrs.length;}
nothrow void inf(in char* name) {freopen(name,"r",core.stdc.stdio.stdin);}
nothrow void ouf(in char* name) {freopen(name,"w",core.stdc.stdio.stdout);}
@property auto arread(T)(){return readln.splitter.map!(to!(T)).array;}
//split strip isAlpha isNumber isWhite isLower isUpper toLower toUpper mixin
//cumulativeFold schwartzSort multiSort partialSort heapify join filter countUntil
//---------------------------------------------------------------program beginning-----------------------------------------------------------------

void main()
{
	/*int n;
	loop:while(read(&n))
	{

	}*/
	auto s=readln.split.join;
	int[char] m,q;
	foreach(i;s)m[i]++;
	auto t=readln.split.join;
	foreach(i;t)q[i]++;
	foreach(c,k;q)
	{
		if(c !in m || m[c]<k){writeln("NO");return;}
	}
	writeln("YES");
}


Petya organized a strange birthday party. He invited $$$n$$$ friends and assigned an integer $$$k_i$$$ to the $$$i$$$-th of them. Now Petya would like to give a present to each of them. In the nearby shop there are $$$m$$$ unique presents available, the $$$j$$$-th present costs $$$c_j$$$ dollars ($$$1 \le c_1 \le c_2 \le \ldots \le c_m$$$). It's not allowed to buy a single present more than once.For the $$$i$$$-th friend Petya can either buy them a present $$$j \le k_i$$$, which costs $$$c_j$$$ dollars, or just give them $$$c_{k_i}$$$ dollars directly.Help Petya determine the minimum total cost of hosting his party.

The first input line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 3 \cdot 10^5$$$) — the number of friends, and the number of unique presents available. The following line contains $$$n$$$ integers $$$k_1, k_2, \ldots, k_n$$$ ($$$1 \leq k_i \leq m$$$), assigned by Petya to his friends.  The next line contains $$$m$$$ integers $$$c_1, c_2, \ldots, c_m$$$ ($$$1 \le c_1 \le c_2 \le \ldots \le c_m \le 10^9$$$) — the prices of the presents. It is guaranteed that sum of values $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$, and the sum of values $$$m$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case output a single integer — the minimum cost of the party.

NoteIn the first example, there are two test cases. In the first one, Petya has $$$5$$$ friends and $$$4$$$ available presents. Petya can spend only $$$30$$$ dollars if he gives  $$$5$$$ dollars to the first friend.  A present that costs $$$12$$$ dollars to the second friend.  A present that costs $$$5$$$ dollars to the third friend.  A present that costs $$$3$$$ dollars to the fourth friend.  $$$5$$$ dollars to the fifth friend. In the second one, Petya has $$$5$$$ and $$$5$$$ available presents. Petya can spend only $$$190$$$ dollars if he gives  A present that costs $$$10$$$ dollars to the first friend.  A present that costs $$$40$$$ dollars to the second friend.  $$$90$$$ dollars to the third friend.  $$$40$$$ dollars to the fourth friend.  $$$10$$$ dollars to the fifth friend.

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)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		readln;
		auto k = readln.splitter.map !(to !(int)).array;
		auto c = readln.splitter.map !(to !(int)).array;
		sort (k);
		int lo = 1;
		for (int j = 1; j <= m; j++)
		{
			if (j <= n && j < k[$ - j])
			{
				k[$ - j] = j;
			}
			else
			{
				break;
			}
		}
		writeln (k.map !(i => c[i - 1]).sum (0L));
	}
}

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

void get(Args...)(ref Args args)
{
    import std.traits, std.meta, std.typecons;

    static if (Args.length == 1) {
        alias Arg = Args[0];

        static if (isArray!Arg) {
          static if (isSomeChar!(ElementType!Arg)) {
            args[0] = readln.chomp.to!Arg;
          } else {
            args[0] = readln.split.to!Arg;
          }
        } else static if (isTuple!Arg) {
            auto input = readln.split;
            static foreach (i; 0..Fields!Arg.length) {
                args[0][i] = input[i].to!(Fields!Arg[i]);
            }
        } else {
            args[0] = readln.chomp.to!Arg;
        }
    } else {
        auto input = readln.split;
        assert(input.length == Args.length);

        static foreach (i; 0..Args.length) {
            args[i] = input[i].to!(Args[i]);
        }
    }
}

void get_lines(Args...)(size_t N, ref Args args)
{
    import std.traits, std.range;

    static foreach (i; 0..Args.length) {
        static assert(isArray!(Args[i]));
        args[i].length = N;
    }

    foreach (i; 0..N) {
        static if (Args.length == 1) {
            get(args[0][i]);
        } else {
            auto input = readln.split;
            static foreach (j; 0..Args.length) {
                args[j][i] = input[j].to!(ElementType!(Args[j]));
            }
        }
    }
}

alias C = Tuple!(int, "i", long, "k", long, "c");

void main()
{
    int T; get(T);
    while (T--) {
        int N, M; get(N, M);
        int[] KS; get(KS);
        long[] CS; get(CS);
        C[] cs;
        foreach (i, c; CS) cs ~= C(i.to!int, 0, c);
        foreach (k; KS) ++cs[k - 1].k;
        sort!"a.c > b.c"(cs);
        auto bs = new bool[](M);
        long r;
        int i;
        foreach (c; cs) {
            while (c.k > 0 && i < c.i) {
                if (!bs[i]) {
                    bs[i] = true;
                    r += CS[i];
                    --c.k;
                }
                ++i;
            }
            bs[c.i] = true;
            while (c.k > 0) {
                r += c.c;
                --c.k;
            }
        }
        writeln(r);
    }
}

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

void theCode(){
    int n, m;
    n = scan!int, m = scan!int;
    auto peeps = scanArray;
    auto gifts = scanArray;
    peeps.sort;
    peeps.reverse;
    ll res = 0;
    int gptr = 0;
    for(int i = 0; i < n; ++i){
        if(gptr < m && gifts[gptr] < gifts[to!int(peeps[i]-1)]){
            res += gifts[gptr];
            ++gptr;
        }else{
            res += gifts[to!int(peeps[i] -1)];
        }
    }
    writeln(res);
}

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

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

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

string FMT_F = "%.10f";

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

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

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

long mod = 10^^9 + 7;
//long mod = 998_244_353;
//long mod = 1_000_003;
void moda(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 m = RD!int;
		auto k = RDA!int(-1);
		auto c = RDA;

		k.sort();
		BinaryHeap!(Array!long, "a > b") heap1, heap2;
		int ci;
		foreach (i; 0..n)
		{
			while (ci <= k[i])
			{
				heap1.insert(c[ci]);
				++ci;
			}
			heap2.insert(c[k[i]]);
			if (heap2.front <= heap1.front)
			{
				ans[ti] += heap2.front; heap2.removeFront;
			}
			else
			{
				ans[ti] += heap1.front; heap1.removeFront;
			}
		}
	}

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


This is a simplified version of the problem B2. Perhaps you should read the problem B2 before you start solving B1.Paul and Mary have a favorite string $$$s$$$ which consists of lowercase letters of the Latin alphabet. They want to paint it using pieces of chalk of two colors: red and green. Let's call a coloring of a string wonderful if the following conditions are met:  each letter of the string is either painted in exactly one color (red or green) or isn't painted;  each two letters which are painted in the same color are different;  the number of letters painted in red is equal to the number of letters painted in green;  the number of painted letters of this coloring is maximum among all colorings of the string which meet the first three conditions. E. g. consider a string $$$s$$$ equal to "kzaaa". One of the wonderful colorings of the string is shown in the figure.    The example of a wonderful coloring of the string "kzaaa". Paul and Mary want to learn by themselves how to find a wonderful coloring of the string. But they are very young, so they need a hint. Help them find $$$k$$$ — the number of red (or green, these numbers are equal) letters in a wonderful coloring.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one non-empty string $$$s$$$ which consists of lowercase letters of the Latin alphabet. The number of characters in the string doesn't exceed $$$50$$$.

For each test case, output a separate line containing one non-negative integer $$$k$$$ — the number of letters which will be painted in red in a wonderful coloring.

NoteThe first test case contains the string from the statement. One of the wonderful colorings is shown in the figure. There's no wonderful coloring containing $$$3$$$ or more red letters because the total number of painted symbols will exceed the string's length.The string from the second test case can be painted as follows. Let's paint the first occurrence of each of the letters "c", "o", "e" in red and the second ones in green. Let's paint the letters "d", "f" in red and "r", "s" in green. So every letter will be painted in red or green, hence the answer better than $$$5$$$ doesn't exist.The third test case contains the string of distinct letters, so you can paint any set of characters in red, as long as the size of this set doesn't exceed half of the size of the string and is the maximum possible.The fourth test case contains a single letter which cannot be painted in red because there will be no letter able to be painted in green.The fifth test case contains a string of identical letters, so there's no way to paint more than one letter in red.

import std.stdio;
import std.ascii;
import std.algorithm;
import std.range;
import core.stdc.stdio;

void main()
{
	int t = readInt!int;
	while (t--)
	{
		solve();
	}
}

void solve()
{
	string s = readString;
	int[30] cnt = 0;
	foreach(c; s) cnt[c-'a']++;
	int c2 = 0;
	int c1 = 0;
	foreach(c; cnt)
	{
		if (c >= 2)
		{
			c2 += 1;
		}
		if (c == 1)
		{
			c1++;
		}
	}
	(((c1/2)*2+c2*2)/2).writeln;
}

/* INPUT ROUTINES */
int currChar;
static this()
{
	currChar = getchar();
}

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

void popChar()
{
	currChar = getchar();
}

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

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
/**MODULAR SYSTEM*/
struct Z(immutable long m)
{
	long rep;
	this(long num)
	{
		rep = num;
	}

	Z!m opBinary(string operator)(Z!m rhs)
	{
		static if (operator == "+")
		{
			long result = rhs.rep + this.rep;
			if (result >= m)
				result -= m;
			return Z!m(result);
		}
		else static if (operator == "-")
		{
			long result = this.rep - rhs.rep;
			if (result < 0)
				result += m;
			return Z!m(result);
		}
		else static if (operator == "*")
		{
			long result = this.rep * rhs.rep;
			if (result >= m)
				result %= m;
			return Z!m(result);
		}
		else
			static assert(text("Operator ", operator, " not supported"));
	}

	Z!m opBinary(string operator)(long exponent) if (operator == "^^")
	{
		assert(exponent >= 0);
		Z!m base = this;
		Z!m result = 1;
		while (exponent)
		{
			if (exponent & 1)
				result = result * base;
			base = base * base;
			exponent >>= 1;
		}
		return result;
	}

	invariant
	{
		assert(rep >= 0 && rep < m);
	}
}

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

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    auto a = readln.strip.split("").map!(x => x[0] - 'a').array;
    int[int] freq;
    foreach (x ; a)
      freq[x]++;
    long nocolor = 0;
    foreach (k, v ; freq)
      if (v > 2)
        nocolor += v - 2;
    writeln((cast(long)a.length - nocolor) / 2);
  }
}

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

void read(S...)(ref S args) {
  auto input = readln.split;
  assert(input.length == args.length);
  foreach (i, ref arg; args) {
    arg = input[i].to!(S[i]);
  }
}

auto list(T)() { return readln.split.map!(e => e.to!T).array; }

string[] words;

int solve(char c) {
  int[] arr = new int[words.length];

  foreach (i, w; words) {
    auto a = w.count(c).to!int;
    arr[i] = a - (w.length.to!int - a);
  }

  sort(arr);
  reverse(arr);

  if (arr[0] < 1) return 0;

  long total = arr[0];
  int answer = 1;

  foreach (i; 1 .. arr.length) {
    total += arr[i];
    if (total <= 0) break;
    answer++;
  }

  return answer;
}

void main() {
  int t;
  read(t);

  while (t--) {
    string s = readln.strip();

    int once = 0;
    int more = 0;
    foreach (c; 'a' .. 'z' + 1) {
      auto T = s.count(c);
      if (T == 1) once++;
      if (T > 1) more++;
    }

    writeln(more + once / 2);
  }
}


Eugene likes working with arrays. And today he needs your help in solving one challenging task.An array $$$c$$$ is a subarray of an array $$$b$$$ if $$$c$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array $$$[-1, 2, -3]$$$ is good, as all arrays $$$[-1]$$$, $$$[-1, 2]$$$, $$$[-1, 2, -3]$$$, $$$[2]$$$, $$$[2, -3]$$$, $$$[-3]$$$ have nonzero sums of elements. However, array $$$[-1, 2, -1, -3]$$$ isn't good, as his subarray $$$[-1, 2, -1]$$$ has sum of elements equal to $$$0$$$.Help Eugene to calculate the number of nonempty good subarrays of a given array $$$a$$$.

The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 2 \times 10^5$$$)  — the length of array $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$)  — the elements of $$$a$$$.

Output a single integer  — the number of good subarrays of $$$a$$$.

NoteIn the first sample, the following subarrays are good: $$$[1]$$$, $$$[1, 2]$$$, $$$[2]$$$, $$$[2, -3]$$$, $$$[-3]$$$. However, the subarray $$$[1, 2, -3]$$$ isn't good, as its subarray $$$[1, 2, -3]$$$ has sum of elements equal to $$$0$$$.In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray $$$[41, -41, 41]$$$ isn't good, as its subarray $$$[41, -41]$$$ has sum of elements equal to $$$0$$$.

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

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

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

    int[long] pos;
    pos[0] = 0;

    long ans = 0;
    long sm = 0;
    int lstpos = -1;
    foreach (i, e; arr) {
        sm += e;
        lstpos = max(lstpos, pos.get(sm, -1));
        ans += i+1 - (lstpos+1);
        pos[sm] = i.to!int + 1;
    }

    ans.writeln;
}

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

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto a = readln.splitter.map !(to !(int)).array;
		long res = 0;
		int [long] used;
		used[0] = 0;
		int lo = 0;
		long cur;
		foreach (i; 0..n)
		{
			cur += a[i];
			if (cur in used)
			{
				lo = max (lo, used[cur] + 1);
			}
			used[cur] = i + 1;
			res += i + 1 - lo;
		}
		writeln (res);
	}
}

//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;
import std.typecons;

final class InputReader {
  private:
  ubyte[] p, buffer;
  bool eof;
  bool rawRead () {
    if (eof) {
      return false;
    }
    p = stdin.rawRead (buffer);
    if (p.empty) {
      eof = true;
      return false;
    }
    return true;
  }
  ubyte nextByte(bool check) () {
    static if (check) {
      if (p.empty) {
        if (!rawRead ()) {
          return 0;
        }
      }
    }
    auto r = p.front;
    p.popFront ();
    return r;
  }
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
  }
  bool seekByte (in ubyte lo) {
    while (true) {
      p = p.find! (c => c >= lo);
      if (!p.empty) {
        return false;
      }
      if (!rawRead ()) {
        return true;
      }
    }
  }
  template next(T) if (isSigned!T) {
    T next ()  {
      if (seekByte (45)) {
        return 0;
      }
      T res;
      ubyte b = nextByte!false ();
      if (b == 45) {
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    T next () {
      if (seekByte (48)) {
        return 0;
      }
      T res = nextByte!false () - 48;
      while (true) {
        ubyte b = nextByte!true ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  T[] nextA(T) (in int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

alias T = Tuple!(long, uint);

void main() {
  auto r = new InputReader ();
  const n = r.next!uint;
  auto a = r.nextA!int (n);
  const s = sum (a, 0L);
  //prefix[i] + suffix[j] + a[i .. j] == s
  //prefix[i] + suffix[j] == s
  auto pr = new long[n+1];
  pr[0] = 0;
  foreach (i; 1 .. n + 1) pr[i] = pr[i-1] + a[i-1];
  /*
  auto sf = new long[n+1];
  sf[n] = 0;
  foreach_reverse (i; 0 .. n) sf[i] = sf[i+1] + a[i];
  */
  T[] x;
  x.reserve (n + 1);
  foreach (i; 0 .. n + 1) x ~= tuple (pr[i], i);
  sort (x);
  debug stderr.writeln ("pr = ", pr);
  debug stderr.writeln ("x = ", x);
  int i;
  auto z = new uint[n+1];
  z[] = uint.max;
  while (i < x.length) {
    int j = i + 1;
    while (j < x.length && x[i][0] == x[j][0]) ++j;
    uint last = uint.max;
    foreach_reverse (const ref q; x[i .. j]) {
      debug stderr.writeln (q);
      if (last != uint.max) {
        z[q[1]] = last - 1;
      }
      last = q[1];
    }
    i = j;
  }
  debug stderr.writeln ("z = ", z);
  foreach_reverse (k; 0 .. n) {
    z[k] = min (z[k+1], z[k]);
  }
  debug stderr.writeln ("z = ", z);
  long res;
  foreach (k; 0 .. n) {
    z[k] = min (z[k], n);
    if (z[k] > k) {
      res += z[k] - k;
    }
  }
  writeln (res);
}

import std.stdio, std.conv, std.string, std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
void main(string[] args){ if(args.length > 1) if(args[1] == "-debug") DEBUG = 1; solve(); } bool DEBUG = 0;
void log(A ...)(lazy A a){ if(DEBUG) print(a); }
void print(){ writeln(""); } void print(T)(T t){ writeln(t); } void print(T, A ...)(T t, A a){ write(t, " "), print(a); }
string unsplit(T)(T xs){ return xs.array.to!(string[]).join(" "); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; } T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
T lowerTo(T)(ref T x, T y){ if(x > y) x = y; return x; } T raiseTo(T)(ref T x, T y){ if(x < y) x = y; return x; }

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

void solve(){
    int n = scan!int;
    long[] as = scan!long(n);

    long[] sums = [0];
    foreach(a; as) sums ~= sums[$ - 1] + a;

    long ans;
    int[long] pos;
    int l = 0;
    foreach(i, s; sums){
        if(s in pos) l.raiseTo(pos[s] + 1);
        ans += i - l;
        pos[s] = i.to!int;
    }

    ans.writeln;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

long test(long[] arr)
{
	long res;
	foreach (i; 0..arr.length)
	{
		long x;
		foreach (j; i..arr.length)
		{
			x += arr[j];
			if (arr[j] == 0 || x == 0) break;
			++res;
		}
	}
	return res;
}

void main()
{
	auto n = RD!int;
	auto a = RDA;
	/*while (true){
	auto n = 3;
	auto a = new long[](3);
	foreach (i; 0..3)
	{
		a[i] = uniform(-3, 4);
	}*/

	int[][long] set;
	auto b = new long[](n+1);
	foreach_reverse (i; 0..n)
	{
		b[i] = b[i+1] + a[i];
	}
	foreach (i; 0..n+1)
	{
		set[b[i]] ~= i;
	}
	auto zero = new RedBlackTree!(int);
	foreach (i; 0..n)
	{
		if (a[i] == 0)
			zero.insert(i);
	}

	long ans;
	foreach (i; 0..n)
	{
		if (a[i] == 0) continue;
		auto arr = set.get(b[i+1], []);
		if (arr.empty)
		{
			ans += i+1;
		}
		else
		{
			auto r = binarySearch!((int p) => arr[p] < i)(-1, cast(int)arr.length);
			int r2 = -1;
			auto arr2 = zero.lowerBound(i);
			if (!arr2.empty)
				r2 = arr2.back;
			if (r == -1 && r2 == -1)
			{
				ans += i+1;
			}
			else
			{
				int x;
				if (r != -1)
					x = arr[r];
				if (r2 != -1)
					x.chmax(r2);
				zero.insert(x);
				ans += i - x;
				//debug writeln("i:", i, " r:", r, " arr[r]:", arr[r]);
			}
		}
		//debug writeln(ans);
	}

	/*auto ans2 = test(a);
	/writeln(a);
	writeln(ans, ":", ans2);*/
	writeln(ans);
	stdout.flush;
	/*if (ans != ans2) break;
	}*/
	debug readln;
}

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

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

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

    int[int] pos;
    pos[0] = 0;

    long ans = 0;
    int sm = 0, lstpos = -1;
    foreach (i, e; arr) {
        sm += e;
        lstpos = max(lstpos, pos.get(sm, -1));
        ans += i+1 - (lstpos+1);
        pos[sm] = i.to!int + 1;
    }

    ans.writeln;
}

//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;
import std.typecons;

final class InputReader {
  private:
  ubyte[] p, buffer;
  bool eof;
  bool rawRead () {
    if (eof) {
      return false;
    }
    p = stdin.rawRead (buffer);
    if (p.empty) {
      eof = true;
      return false;
    }
    return true;
  }
  ubyte nextByte(bool check) () {
    static if (check) {
      if (p.empty) {
        if (!rawRead ()) {
          return 0;
        }
      }
    }
    auto r = p.front;
    p.popFront ();
    return r;
  }
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
  }
  bool seekByte (in ubyte lo) {
    while (true) {
      p = p.find! (c => c >= lo);
      if (!p.empty) {
        return false;
      }
      if (!rawRead ()) {
        return true;
      }
    }
  }
  template next(T) if (isSigned!T) {
    T next ()  {
      if (seekByte (45)) {
        return 0;
      }
      T res;
      ubyte b = nextByte!false ();
      if (b == 45) {
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    T next () {
      if (seekByte (48)) {
        return 0;
      }
      T res = nextByte!false () - 48;
      while (true) {
        ubyte b = nextByte!true ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  T[] nextA(T) (in int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto r = new InputReader ();
  const n = r.next!uint;
  auto a = r.nextA!int (n);
  const s = sum (a, 0L);
  //prefix[i] + suffix[j] + a[i .. j] == s
  //prefix[i] + suffix[j] == s
  auto pr = new long[n+1];
  pr[0] = 0;
  foreach (i; 1 .. n + 1) pr[i] = pr[i-1] + a[i-1];
  /*
  auto sf = new long[n+1];
  sf[n] = 0;
  foreach_reverse (i; 0 .. n) sf[i] = sf[i+1] + a[i];
  */
  int[long] h;
  Tuple!(int, int)[] bad;
  h[0] = 0;
  debug stderr.writeln ("pr = ", pr);
  foreach (j; 0 .. n) {
    //auto p = s - sf[j+1];
    auto p = pr[j+1];
    auto ptr = p in h;
    if (ptr !is null) {
      bad ~= tuple (*ptr, (j + 1).to!int);
    } else {
      h[p] = j + 1;
    }
  }
  int cur = int.max;
  foreach_reverse (ref q; bad) {
    cur = min (cur, q[1]);
    q[1] = cur;
  }
  debug stderr.writeln(bad);
  long res;
  auto e = assumeSorted (bad);
  foreach (i; 0 .. n) {
    auto d = e.upperBound (tuple (i, -1));
    if (d.empty) {
      res += n - i;
    } else {
      res += d.front[1] - 1 - i;
    }
  }
  writeln (res);
}

//prewritten code: https://github.com/antma/algo
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;
import std.typecons;

final class InputReader {
  private:
  ubyte[] p, buffer;
  bool eof;
  bool rawRead () {
    if (eof) {
      return false;
    }
    p = stdin.rawRead (buffer);
    if (p.empty) {
      eof = true;
      return false;
    }
    return true;
  }
  ubyte nextByte(bool check) () {
    static if (check) {
      if (p.empty) {
        if (!rawRead ()) {
          return 0;
        }
      }
    }
    auto r = p.front;
    p.popFront ();
    return r;
  }
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
  }
  bool seekByte (in ubyte lo) {
    while (true) {
      p = p.find! (c => c >= lo);
      if (!p.empty) {
        return false;
      }
      if (!rawRead ()) {
        return true;
      }
    }
  }
  template next(T) if (isSigned!T) {
    T next ()  {
      if (seekByte (45)) {
        return 0;
      }
      T res;
      ubyte b = nextByte!false ();
      if (b == 45) {
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    T next () {
      if (seekByte (48)) {
        return 0;
      }
      T res = nextByte!false () - 48;
      while (true) {
        ubyte b = nextByte!true ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  T[] nextA(T) (in int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto r = new InputReader ();
  const n = r.next!uint;
  auto a = r.nextA!int (n);
  const s = sum (a, 0L);
  //prefix[i] + suffix[j] + a[i .. j] == s
  //prefix[i] + suffix[j] == s
  auto pr = new long[n+1];
  pr[0] = 0;
  foreach (i; 1 .. n + 1) pr[i] = pr[i-1] + a[i-1];
  /*
  auto sf = new long[n+1];
  sf[n] = 0;
  foreach_reverse (i; 0 .. n) sf[i] = sf[i+1] + a[i];
  */
  int[long] h;
  Tuple!(int, int)[] bad;
  h[0] = 0;
  debug stderr.writeln ("pr = ", pr);
  foreach (j; 0 .. n) {
    //auto p = s - sf[j+1];
    auto p = pr[j+1];
    auto ptr = p in h;
    if (ptr !is null) {
      bad ~= tuple (*ptr, (j + 1).to!int);
    }
    h[p] = j + 1;
  }
  int cur = int.max;
  foreach_reverse (ref q; bad) {
    cur = min (cur, q[1]);
    q[1] = cur;
  }
  debug stderr.writeln(bad);
  long res;
  auto e = assumeSorted (bad);
  foreach (i; 0 .. n) {
    auto d = e.upperBound (tuple (i, -1));
    if (d.empty) {
      res += n - i;
    } else {
      res += d.front[1] - 1 - i;
    }
  }
  writeln (res);
}

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

string FMT_F = "%.10f";

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

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

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

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

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

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

	int[][long] set;
	auto b = new long[](n+1);
	foreach_reverse (i; 0..n)
	{
		b[i] = b[i+1] + a[i];
	}
	foreach (i; 0..n+1)
	{
		set[b[i]] ~= i;
	}

	long ans;
	foreach (i; 0..n)
	{
		if (a[i] == 0) continue;
		auto arr = set.get(b[i+1], []);
		if (arr.empty)
		{
			ans += i+1;
		}
		else
		{
			auto r = binarySearch!((int p) => arr[p] < i)(-1, cast(int)arr.length);
			if (r == -1)
			{
				ans += i+1;
			}
			else
			{
				ans += i - arr[r];
				debug writeln("i:", i, " r:", r, " arr[r]:", arr[r]);
			}
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

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

	int[][long] set;
	auto b = new long[](n+1);
	foreach_reverse (i; 0..n)
	{
		b[i] = b[i+1] + a[i];
	}
	foreach (i; 0..n+1)
	{
		set[b[i]] ~= i;
	}

	long ans;
	long x;
	foreach (i; 0..n)
	{
		x += a[i];
		auto arr = set.get(b[i+1], []);
		if (arr.empty)
		{
			ans += i+1;
		}
		else
		{
			auto r = binarySearch!((int p) => arr[p] < i)(-1, cast(int)arr.length);
			if (r == -1)
			{
				ans += i+1;
			}
			else
			{
				ans += i - arr[r];
				debug writeln("i:", i, " r:", r, " arr[r]:", arr[r]);
			}
		}
	}

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

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

string FMT_F = "%.10f";

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

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

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

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

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

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

	int[][long] set;
	auto b = new long[](n+1);
	foreach_reverse (i; 0..n)
	{
		b[i] = b[i+1] + a[i];
	}
	foreach (i; 0..n+1)
	{
		set[b[i]] ~= i;
	}
	int[] zero;
	foreach (i; 0..n)
	{
		if (a[i] == 0)
			zero ~= i;
	}

	long ans;
	foreach (i; 0..n)
	{
		if (a[i] == 0) continue;
		auto arr = set.get(b[i+1], []);
		if (arr.empty)
		{
			ans += i+1;
		}
		else
		{
			auto r = binarySearch!((int p) => arr[p] < i)(-1, cast(int)arr.length);
			auto r2 = binarySearch!((int p) => zero[p] < i)(-1, cast(int)zero.length);
			if (r == -1 && r2 == -1)
			{
				ans += i+1;
			}
			else
			{
				int x;
				if (r != -1)
					x = arr[r];
				if (r2 != -1)
					x.chmax(zero[r2]);
				ans += i - x;
				//debug writeln("i:", i, " r:", r, " arr[r]:", arr[r]);
			}
		}
	}

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


A student of z-school found a kind of sorting called z-sort. The array a with n elements are z-sorted if two conditions hold:  ai ≥ ai - 1 for all even i,  ai ≤ ai - 1 for all odd i > 1. For example the arrays [1,2,1,2] and [1,1,1,1] are z-sorted while the array [1,2,3,4] isn’t z-sorted.Can you make the array z-sorted?

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array a. The second line contains n integers ai (1 ≤ ai ≤ 109) — the elements of the array a.

If it's possible to make the array a z-sorted print n space separated integers ai — the elements after z-sort. Otherwise print the only word "Impossible".

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

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

    int[1000] arr, outarr;
    int n;
    readf(" %s\n", &n);
    foreach (i ; 0 .. n) {
        readf(" %s", &arr[i]);
    }
    arr[0 .. n].sort();
    int idx = n;
    for (int i = 1; i < n; i += 2) {
        outarr[i] = arr[--idx];
    }
    idx = 0;
    for (int i = 0; i < n; i += 2) {
        outarr[i] = arr[idx++];
    }
    writefln("%(%s %)", outarr[0 .. n]);

    return 0;
}


A binary matrix is called good if every even length square sub-matrix has an odd number of ones. Given a binary matrix $$$a$$$ consisting of $$$n$$$ rows and $$$m$$$ columns, determine the minimum number of cells you need to change to make it good, or report that there is no way to make it good at all. All the terms above have their usual meanings — refer to the Notes section for their formal definitions.

The first line of input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq m \leq 10^6$$$ and $$$n\cdot m \leq 10^6$$$)  — the number of rows and columns in $$$a$$$, respectively.  The following $$$n$$$ lines each contain $$$m$$$ characters, each of which is one of 0 and 1. If the $$$j$$$-th character on the $$$i$$$-th line is 1, then $$$a_{i,j} = 1$$$. Similarly, if the $$$j$$$-th character on the $$$i$$$-th line is 0, then $$$a_{i,j} = 0$$$.

Output the minimum number of cells you need to change to make $$$a$$$ good, or output $$$-1$$$ if it's not possible at all.

NoteIn the first case, changing $$$a_{1,1}$$$ to $$$0$$$ and $$$a_{2,2}$$$ to $$$1$$$ is enough. You can verify that there is no way to make the matrix in the second case good. Some definitions —   A binary matrix is one in which every element is either $$$1$$$ or $$$0$$$.  A sub-matrix is described by $$$4$$$ parameters — $$$r_1$$$, $$$r_2$$$, $$$c_1$$$, and $$$c_2$$$; here, $$$1 \leq r_1 \leq r_2 \leq n$$$ and $$$1 \leq c_1 \leq c_2 \leq m$$$.  This sub-matrix contains all elements $$$a_{i,j}$$$ that satisfy both $$$r_1 \leq i \leq r_2$$$ and $$$c_1 \leq j \leq c_2$$$.  A sub-matrix is, further, called an even length square if $$$r_2-r_1 = c_2-c_1$$$ and $$$r_2-r_1+1$$$ is divisible by $$$2$$$.

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

void main ()
{
	int rows, cols;
	while (readf !(" %s %s") (rows, cols) > 0)
	{
		readln;
		auto a = rows.iota.map !(_ => readln.strip.map
		    !(q{cast (int) (a) - '0'}).array).array;
		if (rows > 3 && cols > 3)
		{
			writeln (-1);
			continue;
		}

		if (rows > cols)
		{
			auto b = new int [] [] (cols, rows);
			foreach (row; 0..rows)
			{
				foreach (col; 0..cols)
				{
					b[col][row] = a[row][col];
				}
			}
			a = b;
			swap (rows, cols);
		}
		if (rows == 1)
		{
			writeln (0);
			continue;
		}

		auto g = new int [cols];
		foreach (col; 0..cols)
		{
			foreach (row; 0..rows)
			{
				g[col] ^= a[row][col] << row;
			}
		}

		auto sets = 1 << rows;
		auto f = new int [] [] (2, sets);
		int b = 0;
		foreach (s; 0..sets)
		{
			f[b][s] = popcnt (s ^ g[0]);
		}
		foreach (col; 1..cols)
		{
			b ^= 1;
			f[b][] = int.max;
			foreach (s; 0..sets)
			{
				foreach (t; 0..sets)
				{
					if ((popcnt ((s ^ t) & 3) & 1) &&
					    (rows == 2 ||
					    (popcnt ((s ^ t) >> 1) & 1)))
					{
						f[b][t] = min (f[b][t],
						    f[!b][s] +
						    popcnt (t ^ g[col]));
					}
				}
			}
		}
		writeln (f[b].minElement);
	}
}

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

void main ()
{
	int rows, cols;
	while (readf !(" %s %s") (rows, cols) > 0)
	{
		readln;
		auto a = rows.iota.map !(_ => readln.strip.map
		    !(q{cast (int) (a) - '0'}).array).array;
		if (rows > 3 && cols > 3)
		{
			writeln (-1);
			continue;
		}

		if (rows > cols)
		{
			auto b = new int [] [] (cols, rows);
			foreach (row; 0..rows)
			{
				foreach (col; 0..cols)
				{
					b[col][row] = a[row][col];
				}
			}
			a = b;
			swap (rows, cols);
		}

		int res = 0;
		foreach (col; 1..cols)
		{
			bool bad = false;
			foreach (row; 1..rows)
			{
				bad |= (a[row - 1][col - 1] + a[row - 1][col] +
				    a[row][col - 1] + a[row][col]) % 2 == 0;
			}
			res += bad;
		}
		writeln (res);
	}
}


Reforms continue entering Berland. For example, during yesterday sitting the Berland Parliament approved as much as n laws (each law has been assigned a unique number from 1 to n). Today all these laws were put on the table of the President of Berland, G.W. Boosch, to be signed.This time mr. Boosch plans to sign 2k laws. He decided to choose exactly two non-intersecting segments of integers from 1 to n of length k and sign all laws, whose numbers fall into these segments. More formally, mr. Boosch is going to choose two integers a, b (1 ≤ a ≤ b ≤ n - k + 1, b - a ≥ k) and sign all laws with numbers lying in the segments [a; a + k - 1] and [b; b + k - 1] (borders are included).As mr. Boosch chooses the laws to sign, he of course considers the public opinion. Allberland Public Opinion Study Centre (APOSC) conducted opinion polls among the citizens, processed the results into a report and gave it to the president. The report contains the absurdity value for each law, in the public opinion. As mr. Boosch is a real patriot, he is keen on signing the laws with the maximum total absurdity. Help him.

The first line contains two integers n and k (2 ≤ n ≤ 2·105, 0 < 2k ≤ n) — the number of laws accepted by the parliament and the length of one segment in the law list, correspondingly. The next line contains n integers x1, x2, ..., xn — the absurdity of each law (1 ≤ xi ≤ 109).

Print two integers a, b — the beginning of segments that mr. Boosch should choose. That means that the president signs laws with numbers from segments [a; a + k - 1] and [b; b + k - 1]. If there are multiple solutions, print the one with the minimum number a. If there still are multiple solutions, print the one with the minimum b.

NoteIn the first sample mr. Boosch signs laws with numbers from segments [1;2] and [4;5]. The total absurdity of the signed laws equals 3 + 6 + 1 + 6 = 16.In the second sample mr. Boosch signs laws with numbers from segments [1;2] and [3;4]. The total absurdity of the signed laws equals 1 + 1 + 1 + 1 = 4.

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 inf = 10^^9 + 7;

void main() {
    int n, k;
    readVars(n, k);
    auto x = readln.split.map!(to!long).array;

    auto cs = new long[](n + 1);
    iota(n).each!(i => cs[i + 1] += cs[i] + x[i]);

    auto pfm = new long[](n + 1);
    auto sfm = new long[](n + 1);
    auto pfi = new int[](n + 1);
    auto sfi = new int[](n + 1);

    foreach (i ; k .. n + 1) {
        pfm[i] = pfm[i - 1];
        pfi[i] = pfi[i - 1];

        if (cs[i] - cs[i - k] > pfm[i - 1]) {
            pfm[i] = cs[i] - cs[i - k];
            pfi[i] = i - k;
        }
    }

    foreach_reverse (i ; 0 .. n - k + 1) {
        sfm[i] = sfm[i + 1];
        sfi[i] = sfi[i + 1];

        if (cs[i + k] - cs[i] >= sfm[i + 1]) {
            sfm[i] = cs[i + k] - cs[i];
            sfi[i] = i;
        }
    }

    debug {
        //stderr.writeln("pfm:",pfm);
        stderr.writeln("pfi:",pfi);
        stderr.writeln("sfm:",sfm);
        stderr.writeln("sfi:",sfi);
    }

    long max_v;
    int a, b;

    foreach (i ; k .. n - k + 1) {
        if (pfm[i] + sfm[i] > max_v) {
            max_v = pfm[i] + sfm[i];
            a = pfi[i];
            b = sfi[i];
        }
    }

    writeln(a + 1, " ", b + 1);
}

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, 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 inf = 10^^9 + 7;

void main() {
    int n, k;
    readVars(n, k);
    auto x = readln.split.map!(to!long).array;

    auto cs = new long[](n + 1);
    iota(n).each!(i => cs[i + 1] += cs[i] + x[i]);

    int a = 0, b = k;
    long maxsum = cs[k] - cs[0] + cs[2*k] - cs[k];
    long maxpf = cs[k] - cs[0];
    int maxpfi = 0;

    foreach (i ; k + 1 .. n - k + 1) {
        if (cs[i] - cs[i - k] > maxpf) {
            maxpf = cs[i] - cs[i - k];
            maxpfi = i - k;
        }

        if (maxpf + cs[i + k] - cs[i] > maxsum) {
            maxsum = maxpf + cs[i + k] - cs[i];
            a = maxpfi;
            b = i;
        }
    }

    writeln(a + 1, " ", b + 1);
}

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, 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 inf = 10^^9 + 7;

void main() {
    int n, k;
    readVars(n, k);
    auto x = readln.split.map!(to!long).array;

    auto cs = new long[](n + 1);
    iota(n).each!(i => cs[i + 1] += cs[i] + x[i]);

    auto pfm = new long[](n + 1);
    auto sfm = new long[](n + 1);
    auto pfi = new int[](n + 1);
    auto sfi = new int[](n + 1);

    foreach (i ; k .. n + 1) {
        pfm[i] = pfm[i - 1];
        pfi[i] = pfi[i - 1];

        if (cs[i] - cs[i - k] > pfm[i - 1]) {
            pfm[i] = cs[i] - cs[i - k];
            pfi[i] = i - k;
        }
    }

    foreach_reverse (i ; 0 .. n - k + 1) {
        sfm[i] = sfm[i + 1];
        sfi[i] = sfi[i + 1];

        if (cs[i + k] - cs[i] >= sfm[i + 1]) {
            sfm[i] = cs[i + k] - cs[i];
            sfi[i] = i;
        }
    }

    debug {
        stderr.writeln("pfm:",pfm);
        stderr.writeln("pfi:",pfi);
        stderr.writeln("sfm:",sfm);
        stderr.writeln("sfi:",sfi);
    }

    long max_v;
    int a, b;

    foreach (i ; k .. n - k + 1) {
        if (pfm[i] + sfm[i] > max_v) {
            max_v = pfm[i] + sfm[i];
            a = pfi[i];
            b = sfi[i];
        }
    }

    writeln(a + 1, " ", b + 1);
}

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


Limak is a little polar bear. His parents told him to clean a house before the New Year's Eve. Their house is a rectangular grid with h rows and w columns. Each cell is an empty square.He is a little bear and thus he can't clean a house by himself. Instead, he is going to use a cleaning robot.A cleaning robot has a built-in pattern of n moves, defined by a string of the length n. A single move (character) moves a robot to one of four adjacent cells. Each character is one of the following four: 'U' (up), 'D' (down), 'L' (left), 'R' (right). One move takes one minute.A cleaning robot must be placed and started in some cell. Then it repeats its pattern of moves till it hits a wall (one of four borders of a house). After hitting a wall it can be placed and used again.Limak isn't sure if placing a cleaning robot in one cell will be enough. Thus, he is going to start it w·h times, one time in each cell. Maybe some cells will be cleaned more than once but who cares?Limak asks you one question. How much time will it take to clean a house? Find and print the number of minutes modulo 109 + 7. It's also possible that a cleaning robot will never stop — then print "-1" (without the quotes) instead.Placing and starting a robot takes no time, however, you must count a move when robot hits a wall. Take a look into samples for further clarification.

The first line contains three integers n, h and w (1 ≤ n, h, w ≤ 500 000) — the length of the pattern, the number of rows and the number of columns, respectively. The second line contains a string of length n — the pattern of n moves. Each character is one of uppercase letters 'U', 'D', 'L' or 'R'.

Print one line with the answer. If a cleaning robot will never stop, print "-1" (without the quotes). Otherwise, print the number of minutes it will take to clean a house modulo 109 + 7.

NoteIn the first sample house is a grid with 10 rows and 2 columns. Starting a robot anywhere in the second column will result in only one move (thus, one minute of cleaning) in which robot will hit a wall — he tried to go right but there is no third column. Starting a robot anywhere in the first column will result in two moves. The total number of minutes is 10·1 + 10·2 = 30.In the second sample a started robot will try to move "RULRULRULR..." For example, for the leftmost cell in the second row robot will make 5 moves before it stops because of hitting an upper wall.

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

immutable int DIRS = 4;
immutable dchar [DIRS] DNAME = ['U', 'L', 'D', 'R'];
immutable int  [DIRS] DROW  = [ -1,   0,  +1,   0];
immutable int  [DIRS] DCOL  = [  0,  -1,   0,  +1];
immutable int MOD = 1_000_000_007;

long solve (int n, int h, int w, int [] d)
{
	long res = 0;
	long row_lo = 0;
	long row_hi = 0;
	long col_lo = 0;
	long col_hi = 0;
	long cur = 0;
	long row = 0;
	long col = 0;

	foreach (c; d)
	{
		row += DROW[c];
		col += DCOL[c];
		cur++;

		while (row_lo > row)
		{
			res = (res + cur * (w - (col_hi - col_lo))) % MOD;
			row_lo--;
			if (row_hi - row_lo >= h)
			{
				return res;
			}
		}

		while (row_hi < row)
		{
			res = (res + cur * (w - (col_hi - col_lo))) % MOD;
			row_hi++;
			if (row_hi - row_lo >= h)
			{
				return res;
			}
		}

		while (col_lo > col)
		{
			res = (res + cur * (h - (row_hi - row_lo))) % MOD;
			col_lo--;
			if (col_hi - col_lo >= w)
			{
				return res;
			}
		}

		while (col_hi < col)
		{
			res = (res + cur * (h - (row_hi - row_lo))) % MOD;
			col_hi++;
			if (col_hi - col_lo >= w)
			{
				return res;
			}
		}
	}

	long [] [] events;
	foreach (int i, c; d)
	{
		row += DROW[c];
		col += DCOL[c];
		cur++;

		while (row_lo > row)
		{
			res = (res + cur * (w - (col_hi - col_lo))) % MOD;
			events ~= [i, c];
			row_lo--;
			if (row_hi - row_lo >= h)
			{
				return res;
			}
		}

		while (row_hi < row)
		{
			res = (res + cur * (w - (col_hi - col_lo))) % MOD;
			events ~= [i, c];
			row_hi++;
			if (row_hi - row_lo >= h)
			{
				return res;
			}
		}

		while (col_lo > col)
		{
			res = (res + cur * (h - (row_hi - row_lo))) % MOD;
			events ~= [i, c];
			col_lo--;
			if (col_hi - col_lo >= w)
			{
				return res;
			}
		}

		while (col_hi < col)
		{
			res = (res + cur * (h - (row_hi - row_lo))) % MOD;
			events ~= [i, c];
			col_hi++;
			if (col_hi - col_lo >= w)
			{
				return res;
			}
		}
	}

	if (events.empty)
	{
		return -1;
	}

	for (long periods = 2; ; periods++)
	{
		foreach (event; events)
		{
			long i = event[0];
			long c = event[1];

			if (c == 0)
			{
				row = row_lo - 1;
			}
			else if (c == 1)
			{
				col = col_lo - 1;
			}
			else if (c == 2)
			{
				row = row_hi + 1;
			}
			else if (c == 3)
			{
				col = col_hi + 1;
			}
			else
			{
				assert (false);
			}

			cur = ((periods % MOD) * d.length + i + 1) % MOD;
			debug {writeln ("at ", cur);}

			while (row_lo > row)
			{
				res = (res + cur *
				    (w - (col_hi - col_lo))) % MOD;
				row_lo--;
				if (row_hi - row_lo >= h)
				{
					return res;
				}
			}

			while (row_hi < row)
			{
				res = (res + cur *
				    (w - (col_hi - col_lo))) % MOD;
				row_hi++;
				if (row_hi - row_lo >= h)
				{
					return res;
				}
			}

			while (col_lo > col)
			{
				res = (res + cur *
				    (h - (row_hi - row_lo))) % MOD;
				col_lo--;
				if (col_hi - col_lo >= w)
				{
					return res;
				}
			}

			while (col_hi < col)
			{
				res = (res + cur *
				    (h - (row_hi - row_lo))) % MOD;
				col_hi++;
				if (col_hi - col_lo >= w)
				{
					return res;
				}
			}
		}
	}
}

void main ()
{
	int n, h, w;
	while (readf (" %s %s %s", &n, &h, &w) > 0)
	{
		readln;
		auto s = readln.strip;
		int [] d;
		foreach (c; s)
		{
			foreach (i, e; DNAME)
			{
				if (c == e)
				{
					d ~= i;
				}
			}
		}
		writeln (solve (n, h, w, d));
	}
}

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

immutable int DIRS = 4;
immutable dchar [DIRS] DNAME = ['U', 'L', 'D', 'R'];
immutable int  [DIRS] DROW  = [ -1,   0,  +1,   0];
immutable int  [DIRS] DCOL  = [  0,  -1,   0,  +1];
immutable int MOD = 1_000_000_007;

long solve (int n, int h, int w, int [] d)
{
	long res = 0;
	long row_lo = 0;
	long row_hi = 0;
	long col_lo = 0;
	long col_hi = 0;
	long cur = 0;
	long row = 0;
	long col = 0;

	foreach (c; d)
	{
		row += DROW[c];
		col += DCOL[c];
		cur++;

		while (row_lo > row)
		{
			res = (res + cur * (w - (col_hi - col_lo))) % MOD;
			row_lo--;
			if (row_hi - row_lo >= h)
			{
				return res;
			}
		}

		while (row_hi < row)
		{
			res = (res + cur * (w - (col_hi - col_lo))) % MOD;
			row_hi++;
			if (row_hi - row_lo >= h)
			{
				return res;
			}
		}

		while (col_lo > col)
		{
			res = (res + cur * (h - (row_hi - row_lo))) % MOD;
			col_lo--;
			if (col_hi - col_lo >= w)
			{
				return res;
			}
		}

		while (col_hi < col)
		{
			res = (res + cur * (h - (row_hi - row_lo))) % MOD;
			col_hi++;
			if (col_hi - col_lo >= w)
			{
				return res;
			}
		}
	}

	long [] [] events;
	foreach (int i, c; d)
	{
		row += DROW[c];
		col += DCOL[c];
		cur++;

		while (row_lo > row)
		{
			res = (res + cur * (w - (col_hi - col_lo))) % MOD;
			events ~= [i, c];
			row_lo--;
			if (row_hi - row_lo >= h)
			{
				return res;
			}
		}

		while (row_hi < row)
		{
			res = (res + cur * (w - (col_hi - col_lo))) % MOD;
			events ~= [i, c];
			row_hi++;
			if (row_hi - row_lo >= h)
			{
				return res;
			}
		}

		while (col_lo > col)
		{
			res = (res + cur * (h - (row_hi - row_lo))) % MOD;
			events ~= [i, c];
			col_lo--;
			if (col_hi - col_lo >= w)
			{
				return res;
			}
		}

		while (col_hi < col)
		{
			res = (res + cur * (h - (row_hi - row_lo))) % MOD;
			events ~= [i, c];
			col_hi++;
			if (col_hi - col_lo >= w)
			{
				return res;
			}
		}
	}

	if (events.empty)
	{
		return -1;
	}

	for (long periods = 2; ; periods++)
	{
		foreach (event; events)
		{
			long i = event[0];
			long c = event[1];

			if (c == 0)
			{
				row = row_lo - 1;
			}
			else if (c == 1)
			{
				col = col_lo - 1;
			}
			else if (c == 2)
			{
				row = row_hi + 1;
			}
			else if (c == 3)
			{
				col = col_hi + 1;
			}
			else
			{
				assert (false);
			}

			cur = ((periods % MOD) * d.length + i + 1) % MOD;

			while (row_lo > row)
			{
				res = (res + cur *
				    (w - (col_hi - col_lo))) % MOD;
				events ~= [i, c];
				row_lo--;
				if (row_hi - row_lo >= h)
				{
					return res;
				}
			}

			while (row_hi < row)
			{
				res = (res + cur *
				    (w - (col_hi - col_lo))) % MOD;
				events ~= [i, c];
				row_hi++;
				if (row_hi - row_lo >= h)
				{
					return res;
				}
			}

			while (col_lo > col)
			{
				res = (res + cur *
				    (h - (row_hi - row_lo))) % MOD;
				events ~= [i, c];
				col_lo--;
				if (col_hi - col_lo >= w)
				{
					return res;
				}
			}

			while (col_hi < col)
			{
				res = (res + cur *
				    (h - (row_hi - row_lo))) % MOD;
				events ~= [i, c];
				col_hi++;
				if (col_hi - col_lo >= w)
				{
					return res;
				}
			}
		}
	}
}

void main ()
{
	int n, h, w;
	while (readf (" %s %s %s", &n, &h, &w) > 0)
	{
		readln;
		auto s = readln.strip;
		int [] d;
		foreach (c; s)
		{
			foreach (i, e; DNAME)
			{
				if (c == e)
				{
					d ~= i;
				}
			}
		}
		writeln (solve (n, h, w, d));
	}
}


You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right.To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100".Determine the minimum number of moves needed to make some table column consist only of numbers 1.

The first line contains two space-separated integers: n (1 ≤ n ≤ 100) — the number of rows in the table and m (1 ≤ m ≤ 104) — the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table. It is guaranteed that the description of the table contains no other characters besides "0" and "1".

Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1.

NoteIn the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s.In the second sample one can't shift the rows to get a column containing only 1s.

import std.algorithm;
import std.c.stdio;
import std.stdio;
import std.conv;
import std.math;

int curc;
bool eof = false;

void sb()
{
    do
    {
        curc = getchar ();
    }
    while (0 <= curc && curc <= 32);
    if (curc == EOF)
    {
        eof = true;
    }
}

char rc ()
{
    sb ();
    return cast (char) curc;
}

int ni ()
{
    sb ();
    int res = 0;
    do
    {
        res = res * 10 + cast (int) (curc - '0');
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

long nl ()
{
    sb ();
    long res = 0;
    do
    {
        res = res * 10 + cast (long) (curc - '0');
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

char[] ns ()
{
    sb ();
    char[] res = [];
    do
    {
        res ~= to!char(curc);
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

void CFBETA142C()
{
    int n = ni(), m = ni();
    char[][] table = new char[][](n,m*3);
    int[][] l = new int[][](n,m*3), r = new int[][](n,m*3);
    int inf=1000000;
    for (int i=0; i<n; ++i)
    {
        auto tmp = ns();
        table[i]=tmp~tmp~tmp;
    }
    for (int i=0; i<n; ++i)
    {
        for (int j=0; j<m*3; ++j)
            if (j==0)
            {
                if (table[i][j]=='0') l[i][j]=inf;
                else l[i][j]=0;
            }
            else
            {
                if (table[i][j]=='1') l[i][j]=0;
                else l[i][j]=min(inf,l[i][j-1]+1);
            }
        for (int j=m*3-1; j>=0; --j)
            if (j==m*3-1)
            {
                if (table[i][j]=='0') r[i][j]=inf;
                else r[i][j]=0;
            }
            else
            {
                if (table[i][j]=='1') r[i][j]=0;
                else r[i][j]=min(inf,r[i][j+1]+1);
            }
    }
    int[][] shift = new int[][](n,m);
    for (int i=0; i<n; ++i)
        for (int j=0; j<m; ++j)
            shift[i][j]=min(l[i][j+m],r[i][j+m]);
    int[] shift_max = new int[m];
    for (int i=0; i<n; ++i)
        for (int j=0; j<m; ++j)
        {
            shift_max[j] += shift[i][j];
            if (shift_max[j]>inf) shift_max[j]=inf;
        }
    int ans = inf;
    for (int j=0; j<m; ++j) ans=min(ans, shift_max[j]);
    writeln(ans==inf?-1:ans);
}

void main()
{
    CFBETA142C();
}

import std.algorithm;
import std.c.stdio;
import std.stdio;
import std.conv;
import std.math;

int curc;
bool eof = false;

void sb()
{
    do
    {
        curc = getchar ();
    }
    while (0 <= curc && curc <= 32);
    if (curc == EOF)
    {
        eof = true;
    }
}

char rc ()
{
    sb ();
    return cast (char) curc;
}

int ni ()
{
    sb ();
    int res = 0;
    do
    {
        res = res * 10 + cast (int) (curc - '0');
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

long nl ()
{
    sb ();
    long res = 0;
    do
    {
        res = res * 10 + cast (long) (curc - '0');
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

char[] ns ()
{
    sb ();
    char[] res = [];
    do
    {
        res ~= to!char(curc);
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

void CFBETA142C()
{
    int n = ni(), m = ni();
    char[][] table = new char[][](n,m*3);
    int[][] l = new int[][](n,m*3), r = new int[][](n,m*3);
    int inf=1000000;
    for (int i=0; i<n; ++i)
    {
        auto tmp = ns();
        table[i]=tmp~tmp~tmp;
    }
    for (int i=0; i<n; ++i)
    {
        for (int j=0; j<m*3; ++j)
            if (j==0)
            {
                if (table[i][j]=='0') l[i][j]=inf;
                else l[i][j]=0;
            }
            else
            {
                if (table[i][j]=='1') l[i][j]=0;
                else l[i][j]=min(inf,l[i][j-1]+1);
            }
        for (int j=m*3-1; j>=0; --j)
            if (j==m*3-1)
            {
                if (table[i][j]=='0') r[i][j]=inf;
                else r[i][j]=0;
            }
            else
            {
                if (table[i][j]=='1') r[i][j]=0;
                else r[i][j]=min(inf,r[i][j+1]+1);
            }
    }
    int[][] shift = new int[][](n,m);
    for (int i=0; i<n; ++i)
        for (int j=0; j<m; ++j)
            shift[i][j]=min(l[i][j+m],r[i][j+m]);
    int[] shift_max = new int[m];
    for (int i=0; i<n; ++i)
        for (int j=0; j<m; ++j)
        {
            shift_max[j] += shift[i][j];
            if (shift_max[j]>inf) shift_max[j]=inf;
        }
    int ans = inf;
    for (int j=0; j<m; ++j) ans=min(ans, shift_max[j]);
    writeln(ans);
}

void main()
{
    CFBETA142C();
}