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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti].length = n;
		foreach (i; 0..n)
			ans[ti][i].length = n;

		if (n % 2 == 0)
		{
			foreach (i; 0..n)
			{
				foreach (j; 0..2)
				{
					auto x = (i/2) * 2 + j;
					ans[ti][i][x] = 1;
				}
			}
		}
		else if (n % 3 == 2 || n % 3 == 0)
		{
			foreach (i; 0..n)
			{
				foreach (j; 0..3)
				{
					auto x = (i/3) * 3 + j;
					if (x >= n) break;
					ans[ti][i][x] = 1;
				}
			}
		}
		else
		{
			foreach (i; 0..n-4)
			{
				foreach (j; 0..3)
				{
					auto x = (i/3) * 3 + j;
					if (x >= n) break;
					ans[ti][i][x] = 1;
				}
			}
			foreach (i; n-4..n)
			{
				foreach (j; 0..2)
				{
					auto x = ((i-(n-4))/2) * 2 + (n-4) + j;
					ans[ti][i][x] = 1;
				}
			}
		}
	}

	foreach (e; ans)
	{
		foreach (i; 0..e.length)
		{
			write(e[i][0]);
			foreach (j; 1..e.length)
			{
				write(" ", e[i][j]);
			}
			writeln;
		}
	}
	stdout.flush;
	debug readln;
}

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

void play(){
    int n;
    n = rd!int;
    auto mat = new ll[][](n, n);
    foreach(i; 0..n){
        mat[i][] = 0;
        mat[i][i] = 1;
        mat[i][(i + 1) % n] = 1;
    }
    foreach(i; 0..n){
        mat[i].each!(a => write(a, " "));
        writeln;
    }
}

int main(){
    long t = 1;
    t = rd;        // Toggle!
    while(t--) play();  // Let's play!
    stdout.flush;
    return 0;
}

/**********It's A Me Mario!**********/
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.numeric, std.math, std.random;
static string[] inp;
T rd(T = long)(){while(!inp.length) inp = readln.chomp.split; string a = inp[0]; inp.popFront; return a.to!T;}
T[] rdarr(T = long)(){ auto r = readln.chomp.split.to!(T[]); return r; }
void show(A...)(A a) { debug{ foreach(t; a){ write(t, "| "); } writeln; } }
alias ll = long;
alias rbt = redBlackTree;
alias tup = Tuple!(long, "x",  long, "y");
T max(T = long)(T a, T b){ return (a > b) ? a : b; }
T min(T = long)(T a, T b){ return (a < b) ? a : b; }

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti].length = n;
		foreach (i; 0..n)
			ans[ti][i].length = n;

		if (n % 2 == 0)
		{
			foreach (i; 0..n)
			{
				foreach (j; 0..2)
				{
					auto x = (i/2) * 2 + j;
					ans[ti][i][x] = 1;
				}
			}
		}
		else
		{
			foreach (i; 0..n)
			{
				foreach (j; 0..3)
				{
					auto x = (i/3) * 3 + j;
					ans[ti][i][x] = 1;
				}
			}
		}
	}

	foreach (e; ans)
	{
		foreach (i; 0..e.length)
		{
			write(e[i][0]);
			foreach (j; 1..e.length)
			{
				write(" ", e[i][j]);
			}
			writeln;
		}
	}
	stdout.flush;
	debug readln;
}

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

string FMT_F = "%.10f";

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

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

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

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

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

		ans[ti].length = n;
		foreach (i; 0..n)
			ans[ti][i].length = n;

		if (n % 2 == 0)
		{
			foreach (i; 0..n)
			{
				foreach (j; 0..2)
				{
					auto x = (i/2) * 2 + j;
					ans[ti][i][x] = 1;
				}
			}
		}
		else
		{
			foreach (i; 0..n)
			{
				foreach (j; 0..3)
				{
					auto x = (i/3) * 3 + j;
					if (x >= n) break;
					ans[ti][i][x] = 1;
				}
			}
		}
	}

	foreach (e; ans)
	{
		foreach (i; 0..e.length)
		{
			write(e[i][0]);
			foreach (j; 1..e.length)
			{
				write(" ", e[i][j]);
			}
			writeln;
		}
	}
	stdout.flush;
	debug readln;
}


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

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		int [] [] a;
		a ~= readln.splitter.map !(to !(int)).array;
		foreach (i; 1..n)
		{
			auto b = new int [n - i];
			foreach (j; 0..n - i)
			{
				b[j] = a[i - 1][j] ^ a[i - 1][j + 1];
			}
			a ~= b;
		}
		foreach (i; 1..n + 1)
		{
			foreach (j; 0..n - i)
			{
				a[i][j] = max (a[i][j],
				    a[i - 1][j], a[i - 1][j + 1]);
			}
		}

		int q;
		readf (" %s", &q);
		foreach (v; 0..q)
		{
			int l, r;
			readf (" %s %s", &l, &r);
			l -= 1;
			r -= 1;
			writeln (a[r - l][l]);
		}
	}
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!long).array;

    auto B = new long[][](N, N);
    foreach (i; 0..N) B[i][i] = A[i];

    foreach (len; 2..N+1) {
        foreach (l; 0..N-len+1) {
            int r = l + len - 1;
            B[l][r] = B[l+1][r] ^ B[l][r-1];
        }
    }

    auto dp = new long[][](N, N);
    foreach (i; 0..N) dp[i][i] = A[i];

    foreach (len; 2..N+1) {
        foreach (l; 0..N-len+1) {
            int r = l + len - 1;
            dp[l][r] = B[l][r];
            dp[l][r] = max(dp[l][r], dp[l+1][r]);
            dp[l][r] = max(dp[l][r], dp[l][r-1]);
        }
    }

    auto Q = readln.chomp.to!int;
    while (Q--) {
        auto s = readln.split.map!(to!int);
        auto a = s[0] - 1;
        auto b = s[1] - 1;
        dp[a][b].writeln;
    }
}

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

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!int).array;

    auto dp = new int[][](N, N);
    foreach (i; 0..N) dp[i][i] = A[i];

    foreach (len; 2..N+1) {
        foreach (l; 0..N-len+1) {
            int r = l + len - 1;
            if (len == 2 || len % 2 == 1) {
                dp[l][r] = A[l] ^ A[r];
            } else {
                dp[l][r] = A[l] ^ A[l+1] ^ A[r-1] ^ A[r];
            }
            dp[l][r] = max(dp[l][r], dp[l+1][r]);
            dp[l][r] = max(dp[l][r], dp[l][r-1]);
        }
    }

    auto Q = readln.chomp.to!int;
    while (Q--) {
        auto s = readln.split.map!(to!int);
        auto a = s[0] - 1;
        auto b = s[1] - 1;
        dp[a][b].writeln;
    }
}


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

void main()
{
    int T; get(T); while (T--) {
        int N; get(N);
        int[] AA; get(AA);
        int[3] cs;
        foreach (a; AA) ++cs[a % 3];
        int r;
        foreach (i; 0..4) {
            auto d = max(0, cs[i % 3] - N / 3);
            cs[i % 3] -= d;
            r += d;
            cs[(i + 1) % 3] += d;
        }
        writeln(r);
    }
}

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 int[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA!int;

		auto cnt = new int[](3);
		foreach (i; 0..n)
		{
			++cnt[a[i]%3];
		}
		debug writeln("cnt:", cnt);

		auto y = n/3;
		bool done;
		while (!done)
		{
			done = true;
			foreach (i; 0..3)
			{
				if (cnt[i] > y)
				{
					done = false;
					auto x = cnt[i] - y;
					cnt[i] = y;
					ans[ti] += x;
					cnt[(i+1)%3] += x;
				}
			}
			debug writeln("cnt:", cnt);
		}
	}

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

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

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto c = new int [3];
		foreach (ref x; a)
		{
			c[x % 3] += 1;
		}
		int res = 0;
		foreach (j; 0..2)
		{
			foreach (i; 0..3)
			{
				while (c[i] > n / 3)
				{
					c[i] -= 1;
					c[(i + 1) % 3] += 1;
					res += 1;
				}
			}
		}
		writeln (res);
	}
}


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

int[] transform(long num)
{
    int[] res;
    while (num)
    {
        res ~= (num % 10);
        num /= 10;
    }
    reverse(res);
    return res;
}

int saiki(int idx, int cnt, int flag, int[][][] dp, int[] d)
{
    if (dp[idx][cnt][flag] != -1) return dp[idx][cnt][flag];
    if (idx == cast(int)d.length)
    {
        dp[idx][cnt][flag] = 1;
        return 1;
    }
    dp[idx][cnt][flag] = 0;
    auto bound = flag == 0 ? d[idx] : 9;
    foreach (i; 0 .. bound + 1)
    {
        if (i == 0 || cnt < 3)
        {
            auto nextFlag = i < d[idx] ? 1 : flag;
            auto ret = saiki(idx + 1, cnt + (i != 0), nextFlag, dp, d);
            dp[idx][cnt][flag] += ret;
        }
    }
    return dp[idx][cnt][flag];
}

void solve(long left, long right)
{
    auto dl = transform(left - 1);
    auto dr = transform(right);
    auto m = max(dl.length, dr.length);
    auto dp = new int[][][](m + 1, 4, 2);
    foreach (i; 0 .. m + 1)
    {
        foreach (j; 0 .. 4) fill(dp[i][j], -1);
    }
    auto cl = saiki(0, 0, 0, dp, dl);
    foreach (i; 0 .. m + 1)
    {
        foreach (j; 0 .. 4) fill(dp[i][j], -1);
    }
    auto cr = saiki(0, 0, 0, dp, dr);
    writeln(cr - cl);
}

int main(string[] drgs)
{
    auto T = to!int(readln.strip);
    foreach (i; 0 .. T)
    {
        auto p = map!(to!long)(readln.strip.split(' '));
        solve(p[0], p[1]);
    }
    return 0;
}

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

  int t;
  rd(t);
  while (t--) {
    auto args = readln.split.to!(long[]);
    long solve(long nn) {
      auto n = digit(nn);
      auto dp = new long[][][](n.length + 1, 2, 20);
      dp[0][0][0] = 1;
      foreach (i; 0 .. n.length) {
        foreach (l; 0 .. 2) {
          foreach (c; 0 .. 19) {
            auto d = l ? 9 : n[i];
            for (int digit = 0; digit <= d; digit++) {
              auto less = l || (digit < d);
              auto count = c + (digit > 0);
              dp[i + 1][less][count] += dp[i][l][c];
            }
          }
        }
      }
      long ret = 0;
      foreach (l; 0 .. 2) {
        for (int c = 0; c <= 3; c++) {
          ret += dp[n.length][l][c];
        }
      }
      return ret;
    }

    writeln(solve(args[1]) - solve(args[0] - 1));
  }
}

int[] digit(long x) {
  int[] ret;
  do {
    ret = x % 10 ~ ret;
    x /= 10;
  }
  while (x);
  return ret;
}

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.array;

  int t;
  rd(t);
  while (t--) {
    auto args = readln.split.to!(long[]);
    long solve(long s) {
      int[] n;
      do {
        n = s % 10 ~ n;
        s /= 10;
      }
      while (s);
      auto memo = new long[][][](n.length + 1, 2, n.length + 1);
      foreach (i; 0 .. (n.length + 1))
        foreach (j; 0 .. 2)
          foreach (k; 0 .. (n.length + 1))
            memo[i][j][k] = -1;
      long f(size_t i, bool less, int count) {
        if (i == n.length) {
          return count <= 3;
        } else {
          if (memo[i][less][count] >= 0)
            return memo[i][less][count];
          long ret = 0;
          auto digit = less ? 9 : n[i];
          for (int d = 0; d <= digit; d++) {
            auto l = less || (d < digit);
            auto c = count + (d > 0);
            ret += f(i + 1, l, c);
          }
          return memo[i][less][count] = ret;
        }
      }

      return f(0, 0, 0);
    }

    writeln(solve(args[1]) - solve(args[0] - 1));
  }
}

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

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

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

    while (t--) {
        long le, r;
        readf("%s %s", &le, &r);
        readln;

        long go(string x) {
            int xlen = x.length.to!int;

            long getAns(bool alwaysSmaller, int pos, int nonZeroLeft, int allLeft) {
                if (pos >= xlen) { return 1; }

                if (alwaysSmaller) {
                    if (pos == 0) { //nonZeroLeft  and allLeft always > 0
                        return 9 * getAns(true, pos+1, nonZeroLeft-1, allLeft-1);
                    }

                    long ret = 0;
                    foreach (nrs; 0 .. nonZeroLeft + 1) {
                        if (nrs > allLeft) { continue; }

                        if (nrs == 0) { ret += 1; }
                        if (nrs == 1) { ret += 9 * allLeft; }
                        if (nrs == 2) { ret += 9 ^^ 2 * allLeft * (allLeft-1) / 2; }
                    }

                    return ret;
                }

                long ret = 0;
                int curDig = x[pos] - '0';

                if (pos > 0) { ret += getAns(curDig > 0, pos+1, nonZeroLeft, allLeft-1); }

                if (nonZeroLeft > 0 && curDig > 0) {
                    if (curDig > 1) {
                        int start = 1;
                        int end = x[pos] - '0' - 1;
                        int span = end - start + 1;
                        ret += span * getAns(true, pos+1, nonZeroLeft-1, allLeft-1);
                    }

                    ret += getAns(false, pos+1, nonZeroLeft-1, allLeft-1);
                }

                return ret;
            }

            long ans = getAns(false, 0, 3, xlen);
            foreach (digs; 1 .. xlen) { ans += getAns(true, 0, 3, digs); }

            return ans;
        }

        auto ans = go(r.to!string) - go((le-1).to!string);
        ans.writeln;
    }
}

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

  int t;
  rd(t);
  while (t--) {
    auto args = readln.split.to!(long[]);
    long solve(long nn) {
      auto n = digit(nn);
      auto dp = new long[][][](n.length + 1, 2, 4);
      dp[0][0][0] = 1;
      foreach (i; 0 .. n.length) {
        foreach (l; 0 .. 2) {
          foreach (c; 0 .. 4) {
            auto d = l ? 9 : n[i];
            for (int digit = 0; digit <= d; digit++) {
              auto less = l || (digit < d);
              auto count = max(3, c + (digit > 0));
              dp[i + 1][less][count] += dp[i][l][c];
            }
          }
        }
      }
      long ret = 0;
      foreach (l; 0 .. 2) {
        for (int c = 0; c <= 3; c++) {
          ret += dp[n.length][l][c];
        }
      }
      return ret;
    }

    writeln(solve(args[1]) - solve(args[0] - 1));
  }
}

int[] digit(long x) {
  int[] ret;
  do {
    ret = x % 10 ~ ret;
    x /= 10;
  }
  while (x);
  return ret;
}

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

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


import std.stdio,std.conv;
double[100000] pp;
double ans;
long n,p,l,r;
void main()
{
	scanf(" %d %d",&n,&p);
	for(int i=0;i<n;++i)
	{
		scanf(" %d %d",&l,&r);
		pp[i]=(to!double((r/p-(l-1)/p)))/(r-l+1);
	}
	int t=to!int(n-1);
	ans=(pp[0]+pp[t]-pp[0]*pp[t])*1000;
	for(int i=1;i<n;++i)
	{
		ans+=(pp[i]+pp[i-1]-pp[i]*pp[i-1])*1000;
	}
	writef("%.10f",ans*2);
}

import std.stdio;

void main() {
  int n, p;
  readf(" %s %s", &n, &p);
  auto l = new int[n];
  auto r = new int[n];
  foreach (i; 0..n) {
    readf(" %s %s", &l[i], &r[i]);
  }
  real exp = 0;
  foreach (i; 0..n) {
    int j = (i + 1) % n;
    int ci = r[i] / p - (l[i] - 1) / p;
    int cj = r[j] / p - (l[j] - 1) / p;
    exp += 1.0 * cj / (r[j] - l[j] + 1);
    exp += 1.0 * ci / (r[i] - l[i] + 1);
    exp -= 1.0 * ci * cj / (r[i] - l[i] + 1) / (r[j] - l[j] + 1);
  }
  writeln(exp * 2000);
}

import std.stdio;

void main() {
  int n, p;
  readf(" %s %s", &n, &p);
  auto l = new int[n];
  auto r = new int[n];
  foreach (i; 0..n) {
    readf(" %s %s", &l[i], &r[i]);
  }
  real exp = 0;
  foreach (i; 0..n) {
    int j = (i + 1) % n;
    real denom = 1.0 * (r[i] - l[i] + 1) * (r[j] - l[j] + 1);
    int ci = r[i] / p - (l[i] - 1) / p;
    int cj = r[j] / p - (l[j] - 1) / p;
    exp += cj * (r[i] - l[i] + 1) / denom;
    exp += ci * (r[j] - l[j] + 1) / denom;
    exp -= ci * cj / denom;
  }
  writeln(exp * 2000);
}

import std.stdio,std.conv;
double[100000] pp;
double ans;
long n,p,l,r;
void main()
{
	scanf(" %d %d",&n,&p);
	for(int i=0;i<n;++i)
	{
		scanf(" %d %d",&l,&r);
		pp[i]=(to!double((r/p-(l-1)/p)))/(r-l+1);
	}
	int t=to!int(n-1);
	ans=(pp[0]+pp[t]-pp[0]*pp[t])*1000;
	for(int i=1;i<n;++i)
	{
		ans+=(pp[i]+pp[i-1]-pp[i]*pp[i-1])*1000;
	}
	writeln(ans*2);
}


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

long max(long a, long b)
{
	if (a > b) return a;
	return b;
}

int main(string[] argv)
{
	long n;
	long nums;
	long[long] cnt;
	scanf("%d", &n);
	foreach (long i; 0..n)
	{
		scanf("%d", &nums);
		cnt[nums]++;
	}
	long maxk = 0;
	foreach (long k; cnt.byKey)
	{
		if (k > maxk) maxk = k;
	}

	long[] dp; dp.length = cast(uint)(maxk + 5);
	dp[0] = 0;
	dp[1] = (1 in cnt ? cnt[1] : 0);
	foreach (uint k; 2..dp.length)
	{
		dp[k] = max(dp[k-1], dp[k-2] + cast(long)k * (k in cnt ? cnt[k] : cast(long)0));
	}
	write(dp[$-1]);
	return 0;
}

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

immutable int MAX_K = 100_005;

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

		auto f = new long [MAX_K];
		foreach_reverse (i; 0..MAX_K - 2)
		{
			f[i] = max (f[i + 1], f[i + 2] + (i + 1) * b[i + 2]);
		}

		writeln (f[0]);
	}
}

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

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

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

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

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

immutable LIM = 100_005;

int N;
int[] A;

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

		long[] ps = new long[LIM];
		foreach (i; 0 .. N) {
			ps[A[i]] += A[i];
		}

		long[] dp = new long[LIM];
		foreach (x; 0 .. LIM) {
			dp[x] = ps[x];
			if (x - 1 >= 0) {
				chmax(dp[x], dp[x - 1]);
			}
			if (x - 2 >= 0) {
				chmax(dp[x], dp[x - 2] + ps[x]);
			}
		}

		writeln(dp[LIM - 1]);

	}
	} catch (EOFException) {}
}

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

alias type = single;
struct TestCase
{
  mixin prettyPrinting;

  long n;
  @Dim("n") long[] a;

  void solve(long tc = -1)
  {
    long[100000 + 1] aps = 0;
    foreach(ai; a)
      aps.at(ai)++;
    long[100000 + 1] dp = 0;
    dp[0] = 0;
    foreach(i; 1 .. dp.length)
      {
        if (i >= 2)
          dp[i] = max(aps.at(i) * cast(long)i
                      + dp[i - 2],
                      dp[i - 1]);
        else
          dp[i] = max(aps.at(i) * cast(long)i, dp[i - 1]);
      }
    writeln(dp[100000]);
  }
}

struct Interval
{
  long l, h;

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

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

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

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

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

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

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

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

DList!string _words;

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

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

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

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

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

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

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

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

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

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

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

    }
}

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

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

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

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

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

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

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

void main()
{
  type;
}

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

alias number = long;

void main() {
	int n;
	readf(" %s ", &n);
	assert(1 <= n && n <= 10^^5);
	auto a = new number[n];
	foreach (ref ai; a)
		readf(" %s ", &ai);
	number prev_max, cur_max;
	number last_used = -1;
	foreach (ref ri; a.sort.group) {
		number new_max;
		auto value = ri[0] * ri[1];
		if (last_used == ri[0] - 1) {
			if (cur_max >= prev_max + value) {
				new_max = cur_max;
			} else {
				last_used = ri[0];
				new_max = prev_max + value;
			}
		} else {
			last_used = ri[0];
			new_max = cur_max + value;
		}
		prev_max = cur_max;
		cur_max = new_max;
	}
	writeln(cur_max);
}

import std.algorithm;

static immutable MAXA = 100000 + 1;

ulong solve(const uint[] as) {
	auto sums = new ulong[](MAXA);
	auto dp = new ulong[][](MAXA, 2);

	foreach (a; as) {
		sums[a] += a;
	}

	foreach (i; 1..MAXA) {
		dp[i][0] = max(dp[i - 1][0], dp[i - 1][1]);
		dp[i][1] = dp[i - 1][0] + sums[i];
	}

	return max(dp[$ - 1][0], dp[$ - 1][1]);
}

unittest {
	{
		uint[] as = [1, 2];
		assert(2 == solve(as));
	}

	{
		uint[] as = [1, 2, 3];
		assert(4 == solve(as));
	}

	{
		uint[] as = [1, 2, 1, 3, 2, 2, 2, 2, 3];
		assert(10 == solve(as));
	}

	{
		uint[] as = [2, 3, 2, 2, 2, 2, 3];
		assert(10 == solve(as));
	}

	{
		uint[] as = [2, 3, 2, 2, 2, 2, 3, 3, 3];
		assert(12 == solve(as));
	}

	{
		uint[] as = [666];
		assert(666 == solve(as));
	}

	{
		uint[] as = [1];
		assert(1 == solve(as));
	}

	{
		uint[] as = [100000];
		assert(100000 == solve(as));
	}

	{
		uint[] as = [99999, 100000];
		assert(100000 == solve(as));
	}

	{
		uint[] as = [99999, 99999, 100000];
		assert(199998 == solve(as));
	}
}

int main(string[] argv) {
	import std.stdio;
	uint n = 0;
	readf(" %s", &n);
	auto as = new uint[](n);
	foreach (i; 0..n) {
		readf(" %s", &(as[i]));
	}
	writeln(solve(as));
    return 0;
}

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

long max(long a, long b)
{
	if (a > b) return a;
	return b;
}

int main(string[] argv)
{
	long n;
	long nums;
	long[long] cnt;
	scanf("%d", &n);
	foreach (long i; 0..n)
	{
		scanf("%d", &nums);
		cnt[nums]++;
	}
	long maxk = 0;
	foreach (long k; cnt.byKey)
	{
		if (k > maxk) maxk = k;
	}

	long[] dp; dp.length = 100005;
	dp[0] = 0;
	dp[1] = (1 in cnt ? cnt[1] : 0);
	foreach (uint k; 2..dp.length)
	{
		dp[k] = max(dp[k-1], dp[k-2] + cast(long)k * (k in cnt ? cnt[k] : cast(long)0));
	}
	write(dp[$-1]);
	return 0;
}

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

int main(string[] argv)
{
	int n;
	int[] nums;
	int[int] cnt;
	scanf("%d", &n); nums.length = n;
	foreach (int i; 0..n)
	{
		scanf("%d", &nums[i]);
		cnt[nums[i]]++;
	}
	foreach (int k; cnt.byKey)
	{
		cnt[k] *= k;
	}
	int[] keys = cnt.keys;
	keys.sort!((x, y) => cnt[x] > cnt[y]);
	int sum1 = 0;
	int sum2 = 0;
	int pk1 = -2;
	int pk2 = -2;
	foreach (int i; 0..keys.length)
	{
		if (keys[i] + 1 != pk1 && keys[i] - 1 != pk1)
		{
			pk1 = keys[i];
			sum1 += cnt[keys[i]];
		} else
		if (keys[i] +1 != pk2 && keys[i] - 1 != pk2)
		{
			pk2 = keys[i];
			sum2 += cnt[keys[i]];
		}
	}
	write(sum1 > sum2 ? sum1 : sum2);
	return 0;
}

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

long max(long a, long b)
{
	if (a > b) return a;
	return b;
}

int main(string[] argv)
{
	int n;
	int[] nums;
	int[int] cnt;
	scanf("%d", &n); nums.length = n;
	foreach (int i; 0..n)
	{
		scanf("%d", &nums[i]);
		cnt[nums[i]]++;
	}
	int maxk = 0;
	foreach (int k; cnt.byKey)
	{
		if (k > maxk) maxk = k;
	}

	long[] dp; dp.length = maxk+2;
	dp[0] = 0;
	dp[1] = (1 in cnt ? cnt[1] : 0);
	foreach (int k; 2..(maxk+2))
	{
		dp[k] = max(dp[k-1], dp[k-2] + k * (k in cnt ? cnt[k] : 0));
	}
	write(dp[maxk+1]);
	return 0;
}

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

int max(int a, int b)
{
	if (a > b) return a;
	return b;
}

int main(string[] argv)
{
	int n;
	int[] nums;
	int[int] cnt;
	scanf("%d", &n); nums.length = n;
	foreach (int i; 0..n)
	{
		scanf("%d", &nums[i]);
		cnt[nums[i]]++;
	}
	int maxk = 0;
	foreach (int k; cnt.byKey)
	{
		cnt[k] *= k;
		if (k > maxk) maxk = k;
	}

	int[] dp; dp.length = maxk+2;
	dp[0] = 0;
	dp[1] = (1 in cnt ? cnt[1] : 0);
	foreach (int k; 2..(maxk+2))
	{
		dp[k] = max(dp[k-1], dp[k-2] + (k in cnt ? cnt[k] : 0));
	}
	write(dp[maxk+1]);
	return 0;
}

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

int main(string[] argv)
{
	int n;
	int[] nums;
	int[int] cnt;
	scanf("%d", &n); nums.length = n;
	foreach (int i; 0..n)
	{
		scanf("%d", &nums[i]);
		cnt[nums[i]]++;
	}
	foreach (int k; cnt.byKey)
	{
		cnt[k] *= k;
	}
	int[] keys = cnt.keys;
	keys.sort!((x, y) => cnt[x] > cnt[y]);
	int sum1 = 0;
	int sum2 = 0;
	bool[int] sumk1;
	bool[int] sumk2;
	foreach (int i; 0..keys.length)
	{
		if (!(keys[i] in sumk1))
		{
			sum1 += cnt[keys[i]];
			sumk1[keys[i]] = true;
			sumk1[keys[i]-1] = true;
			sumk1[keys[i]+1] = true;
		} else
		if (!(keys[i] in sumk2))
		{
			sum2 += cnt[keys[i]];
			sumk2[keys[i]] = true;
			sumk2[keys[i]-1] = true;
			sumk2[keys[i]+1] = true;
		}
	}
	write(sum1 > sum2 ? sum1 : sum2);
	return 0;
}

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

int main(string[] argv)
{
	int n;
	int[] nums;
	int[int] cnt;
	scanf("%d", &n); nums.length = n;
	foreach (int i; 0..n)
	{
		scanf("%d", &nums[i]);
		cnt[nums[i]]++;
	}
	int sum_1 = 0;
	int sum_2 = 0;
	foreach (int i; 0..(n/2 + 1))
	{
		int idx1 = 2*i;
		int idx2 = 2*i+1;
		sum_1 += idx1 * (idx1 in cnt ? cnt[idx1] : 0);
		sum_2 += idx2 * (idx2 in cnt ? cnt[idx2] : 0);
	}
	write(sum_1 > sum_2 ? sum_1 : sum_2);
	return 0;
}

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

long max(long a, long b)
{
	if (a > b) return a;
	return b;
}

int main(string[] argv)
{
	int n;
	int[] nums;
	int[int] cnt;
	scanf("%d", &n); nums.length = n;
	foreach (int i; 0..n)
	{
		scanf("%d", &nums[i]);
		cnt[nums[i]]++;
	}
	int maxk = 0;
	foreach (int k; cnt.byKey)
	{
		cnt[k] *= k;
		if (k > maxk) maxk = k;
	}

	long[] dp; dp.length = maxk+2;
	dp[0] = 0;
	dp[1] = (1 in cnt ? cnt[1] : 0);
	foreach (int k; 2..(maxk+2))
	{
		dp[k] = max(dp[k-1], dp[k-2] + (k in cnt ? cnt[k] : 0));
	}
	write(dp[maxk+1]);
	return 0;
}

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

int main(string[] argv)
{
	int n;
	int[] nums;
	int[int] cnt;
	scanf("%d", &n); nums.length = n;
	foreach (int i; 0..n)
	{
		scanf("%d", &nums[i]);
		cnt[nums[i]]++;
	}
	int points = 0;
	bool canPick = true;
	while (canPick)
	{
		int max = int.min;
		int p = -1;
		foreach (int k; cnt.byKey)
		{
			int lm = (k-1) in cnt ? (k-1) * cnt[k-1] : 0;
			lm += (k+1) in cnt ? (k+1) * cnt[k+1] : 0;
			lm = k * cnt[k] - lm;
			if (lm > max)
			{
				max = lm;
				p = k;
			}
		}

		points += p; cnt[p]--;
		cnt.remove(p-1);
		cnt.remove(p+1);
		canPick = cnt[p] != 0;
		if (!canPick)
		{
			cnt.remove(p);
			foreach (int k; cnt.byKey)
				if (cnt[k] != 0)
				{
					canPick = true;
					break;
				}
		}
	}
	write(points);
	return 0;
}

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

void main() {
	int n;
	readf(" %s ", &n);
	assert(1 <= n && n <= 10^^5);
	auto a = new int[n];
	foreach (ref ai; a)
		readf(" %s ", &ai);
	int prev_max, cur_max;
	int last_used = -1;
	foreach (ref ri; a.sort.group) {
		int new_max;
		int value = ri[0] * ri[1];
		if (last_used == ri[0] - 1) {
			if (cur_max >= prev_max + value) {
				new_max = cur_max;
			} else {
				last_used = ri[0];
				new_max = prev_max + value;
			}
		} else {
			last_used = ri[0];
			new_max = cur_max + value;
		}
		prev_max = cur_max;
		cur_max = new_max;
	}
	writeln(cur_max);
}


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, core.checkedint;

bool check(long[] a, long div)
{
  bool prev = ((a[0] % div) != 0);
  foreach (x ; a[1 .. $]) {
    bool cur = ((x % div) != 0);
    if (cur == prev)
      return false;
    prev = cur;
  }
  return true;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!long).array;
    long[] e, o;
    foreach (i ; 0 .. n) {
      if (i % 2 == 0)
        e ~= a[i];
      else
        o ~= a[i];
    }

    long gcdo = o[0];
    foreach (x ; o[1 .. $])
      gcdo = gcd(gcdo, x);
    long gcde = e[0];
    foreach (x ; e[1 .. $])
      gcde = gcd(gcde, x);

    if (check(a, gcdo)) {
      writeln(gcdo);
    } else if (check(a, gcde)) {
      writeln(gcde);
    } else {
      writeln(0);
    }
  }
}

immutable multi = true;

void solve(int tc)
{
  auto n = readInt!int;
  auto a = ma(n, readInt!long);

  long[] even, odd;
  foreach(i; 0 .. n)
    {
      if (i%2)
	{
	  odd ~= a[i];
	}
      else
	{
	  even ~= a[i];
	}
    }
  auto egcd = even.fold!gcd,
    ogcd = odd.fold!gcd;
  if (odd.all!(ai => ai % egcd != 0)) return writeln(egcd);
  if (even.all!(ai => ai % ogcd != 0)) return writeln(ogcd);
  return writeln(0);
}

// main {{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
// }}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

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

void popChar()
{
	import core.stdc.stdio;
	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;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}

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

void solve(){
    auto n = scan;
    auto arr = scanArray;
    long gcd1 = arr[0];
    for(int i = 2; i < n; i += 2){
        gcd1 = gcd(gcd1, arr[i]);
    }
    long gcd2 = arr[1];
    for(int i = 3; i < n; i += 2){
        gcd2 = gcd(gcd2, arr[i]);
    }
    show(gcd1, gcd2);

    bool f = 1;
    for(int i = 1; i < n; i += 2){
        if(arr[i] % gcd1 == 0){
            f = 0;
            break;
        }
    }
    if(f){
        writeln(gcd1);
        return;
    }

    f = 1;
    for(int i = 0; i < n; i += 2){
        if(arr[i] % gcd2 == 0){
            f = 0;
            break;
        }
    }
    if(f){
        writeln(gcd2);
        return;
    }

    writeln(0);
}

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

/**************    *****    That's All Folks!    *****    **************/
import std.stdio, std.range, std.conv, std.typecons, std.algorithm, std.container, std.math, std.numeric;
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.algorithm, std.array, std.container, std.conv, std.math, std.numeric, std.random, std.range, std.stdio, std.string, std.typecons, core.bitop;

bool check(long[] a, long div)
{
  bool prev = ((a[0] % div) != 0);
  foreach (x ; a[1 .. $]) {
    bool cur = ((x % div) != 0);
    if (cur == prev)
      return false;
    prev = cur;
  }
  return true;
}

// From: https://rosettacode.org/wiki/Least_common_multiple#D
T lcm(T)(T m, T n) pure nothrow {
    if (m == 0) return m;
    if (n == 0) return n;
    return abs((m * n) / gcd(m, n));
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!long).array;
    long[] b;
    foreach (i ; 1 .. n) {
      long x = a[i], y = a[i - 1];
      if (x > y)
        swap(x, y);
      if (y % x == 0)
        b ~= y / x;
      b ~= x;
      b ~= y;
    }

    long ans = 0;
    foreach (div ; b) {
      if (check(a, div)) {
        ans = div;
        break;
      }
    }
    writeln(ans);
  }
}

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;

bool check(long[] a, long div)
{
  bool prev = ((a[0] % div) != 0);
  foreach (x ; a[1 .. $]) {
    bool cur = ((x % div) != 0);
    if (cur == prev)
      return false;
    prev = cur;
  }
  return true;
}

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    long n;
    readf!" %d "(n);
    auto a = readln.splitter.map!(to!long).array;
    long ans = 0;
    foreach (div ; a) {
      if (check(a, div)) {
        ans = div;
        break;
      }
    }
    writeln(ans);
  }
}

immutable multi = true;

void solve(int tc)
{
  auto n = readInt!int;
  auto a = ma(n, readInt!int);

  int[] even, odd;
  foreach(i; 0 .. n)
    {
      if (i%2)
	{
	  odd ~= a[i];
	}
      else
	{
	  even ~= a[i];
	}
    }
  auto egcd = even.fold!gcd,
    ogcd = odd.fold!gcd;
  if (odd.all!(ai => ai % egcd != 0)) return writeln(egcd);
  if (even.all!(ai => ai % ogcd != 0)) return writeln(ogcd);
  return writeln(0);
}

// main {{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
// }}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

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

void popChar()
{
	import core.stdc.stdio;
	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;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}


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

int[] removeminmax(int[] a, int min_x, int max_x)
{
  auto l = a.countUntil!(x => (x == min_x || x == max_x));
  a = a.dup.reverse;
  auto r = a.countUntil!(x => (x == min_x || x == max_x));
  if (l < r) {
    a.reverse;
    return a[l + 1 .. $];
  } else {
    return a[r + 1 .. $];
  }
}

void main()
{
  int t;
  readf!" %d "(t);
  while (t--) {
    int n;
    readf!" %d "(n);
    auto a = readln.strip.split.map!(to!int).array;
    int min_x = a.minElement;
    int max_x = a.maxElement;
    int[] step1 = removeminmax(a, min_x, max_x);
    int[] step2 = removeminmax(step1, min_x, max_x);
    writeln(a.length - step2.length);
  }
}

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

void main() {
    foreach(t; 0 .. to!int(readln.strip)) {
        int n = to!int(readln.strip);
        auto ar = readln.strip.split.map!(to!int);
        int mn = ar.countUntil(1), mx = ar.countUntil(n);
        if(mn > mx) swap(mn, mx);
        writeln(min(n-mn, mx+1, n-mx+mn+1));
    }
}

// Vicfred
// https://codeforces.com/contest/1538/problem/A
//
import std.algorithm;
import std.array;
import std.conv;
import std.stdio;
import std.string;

int abs(int x) {
    return x > 0 ? x : -x;
}

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

while(t--) {
    int n = readln.chomp.to!int;
    int[] a = readln.split.map!(to!int).array;

    int maxima = a.maxElement;
    int minima = a.minElement;

    int left = 0;
    int right;

    for(int i = 0; i < n; ++i) {
        left += 1;
        if(a[i] == maxima || a[i] == minima) {
            break;
        }
    }

    for(int i = n - 1; i >= 0; --i) {
        right += 1;
        if(a[i] == maxima || a[i] == minima) {
            break;
        }
    }

    //left.writeln;
    //right.writeln;

    int between = abs(left - n + right - 1);
    //between.writeln;
    int[] ans = [left, right, between];
    ans.sort;
    //ans.writeln;
    (ans[0] + ans[1]).writeln;
}
}


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

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

    Tuple!(int, int)[][] vals;
    foreach (_; 0 .. 2) vals ~= readln.chomp.split.map!(to!int).enumerate.map!(t => tuple(cast(int)t[0], t[1])).array;

    debug { vals.writeln; }

    auto ans = new int[][] (n, m);

    foreach_reverse (b; 0 .. 31) {
        auto cur = 1 << b;

        auto f = (Tuple!(int, int)[] arr) => arr.filter!(t => (t[1] & cur) > 0).map!(t => t[0]).array;
        auto nrs = vals.map!f.array;

        debug { if (b < 4) writeln(cur, ' ', nrs[0], ' ', nrs[1]); }

        if (nrs[0].length % 2 != nrs[1].length % 2) {
            writeln("NO");
            return;
        }

        if (nrs[0].length % 2 == 0) { // both even from above
            if (nrs[0].empty) foreach (j; nrs[1]) ans[0][j] ^= cur;
            else if (nrs[1].empty) foreach (i; nrs[0]) ans[i][0] ^= cur;
            else {
                while (nrs[0].length < nrs[1].length) nrs[0] ~= nrs[0].back;
                while (nrs[1].length < nrs[0].length) nrs[1] ~= nrs[1].back;
                foreach (i, j; lockstep(nrs[0], nrs[1])) ans[i][j] ^= cur;
            }
        } else { // both odd
            foreach (i; nrs[0]) {
                foreach (j; nrs[1]) {
                    ans[i][j] ^= cur;
                }
            }
        }
    }

    writeln("YES");
    ans.each!(arr => arr.writefln!("%(%s %)"));
}

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

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

  auto ax=a.reduce!((r, e)=>(r^e)),
       bx=b.reduce!((r, e)=>(r^e));
  if(ax!=bx){writeln("NO"); return;}
  writeln("YES");
  write(a[0]^b[0]^bx, " ");
  writefln("%(%s %)", b[1..$]);
  foreach(i; 1..n){
    write(a[i], " ");
    auto zero=new int[](m-1);
    writefln("%(%s %)", zero);
  }
}

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

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

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto A = readln.split.map!(to!long).array;
    auto B = readln.split.map!(to!long).array;

    long a = 0;
    long b = 0;

    foreach (i; 0..N) a ^= A[i];
    foreach (i; 0..M) b ^= B[i];

    if (a != b) {
        writeln("NO");
        return;
    }

    a = 0;
    b = 0;
    auto ans = new long[][](N, M);
    foreach (i; 0..N-1) ans[i][M-1] = A[i], a ^= A[i];
    foreach (j; 0..M-1) ans[N-1][j] = B[j], b ^= B[j];
    ans[N-1][M-1] = a ^ B[M-1];

    writeln("YES");
    ans.each!(a => a.map!(to!string).join(" ").writeln);
}

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

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

    Tuple!(int, int)[][] vals;
    foreach (_; 0 .. 2) vals ~= readln.chomp.split.map!(to!int).enumerate.map!(t => tuple(cast(int)t[0], t[1])).array;

    debug { vals.writeln; }

    auto ans = new int[][] (n, m);

    foreach_reverse (b; 0 .. 31) {
        auto cur = 1 << b;

        auto f = (Tuple!(int, int)[] arr) => arr.filter!(t => (t[1] & cur) > 0).map!(t => t[0]).array;
        auto nrs = vals.map!f.array;

        debug { if (b < 4) writeln(cur, ' ', nrs[0], ' ', nrs[1]); }

        if (nrs[0].length % 2 != nrs[1].length % 2) {
            writeln("NO");
            return;
        }

        if (nrs[0].length == 0) {
            foreach (j; nrs[1]) ans[0][j] ^= cur;
        } else if (nrs[1].length == 0) {
            foreach (i; nrs[0]) ans[i][0] ^= cur;
        } else if (nrs[0].length % 2 == 1) { // && nrs[1].length % 2 == 1 from above
            foreach (i; nrs[0]) {
                foreach (j; nrs[1]) {
                    ans[i][j] ^= cur;
                }
            }
        } else {
            while (nrs[0].length < nrs[1].length) nrs[0] ~= nrs[1].back;
            while (nrs[1].length < nrs[0].length) nrs[1] ~= nrs[0].back;
            foreach (i, j; lockstep(nrs[0], nrs[1])) ans[i][j] ^= cur;
        }
    }

    writeln("YES");
    ans.each!(arr => arr.writefln!("%(%s %)"));
}

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

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

    Tuple!(int, int)[][] vals;
    foreach (_; 0 .. 2) vals ~= readln.chomp.split.map!(to!int).enumerate.map!(t => tuple(cast(int)t[0], t[1])).array;

    debug { vals.writeln; }

    auto ans = new int[][] (n, m);

    foreach_reverse (b; 0 .. 31) {
        auto cur = 1 << b;

        auto f = (Tuple!(int, int)[] arr) => arr.filter!(t => (t[1] & cur) > 0).map!(t => t[0]).array;
        auto nrs = vals.map!f.array;

        debug { if (b < 4) writeln(cur, ' ', nrs[0], ' ', nrs[1]); }

        if (nrs[0].length % 2 != nrs[1].length % 2) {
            writeln("NO");
            return;
        }

        if (nrs[0].length == 0) {
            foreach (j; nrs[1]) ans[0][j] ^= cur;
        } else if (nrs[1].length == 0) {
            foreach (i; nrs[0]) ans[i][0] ^= cur;
        } else if (nrs[0].length % 2 == 1) { // && nrs[1].length % 2 == 1 from above
            foreach (i; nrs[0]) {
                foreach (j; nrs[1]) {
                    ans[i][j] ^= cur;
                }
            }
        } else {
            while (nrs[0].length < nrs[1].length) nrs[0] ~= nrs[1].back;
            while (nrs[1].length < nrs[0].length) nrs[1] ~= nrs[0].back;
            foreach (i, j; lockstep(nrs[0], nrs[1])) ans[i][j] ^= cur;
        }
    }

    ans.each!(arr => arr.writefln!("%(%s %)"));
}


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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

void main()
{
	auto n = RD!int;
	auto l = RD;
	auto k = RD!int;
	auto d = RDA ~ l;
	auto a = RDA;

	auto dp = new long[][](n, k+1);
	foreach (i; 0..n)
		dp[i][] = -1;
	dp[0][k] = 0;
	foreach (i; 1..n)
	{
		auto ndp = new long[][](n, k+1);
		foreach (j; 0..n)
			ndp[j][] = -1;
		foreach (j; 0..i)
		{
			foreach (m; 0..k+1)
			{
				if (dp[j][m] == -1) continue;
				ndp[i][m].chmax(dp[j][m]);
				if (m != 0)
				{
					ndp[j][m-1].chmax(dp[j][m] + (a[i] - a[j]) * (d[i+1] - d[i]));
				}
			}
		}
		dp = ndp;
		debug writeln(dp);
	}

	long ans;
	foreach (i; 0..n)
	{
		ans += a[i] * (d[i+1] - d[i]);
	}
	long tmp;
	foreach (i; 0..n)
	{
		foreach (j; 0..k+1)
		{
			tmp.chmax(dp[i][j]);
		}
	}
	ans -= tmp;

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

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

void main()
{
    immutable int INF = int.max;

    int n, t, k;
    readf!"%s %s %s"(n, t, k);
    readln;

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

    d ~= t;

    auto dp = new int[][] (n+1, k+1);
    dp[n][] = 0;
    foreach (i; 0 .. n) { dp[i][] = INF; }

    foreach_reverse (i; 0 .. n) {
        foreach (maxk; 0 .. k+1) {
            if (maxk > 0) { dp[i][maxk] = dp[i][maxk-1]; }
            for (int nxt = i+1, leftk = maxk; nxt <= n && leftk >= 0; ++nxt, --leftk) {
                auto cur = dp[nxt][leftk] + (d[nxt] - d[i]) * a[i];
                dp[i][maxk] = min(dp[i][maxk], cur);
            }
        }
    }

    debug { dp.writeln; }

    dp[0][k].writeln;
}

void main() { runSolver(); }

void problem() {
  auto N = scan!int;
  auto L = scan!long;
  auto K = scan!int;
  auto X = scan!long(N) ~ L;
  auto S = scan!long(N) ~ 0;

  auto solve() {
    auto dp = new long[][](N, K + 1);
    foreach(ref p; dp) p[] = int.max;
    dp[0][0] = X[1] * S[0];
    auto preDp = new long[][](N, K + 1);

    foreach(i; 1..N) {
      // dp.deb;
      swap(dp, preDp);
      dp = new long[][](N, K + 1);
      foreach(ref p; dp) p[] = int.max;
      const distance = X[i + 1] - X[i];

      foreach(from; 0..i) {
        foreach(skipped; 0..K) {
          dp[from][skipped + 1].chmin(preDp[from][skipped] + S[from]*distance);
        }
        foreach(skipped; 0..K + 1) {
          dp[i][skipped].chmin(preDp[from][skipped] + S[i]*distance);
        }
      }
    }
    // dp.deb;

    return dp.map!minElement.minElement;
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
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)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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

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

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

enum int INF = 1<<30;

void main() {
    int N, L, K; readf("%d %d %d\n", &N, &L, &K);
    auto D = readarray!int ~ [L];
    auto A = readarray!int ~ [0];
    N++;

    auto f = new int[][](K + 1, N + 1);
    auto nf = new int[][](K + 1, N + 1);
    foreach (ref l; f) l[] = INF;
    f[0][0] = 0;
    for (int n = 1; n < N; n++) {
        foreach (ref l; nf) l[] = INF;
        int d = D[n] - D[n-1];
        for (int k = 0; k <= min(K, n); k++) {
            for (int s = 0; s < n; s++) {
                nf[k][n] = min(nf[k][n], f[k][s] + d * A[s]);
                if (k + 1 <= min(K, n)) {
                    nf[k + 1][s] = min(nf[k + 1][s], f[k][s] + d * A[s]);
                }
            }
        }
        swap(f, nf);
    }
    int ans = INF;
    for (int k = 0; k <= K; k++) {
        ans = min(ans, f[k].reduce!min);
    }
    writeln(ans);
}

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.ascii, std.typecons;

void main()
{
    immutable int INF = int.max;

    int n, t, k;
    readf!"%s %s %s"(n, t, k);
    readln;

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

    d ~= t;

    auto dp = new int[][] (n+1, k+1);
    dp[n][] = 0;
    foreach (i; 0 .. n) { dp[i][] = INF; }

    foreach_reverse (i; 0 .. n) {
        foreach (maxk; 0 .. k+1) {
            for (int nxt = i+1, leftk = maxk; nxt <= n && leftk >= 0; ++nxt, --leftk) {
                auto cur = dp[nxt][leftk] + (d[nxt] - d[i]) * a[i];
                dp[i][maxk] = min(dp[i][maxk], cur);
            }
        }
    }

    debug { dp.writeln; }

    dp[0][k].writeln;
}

void main() { runSolver(); }

void problem() {
  auto N = scan!int;
  auto L = scan!long;
  auto K = scan!int;
  auto X = scan!long(N) ~ L;
  auto S = scan!long(N) ~ 0;

  struct Run {
    long time;
    long speed;

    int opCmp(Run other) {
      if (time > other.time) return 1;
      if (time < other.time) return -1;

      return speed > other.speed ? 1 : speed == other.speed ? 0 : -1;
    }
  }

  auto solve() {
    auto dp = new Run[][](N, K + 1);
    foreach(ref d; dp) foreach(ref x; d) x = Run(int.max, int.max);
    dp[0][0] = Run(S[0] * X[1], S[0]);

    foreach(i; 1..N) {
      auto pre = dp[i - 1];
      const d = X[i + 1] - X[i];
      const speed = S[i];

      foreach(k; 0..K) {
        if (pre[k].speed == int.max) continue;

        const preSpeed = pre[k].speed;
        const newTime = pre[k].time + preSpeed * d;
        auto run = Run(newTime, preSpeed);
        dp[i][k + 1].chmin(run);
      }
      foreach(k; 0..K + 1) {
        if (pre[k].speed == int.max) continue;

        const newTime = pre[k].time + speed * d;
        auto run = Run(newTime, speed);
        dp[i][k].chmin(run);
      }
    }

    dp.each!deb;
    // dp.deb;
    return dp[N - 1].map!"a.time".minElement;
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
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)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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

void main() { runSolver(); }

void problem() {
  auto N = scan!int;
  auto L = scan!long;
  auto K = scan!int;
  auto X = scan!long(N) ~ L;
  auto S = scan!long(N) ~ 0;

  auto solve() {
    alias Run = Tuple!(long, "time", long, "speed");
    auto dp = new Run[][](N, K + 1);
    foreach(ref d; dp) foreach(ref x; d) x = Run(int.max, int.max);
    dp[0][0] = Run(S[0] * X[1], S[0]);

    foreach(i; 1..N) {
      auto pre = dp[i - 1];
      const d = X[i + 1] - X[i];
      const speed = S[i];

      foreach(k; 0..K) {
        if (pre[k].speed == int.max) continue;

        const preSpeed = pre[k].speed;
        const newTime = pre[k].time + preSpeed * d;
        if (dp[i][k + 1].time > newTime) {
          dp[i][k + 1] = Run(newTime, preSpeed);
        }
      }
      foreach(k; 0..K + 1) {
        if (pre[k].speed == int.max) continue;

        const newTime = pre[k].time + speed * d;
        if (dp[i][k].time > newTime) {
          dp[i][k] = Run(newTime, speed);
        }
      }
    }

    dp.each!deb;
    // dp.deb;
    return dp[N - 1].map!"a.time".minElement;
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
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)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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

void main() { runSolver(); }

void problem() {
  auto N = scan!int;
  auto L = scan!long;
  auto K = scan!int;
  auto X = scan!long(N) ~ L;
  auto S = scan!long(N) ~ 0;

  auto solve() {
    alias Run = Tuple!(long, "time", long, "speed");
    auto dp = new Run[][](N, K + 1);
    foreach(ref d; dp) d[] = Run(int.max, int.max);
    dp[0][0] = Run(S[0] * X[1], S[0]);

    foreach(i; 1..N) {
      auto pre = dp[i - 1];
      const d = X[i + 1] - X[i];
      const speed = S[i];

      foreach(k; 0..K) {
        if (pre[k].speed == int.max) continue;

        const preSpeed = pre[k].speed;
        const newTime = pre[k].time + preSpeed * d;
        if (dp[i][k + 1].time > newTime) {
          dp[i][k + 1] = Run(newTime, preSpeed);
        }
      }
      foreach(k; 0..K + 1) {
        if (pre[k].speed == int.max) continue;

        const newTime = pre[k].time + speed * d;
        if (dp[i][k].time > newTime) {
          dp[i][k] = Run(newTime, speed);
        }
      }
    }

    // dp.each!deb;

    // dp.deb;
    return dp[N - 1].map!"a.time".minElement;
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
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)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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

void main() { runSolver(); }

void problem() {
  auto N = scan!int;
  auto L = scan!long;
  auto K = scan!int;
  auto X = scan!long(N) ~ L;
  auto S = scan!long(N) ~ 0;

  auto solve() {
    alias Run = Tuple!(long, "time", long, "speed");
    auto dp = new Run[][](N, K + 1);
    foreach(ref d; dp) d[] = Run(int.max, int.max);
    dp[0][0] = Run(S[0] * X[1], S[0]);

    foreach(i; 1..N) {
      auto pre = dp[i - 1];
      const d = X[i + 1] - X[i];
      const speed = S[i];

      foreach(k; 0..K) {
        const preSpeed = pre[k].speed;
        const newTime = pre[k].time + preSpeed * d;
        if (dp[i][k + 1].time > newTime) {
          dp[i][k + 1] = Run(newTime, preSpeed);
        }
      }
      foreach(k; 0..K + 1) {
        const newTime = pre[k].time + speed * d;
        if (dp[i][k].time > newTime) {
          dp[i][k] = Run(newTime, speed);
        }
      }
    }

    // dp.deb;
    return dp[N - 1].map!"a.time".minElement;
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
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)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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

void main() { runSolver(); }

void problem() {
  auto N = scan!int;
  auto L = scan!int;
  auto K = scan!int;
  auto X = scan!int(N) ~ L;
  auto S = scan!int(N) ~ 0;

  auto solve() {
    alias Run = Tuple!(long, "time", long, "speed");
    auto dp = new Run[][](N, K + 1);
    foreach(ref d; dp) d[] = Run(int.max, int.max);
    dp[0][0] = Run(S[0] * X[1], S[0]);

    foreach(i; 1..N) {
      auto pre = dp[i - 1];
      const d = X[i + 1] - X[i];
      const speed = S[i];

      foreach(k; 0..K) {
        const preSpeed = pre[k].speed;
        const newTime = pre[k].time + preSpeed * d;
        if (dp[i][k + 1].time > newTime) {
          dp[i][k + 1] = Run(newTime, preSpeed);
        }
      }
      foreach(k; 0..K + 1) {
        const newTime = pre[k].time + speed * d;
        if (dp[i][k].time > newTime) {
          dp[i][k] = Run(newTime, speed);
        }
      }
    }

    // dp.deb;
    return dp[N - 1].map!"a.time".minElement;
  }

  outputForAtCoder(&solve);
}

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

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric, std.traits, std.functional, std.bigint, std.datetime.stopwatch, core.time, core.bitop;
T[][] combinations(T)(T[] s, in long m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
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)(long n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");
Point invert(Point p) { return Point(p.y, p.x); }
long[] divisors(long n) { long[] ret; for (long i = 1; i * i <= n; i++) { if (n % i == 0) { ret ~= i; if (i * i != n) ret ~= n / i; } } return ret.sort.array; }
bool chmin(T)(ref T a, T b) { if (b < a) { a = b; return true; } else return false; }
bool chmax(T)(ref T a, T b) { if (b > a) { a = b; return true; } else return false; }
string charSort(alias S = "a < b")(string s) { return (cast(char[])((cast(byte[])s).sort!S.array)).to!string; }
ulong comb(ulong a, ulong b) { if (b == 0) {return 1;}else{return comb(a - 1, b - 1) * a / b;}}
string toAnswerString(R)(R r) { return r.map!"a.to!string".joiner(" ").array.to!string; }
struct ModInt(uint MD) if (MD < int.max) {ulong v;this(string v) {this(v.to!long);}this(int v) {this(long(v));}this(long v) {this.v = (v%MD+MD)%MD;}void opAssign(long t) {v = (t%MD+MD)%MD;}static auto normS(ulong x) {return (x<MD)?x:x-MD;}static auto make(ulong x) {ModInt m; m.v = x; return m;}auto opBinary(string op:"+")(ModInt r) const {return make(normS(v+r.v));}auto opBinary(string op:"-")(ModInt r) const {return make(normS(v+MD-r.v));}auto opBinary(string op:"*")(ModInt r) const {return make((ulong(v)*r.v%MD).to!ulong);}auto opBinary(string op:"^^", T)(T r) const {long x=v;long y=1;while(r){if(r%2==1)y=(y*x)%MD;x=x^^2%MD;r/=2;} return make(y);}auto opBinary(string op:"/")(ModInt r) const {return this*memoize!inv(r);}static ModInt inv(ModInt x) {return x^^(MD-2);}string toString() const {return v.to!string;}auto opOpAssign(string op)(ModInt r) {return mixin ("this=this"~op~"r");}}
alias MInt1 = ModInt!(10^^9 + 7);
alias MInt9 = ModInt!(998_244_353);
void outputForAtCoder(T)(T delegate() fn) {
  static if (is(T == float) || is(T == double) || is(T == real)) "%.16f".writefln(fn());
  else static if (is(T == void)) fn();
  else static if (is(T == string)) fn().writeln;
  else static if (isInputRange!T) {
    static if (!is(string == ElementType!T) && isInputRange!(ElementType!T)) foreach(r; fn()) r.toAnswerString.writeln;
    else foreach(r; fn()) r.writeln;
  }
  else fn().writeln;
}
void runSolver() {
  enum BORDER = "==================================";
  debug { BORDER.writeln; while(!stdin.eof) { "<<< Process time: %s >>>".writefln(benchmark!problem(1)); BORDER.writeln; } }
  else problem();
}
enum YESNO = [true: "Yes", false: "No"];

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

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

string FMT_F = "%.10f";

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

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

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }
double euDist(T)(T[] a, T[] b) { auto c = a.dup; c[] -= b[]; c[] *= c[]; return sqrt(cast(double)c.sum); }
double[] rotate(double[] vec, double rad) { return [cos(rad)*vec[0] - sin(rad)*vec[1], sin(rad)*vec[0] + cos(rad)*vec[1]]; }
double norm(double[] vec) { return sqrt(reduce!((a,b)=>a+b*b)(0.0, vec)); }
double dotProd(double[] a, double[] b) { auto r = a.dup; r[] *= b[]; return r.sum; }

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

void main()
{
	auto n = RD!int;
	auto l = RD;
	auto k = RD!int;
	auto d = RDA ~ l;
	auto a = RDA;

	auto dp = new long[][](n, k+1);
	foreach (i; 1..n)
	{
		auto ndp = new long[][](n, k+1);
		foreach (j; 0..i)
		{
			foreach (m; 0..k+1)
			{
				ndp[i][m].chmax(dp[j][m]);
				if (m != 0)
				{
					ndp[j][m-1].chmax(dp[j][m] + (a[i] - a[j]) * (d[i+1] - d[i]));
				}
			}
		}
		dp = ndp;
		debug writeln(dp);
	}

	long ans;
	foreach (i; 0..n)
	{
		ans += a[i] * (d[i+1] - d[i]);
	}
	long tmp;
	foreach (i; 0..n)
	{
		foreach (j; 0..k+1)
		{
			tmp.chmax(dp[i][j]);
		}
	}
	ans -= tmp;

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