On February, 30th n students came in the Center for Training Olympiad Programmers (CTOP) of the Berland State University. They came one by one, one after another. Each of them went in, and before sitting down at his desk, greeted with those who were present in the room by shaking hands. Each of the students who came in stayed in CTOP until the end of the day and never left.At any time any three students could join together and start participating in a team contest, which lasted until the end of the day. The team did not distract from the contest for a minute, so when another student came in and greeted those who were present, he did not shake hands with the members of the contest writing team. Each team consisted of exactly three students, and each student could not become a member of more than one team. Different teams could start writing contest at different times.Given how many present people shook the hands of each student, get a possible order in which the students could have come to CTOP. If such an order does not exist, then print that this is impossible.Please note that some students could work independently until the end of the day, without participating in a team contest.

The first line contains integer n (1 ≤ n ≤ 2·105) — the number of students who came to CTOP. The next line contains n integers a1, a2, ..., an (0 ≤ ai < n), where ai is the number of students with who the i-th student shook hands.

If the sought order of students exists, print in the first line "Possible" and in the second line print the permutation of the students' numbers defining the order in which the students entered the center. Number i that stands to the left of number j in this permutation means that the i-th student came earlier than the j-th student. If there are multiple answers, print any of them. If the sought order of students doesn't exist, in a single line print "Impossible".

NoteIn the first sample from the statement the order of events could be as follows:   student 4 comes in (a4 = 0), he has no one to greet;  student 5 comes in (a5 = 1), he shakes hands with student 4;  student 1 comes in (a1 = 2), he shakes hands with two students (students 4, 5);  student 3 comes in (a3 = 3), he shakes hands with three students (students 4, 5, 1);  students 4, 5, 3 form a team and start writing a contest;  student 2 comes in (a2 = 1), he shakes hands with one student (number 1). In the second sample from the statement the order of events could be as follows:   student 7 comes in (a7 = 0), he has nobody to greet;  student 5 comes in (a5 = 1), he shakes hands with student 7;  student 2 comes in (a2 = 2), he shakes hands with two students (students 7, 5);  students 7, 5, 2 form a team and start writing a contest;  student 1 comes in(a1 = 0), he has no one to greet (everyone is busy with the contest);  student 6 comes in (a6 = 1), he shakes hands with student 1;  student 8 comes in (a8 = 2), he shakes hands with two students (students 1, 6);  student 3 comes in (a3 = 3), he shakes hands with three students (students 1, 6, 8);  student 4 comes in (a4 = 4), he shakes hands with four students (students 1, 6, 8, 3);  students 8, 3, 4 form a team and start writing a contest;  student 9 comes in (a9 = 2), he shakes hands with two students (students 1, 6). In the third sample from the statement the order of events is restored unambiguously:   student 1 comes in (a1 = 0), he has no one to greet;  student 3 comes in (or student 4) (a3 = a4 = 1), he shakes hands with student 1;  student 2 comes in (a2 = 2), he shakes hands with two students (students 1, 3 (or 4));  the remaining student 4 (or student 3), must shake one student's hand (a3 = a4 = 1) but it is impossible as there are only two scenarios: either a team formed and he doesn't greet anyone, or he greets all the three present people who work individually.

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
alias to!int isz;
alias rbt = redBlackTree;
static string[] inp;
T rd(T = long)() { while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
/*******************************It's a Me, Mario!**********************************************/

void play(){
    int n;
    n = rd!int;
    int[] arr;
    arr = rdarr!int;

    int[][int] mvec;
    int pos = 0;
    foreach(el; arr){ mvec[el] ~= ++pos; }

    auto res = new int[](n);
    pos = 0;
    int ptr = 0;
    while(ptr < n && pos >= 0){
        while(pos >= 0 && (!(pos in mvec) || !mvec[pos].length)){
            pos -= 3;
        }
        if(pos < 0){
            writeln("Impossible"); return;
        }
        res[ptr] = mvec[pos].back;
        mvec[pos].popBack;
        ++pos;++ptr;
        debug writeln(res, " ", pos);
    }
    writeln("Possible");
    foreach(el; res){ write(el, " "); } writeln;
}

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

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
alias to!int isz;
alias rbt = redBlackTree;
static string[] inp;
T rd(T = long)() { while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
/*******************************It's a Me, Mario!**********************************************/

void play(){
    int n;
    n = rd!int;
    int[] arr;
    arr = rdarr!int;

    int[][int] mvec;
    int pos = 0;
    foreach(el; arr){ mvec[el] ~= ++pos; }

    auto res = new int[](n);
    int[] meep;
    pos = 0;
    int ptr = 0;
    int rptr = n-1;
    while(ptr <= rptr){
        if(!(pos in mvec) || !mvec[pos].length){ writeln("Impossible"); return; }

        res[ptr] = mvec[pos].back;
        mvec[pos].popBack;

        meep.sort();

        if(meep.length >= 2 && meep[0] > 0){
            pos -= 3;
            meep = [];
        }else if(meep.length >= 2){
            meep.popFront;
            if(pos >= 2 && ((pos-2) in mvec && mvec[pos-2].length)){
                if(mvec[pos-2].length > 1){ writeln("Impossible"); return; }
                res[rptr] = mvec[pos-2].back;
                mvec[pos-2].popBack;
                --rptr;
            }
            meep ~= mvec[pos].length.to!int;
        }else{
            meep ~= mvec[pos].length.to!int;
        }
        debug writeln("DEB: ", pos, " ", ptr, " ", res, " ", meep);
        ++pos;++ptr;
    }
    foreach_reverse(i; (rptr+1)..n){
        if(arr[res[i-1]-1] - arr[res[i]-1] != 2){
            /* debug writeln("DEB2: ", res[i]-1, " ", i-1, " ", arr[res[i]-1] - arr[res[i-1]-1]); */
            writeln("Impossible"); return;
        }
    }
    writeln("Possible");
    foreach(el; res){ write(el, " "); } writeln;
}

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

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
alias to!int isz;
alias rbt = redBlackTree;
static string[] inp;
T rd(T = long)() { while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
/*******************************It's a Me, Mario!**********************************************/

void play(){
    int n;
    n = rd!int;
    int[] arr;
    arr = rdarr!int;

    int[][int] mvec;
    int pos = 0;
    foreach(el; arr){ mvec[el] ~= ++pos; }

    auto res = new int[](n);
    int[] meep;
    pos = 0;
    int ptr = 0;
    int rptr = n-1;
    while(ptr <= rptr){
        if(!(pos in mvec) || !mvec[pos].length){ writeln("Impossible"); return; }

        res[ptr] = mvec[pos].back;
        mvec[pos].popBack;

        meep.sort();

        if(meep.length >= 2 && meep[0] > 0){
            pos -= 3;
            meep = [];
        }else if(meep.length >= 2){
            meep.popFront;
            if(pos >= 2 && ((pos-2) in mvec && mvec[pos-2].length)){
                if(mvec[pos-2].length > 1){ writeln("Impossible"); return; }
                res[rptr] = mvec[pos-2].back;
                mvec[pos-2].popBack;
                --rptr;
                meep.popFront;
            }
            meep ~= mvec[pos].length.to!int;
        }else{
            meep ~= mvec[pos].length.to!int;
        }
        /* debug if(pos == 0) writeln(mvec); */
        debug writeln("DEB: ", pos, " ", ptr, " ", res, " ", meep);
        ++pos;++ptr;
    }
    foreach_reverse(i; (rptr+1)..n){
        if(arr[res[i-1]-1] - arr[res[i]-1] % 2 != 0){
            /* debug writeln("DEB2: ", res[i]-1, " ", i-1, " ", arr[res[i]-1] - arr[res[i-1]-1]); */
            writeln("Impossible"); return;
        }
    }
    writeln("Possible");
    foreach(el; res){ write(el, " "); } writeln;
}

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

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
alias to!int isz;
alias rbt = redBlackTree;
static string[] inp;
T rd(T = long)() { while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
/*******************************It's a Me, Mario!**********************************************/

void play(){
    int n;
    n = rd!int;
    int[] arr;
    arr = rdarr!int;

    int[][int] mvec;
    int pos = 0;
    foreach(el; arr){ mvec[el] ~= ++pos; }

    auto res = new int[](n);
    int[] meep;
    pos = 0;
    int ptr = 0;
    int rptr = n-1;
    while(ptr <= rptr){
        if(!(pos in mvec)){ writeln("Impossible"); return; }

        res[ptr] = mvec[pos].back;
        mvec[pos].popBack;

        meep ~= mvec[pos].length.to!int;
        meep.sort();

        if(meep.length >= 3 && meep[0] > 0){
            pos -= 3;
            meep = [];
        }else if(meep.length >= 3){
            meep.popFront;
            if(pos >= 2 && mvec[pos-2].length){
                if(mvec[pos-2].length > 1){ writeln("Impossible"); return; }
                res[rptr] = mvec[pos-2].back;
                mvec[pos-2].popBack;
                --rptr;
            }
        }
        debug writeln("DEB: ", pos, " ", ptr, " ", res, " ", meep);
        ++pos;++ptr;
    }
    writeln("Possible");
    foreach(el; res){ write(el, " "); } writeln;
}

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

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
alias to!int isz;
alias rbt = redBlackTree;
static string[] inp;
T rd(T = long)() { while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
/*******************************It's a Me, Mario!**********************************************/

void play(){
    int n;
    n = rd!int;
    int[] arr;
    arr = rdarr!int;

    int[][int] mvec;
    int pos = 0;
    foreach(el; arr){ mvec[el] ~= ++pos; }

    auto res = new int[](n);
    int[] meep;
    pos = 0;
    int ptr = 0;
    int rptr = n-1;
    while(ptr <= rptr){
        if(!(pos in mvec) || !mvec[pos].length){ writeln("Impossible"); return; }

        res[ptr] = mvec[pos].back;
        mvec[pos].popBack;

        meep.sort();

        if(meep.length >= 2 && meep[0] > 0){
            pos -= 3;
            meep = [];
        }else if(meep.length >= 2){
            meep.popFront;
            if(pos >= 2 && ((pos-2) in mvec && mvec[pos-2].length)){
                if(mvec[pos-2].length > 1){ writeln("Impossible"); return; }
                res[rptr] = mvec[pos-2].back;
                mvec[pos-2].popBack;
                --rptr;
                meep.popFront;
            }
            meep ~= mvec[pos].length.to!int;
        }else{
            meep ~= mvec[pos].length.to!int;
        }
        /* debug if(pos == 0) writeln(mvec); */
        debug writeln("DEB: ", pos, " ", ptr, " ", res, " ", meep);
        ++pos;++ptr;
    }
    foreach_reverse(i; (rptr+1)..n){
        if(arr[res[i-1]-1] - arr[res[i]-1] != 2){
            /* debug writeln("DEB2: ", res[i]-1, " ", i-1, " ", arr[res[i]-1] - arr[res[i-1]-1]); */
            writeln("Impossible"); return;
        }
    }
    writeln("Possible");
    foreach(el; res){ write(el, " "); } writeln;
}

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

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
alias to!int isz;
alias rbt = redBlackTree;
static string[] inp;
T rd(T = long)() { while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
/*******************************It's a Me, Mario!**********************************************/

void play(){
    int n;
    n = rd!int;
    int[] arr;
    arr = rdarr!int;

    int[][int] mvec;
    int pos = 0;
    foreach(el; arr){ mvec[el] ~= ++pos; }

    auto res = new int[](n);
    int[] meep;
    pos = 0;
    int ptr = 0;
    int rptr = n-1;
    while(ptr <= rptr){
        if(!(pos in mvec)){ writeln("Impossible"); return; }

        res[ptr] = mvec[pos].back;
        mvec[pos].popBack;

        meep ~= mvec[pos].length.to!int;
        meep.sort();

        if(meep.length >= 3 && meep[0] > 0){
            pos -= 3;
            meep = [];
        }else if(meep.length >= 3){
            meep.popFront;
            if(pos >= 2 && mvec[pos-2].length){
                if(mvec[pos-2].length > 1){ writeln("Impossible"); return; }
                res[rptr] = mvec[pos-2].back;
                mvec[pos-2].popBack;
                --rptr;
            }
        }
        debug writeln("DEB: ", pos, " ", ptr, " ", res, " ", meep);
        ++pos;++ptr;
    }
    foreach_reverse(i; (rptr+1)..n){
        if(arr[res[i-1]-1] - arr[res[i]-1] != 2){
            /* debug writeln("DEB2: ", res[i]-1, " ", i-1, " ", arr[res[i]-1] - arr[res[i-1]-1]); */
            writeln("Impossible"); return;
        }
    }
    writeln("Possible");
    foreach(el; res){ write(el, " "); } writeln;
}

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

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
alias to!int isz;
alias rbt = redBlackTree;
static string[] inp;
T rd(T = long)() { while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
/*******************************It's a Me, Mario!**********************************************/

void play(){
    int n;
    n = rd!int;
    int[] arr;
    arr = rdarr!int;

    int[][int] mvec;
    int pos = 0;
    foreach(el; arr){ mvec[el] ~= ++pos; }

    auto res = new int[](n);
    pos = 0;
    int ptr = 0;
    while(ptr < n && ptr >= 0){
        if(pos >= 0 && (!(pos in mvec) || !mvec[pos].length)){
            pos -= 3;
        }
        if(pos < 0 || !mvec[pos].length){
            writeln("Impossible"); return;
        }
        res[ptr] = mvec[pos].back;
        mvec[pos].popBack;
        ++pos;++ptr;
        debug writeln(res, " ", pos);
    }
    writeln("Possible");
    foreach(el; res){ write(el, " "); } writeln;
}

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

// Cheese-Cracker: cheese-cracker.github.io
import std.stdio, std.conv, std.functional, std.string, std.algorithm;
import std.container, std.range, std.typecons, std.bigint, std.numeric, std.math, std.random;

alias ll = long;
alias to!int isz;
alias rbt = redBlackTree;
static string[] inp;
T rd(T = long)() { while(!inp.length) inp = readln.chomp.split; string res = inp[0]; inp.popFront; return res.to!T; }
T[] rdarr(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
/*******************************It's a Me, Mario!**********************************************/

void play(){
    int n;
    n = rd!int;
    int[] arr;
    arr = rdarr!int;

    int[][int] mvec;
    int pos = 0;
    foreach(el; arr){ mvec[el] ~= ++pos; }

    auto res = new int[](n);
    int[] meep;
    pos = 0;
    int ptr = 0;
    int rptr = n-1;
    while(ptr <= rptr){
        if(!(pos in mvec)){ writeln("Impossible"); return; }

        res[ptr] = mvec[pos].back;
        mvec[pos].popBack;

        meep ~= mvec[pos].length.to!int;
        meep.sort();

        if(meep.length >= 3 && meep[0] > 0){
            pos -= 3;
            meep = [];
        }else if(meep.length >= 3){
            meep.popFront;
            if(pos >= 2 && mvec[pos-2].length){
                if(mvec[pos-2].length > 1){ writeln("Impossible"); return; }
                res[rptr] = mvec[pos-2].back;
                mvec[pos-2].popBack;
                --rptr;
            }
        }
        debug writeln("DEB: ", pos, " ", ptr, " ", res, " ", meep);
        ++pos;++ptr;
    }
    foreach_reverse(i; (rptr+1)..n){
        if(arr[res[i]] - arr[res[i-1]] != 2){
            writeln("Impossible"); return;
        }
    }
    writeln("Possible");
    foreach(el; res){ write(el, " "); } writeln;
}

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


You are given two integers $$$a$$$ and $$$b$$$. You may perform any number of operations on them (possibly zero).During each operation you should choose any positive integer $$$x$$$ and set $$$a := a - x$$$, $$$b := b - 2x$$$ or $$$a := a - 2x$$$, $$$b := b - x$$$. Note that you may choose different values of $$$x$$$ in different operations.Is it possible to make $$$a$$$ and $$$b$$$ equal to $$$0$$$ simultaneously?Your program should answer $$$t$$$ independent test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow, each test case is represented by one line containing two integers $$$a$$$ and $$$b$$$ for this test case ($$$0 \le a, b \le 10^9$$$).

For each test case print the answer to it — YES if it is possible to make $$$a$$$ and $$$b$$$ equal to $$$0$$$ simultaneously, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

NoteIn the first test case of the example two operations can be used to make both $$$a$$$ and $$$b$$$ equal to zero:  choose $$$x = 4$$$ and set $$$a := a - x$$$, $$$b := b - 2x$$$. Then $$$a = 6 - 4 = 2$$$, $$$b = 9 - 8 = 1$$$;  choose $$$x = 1$$$ and set $$$a := a - 2x$$$, $$$b := b - x$$$. Then $$$a = 2 - 2 = 0$$$, $$$b = 1 - 1 = 0$$$.

import std.stdio;

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

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

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

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

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

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

string FMT_F = "%.10f";

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

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

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

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

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

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

import std.stdio;

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

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

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

string FMT_F = "%.10f";

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

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

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

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

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

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


In all schools in Buryatia, in the $$$1$$$ class, everyone is told the theory of Fibonacci strings."A block is a subsegment of a string where all the letters are the same and are bounded on the left and right by the ends of the string or by letters other than the letters in the block. A string is called a Fibonacci string if, when it is divided into blocks, their lengths in the order they appear in the string form the Fibonacci sequence ($$$f_0 = f_1 = 1$$$, $$$f_i = f_{i-2} + f_{i-1}$$$), starting from the zeroth member of this sequence. A string is called semi-Fibonacci if it possible to reorder its letters to get a Fibonacci string."Burenka decided to enter the Buryat State University, but at the entrance exam she was given a difficult task. She was given a string consisting of the letters of the Buryat alphabet (which contains exactly $$$k$$$ letters), and was asked if the given string is semi-Fibonacci. The string can be very long, so instead of the string, she was given the number of appearances of each letter ($$$c_i$$$ for the $$$i$$$-th letter) in that string. Unfortunately, Burenka no longer remembers the theory of Fibonacci strings, so without your help she will not pass the exam.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The following is a description of the input data sets. The first line of each test case contains one integer $$$k$$$ ($$$1 \leq k \leq 100$$$) — the number of letters in the alphabet. The second line of each test case contains $$$k$$$ integers $$$c_1, c_2, \ldots, c_k$$$ ($$$1 \leq c_i \leq 10^9$$$) — the number of occurrences of each letter in the string.

For each test case print the string "YES" if the corresponding string is semi-Fibonacci, and "NO" if it is not. You can print "YES" and "NO" in any case (for example, the strings "yEs", "yes", "Yes" will be recognized as a positive answer).

NoteIn the first test case, a one-character string is semi-Fibonacci, being itself a Fibonacci string.In the second test case, a string of two different characters is Fibonacci.In the third test case, the string "abb" (let the first of the alphabet letter be a, the second letter b) is not a semi-Fibonacci string, since no permutation of its letters ("abb", "bab", and "bba") is a Fibonacci string.In the fourth test case, two permutations of the letters of the string "abaccac" (the first letter is a, the second letter is b, the third letter is c) are Fibonacci strings — "abaaccc" and "cbccaaa".

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

immutable long [] f = recurrence !(q{a[n - 1] + a[n - 2]}) (1L, 1L)
    .take (75).array;

bool solve (int k, long [] c)
{
	sort (c);
	auto total = sum (c);
	int n = 0;
	while (total > 0)
	{
		total -= f[n];
		n += 1;
	}
	if (total < 0)
	{
		return false;
	}

	for (n--; n >= 0; n--)
	{
		if (c[k - 1] < f[n])
		{
			return false;
		}

		c[k - 1] -= f[n];
		int i = k - 1;
		while (i > 0 && c[i] <= c[i - 1])
		{
			c.swapAt (i - 1, i);
			i -= 1;
		}
		if (c[i] == 0)
		{
			c = c[1..$];
			k -= 1;
		}
		else if (i == k - 1)
		{
			return false;
		}
	}
	return true;
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto k = readln.strip.to !(int);
		auto c = readln.splitter.map !(to !(long)).array;
		writeln (solve (k, c) ? "YES" : "NO");
	}
}


Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the olympiad should meet together in Metropolis (the capital of the country) for the problem preparation process.There are n + 1 cities consecutively numbered from 0 to n. City 0 is Metropolis that is the meeting point for all jury members. For each city from 1 to n there is exactly one jury member living there. Olympiad preparation is a long and demanding process that requires k days of work. For all of these k days each of the n jury members should be present in Metropolis to be able to work on problems.You know the flight schedule in the country (jury members consider themselves important enough to only use flights for transportation). All flights in Metropolia are either going to Metropolis or out of Metropolis. There are no night flights in Metropolia, or in the other words, plane always takes off at the same day it arrives. On his arrival day and departure day jury member is not able to discuss the olympiad. All flights in Megapolia depart and arrive at the same day.Gather everybody for k days in the capital is a hard objective, doing that while spending the minimum possible money is even harder. Nevertheless, your task is to arrange the cheapest way to bring all of the jury members to Metrpolis, so that they can work together for k days and then send them back to their home cities. Cost of the arrangement is defined as a total cost of tickets for all used flights. It is allowed for jury member to stay in Metropolis for more than k days.

The first line of input contains three integers n, m and k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 106).  The i-th of the following m lines contains the description of the i-th flight defined by four integers di, fi, ti and ci (1 ≤ di ≤ 106, 0 ≤ fi ≤ n, 0 ≤ ti ≤ n, 1 ≤ ci ≤ 106, exactly one of fi and ti equals zero), the day of departure (and arrival), the departure city, the arrival city and the ticket cost.

Output the only integer that is the minimum cost of gathering all jury members in city 0 for k days and then sending them back to their home cities. If it is impossible to gather everybody in Metropolis for k days and then send them back to their home cities, output "-1" (without the quotes).

NoteThe optimal way to gather everybody in Metropolis in the first sample test is to use flights that take place on days 1, 2, 8 and 9. The only alternative option is to send jury member from second city back home on day 15, that would cost 2500 more.In the second sample it is impossible to send jury member from city 2 back home from Metropolis.

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

immutable long INF = 1L << 59;

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

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

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

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

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

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

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

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

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

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

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

        if (used_cnt < N)
            continue;

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

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

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

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

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

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

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

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

    immutable int MXD = 10 ^^ 6;

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

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

    }

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

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

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

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

        if (rborder < k) { continue; }

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

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

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

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

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

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

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

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

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

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

    }

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

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

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

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

        if (rborder < k) { continue; }

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

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

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

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

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

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

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

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

enum INF = 10L^^13;

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

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

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

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

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

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

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

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

immutable long INF = 1L << 59;

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

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

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

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

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

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

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

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

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

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

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

        if (used_cnt < N)
            continue;

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

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

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

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

immutable long INF = 1L << 59;

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

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

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

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

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

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

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

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

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

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

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

        if (used_cnt < N)
            continue;

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

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

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


You are given $$$m$$$ sets of integers $$$A_1, A_2, \ldots, A_m$$$; elements of these sets are integers between $$$1$$$ and $$$n$$$, inclusive.There are two arrays of positive integers $$$a_1, a_2, \ldots, a_m$$$ and $$$b_1, b_2, \ldots, b_n$$$. In one operation you can delete an element $$$j$$$ from the set $$$A_i$$$ and pay $$$a_i + b_j$$$ coins for that.You can make several (maybe none) operations (some sets can become empty).After that, you will make an edge-colored undirected graph consisting of $$$n$$$ vertices. For each set $$$A_i$$$ you will add an edge $$$(x, y)$$$ with color $$$i$$$ for all $$$x, y \in A_i$$$ and $$$x < y$$$. Some pairs of vertices can be connected with more than one edge, but such edges have different colors.You call a cycle $$$i_1 \to e_1 \to i_2 \to e_2 \to \ldots \to i_k \to e_k \to i_1$$$ ($$$e_j$$$ is some edge connecting vertices $$$i_j$$$ and $$$i_{j+1}$$$ in this graph) rainbow if all edges on it have different colors.Find the minimum number of coins you should pay to get a graph without rainbow cycles.

The first line contains two integers $$$m$$$ and $$$n$$$ ($$$1 \leq m, n \leq 10^5$$$), the number of sets and the number of vertices in the graph. The second line contains $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ ($$$1 \leq a_i \leq 10^9$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$). In the each of the next of $$$m$$$ lines there are descriptions of sets. In the $$$i$$$-th line the first integer $$$s_i$$$ ($$$1 \leq s_i \leq n$$$) is equal to the size of $$$A_i$$$. Then $$$s_i$$$ integers follow: the elements of the set $$$A_i$$$. These integers are from $$$1$$$ to $$$n$$$ and distinct. It is guaranteed that the sum of $$$s_i$$$ for all $$$1 \leq i \leq m$$$ does not exceed $$$2 \cdot 10^5$$$.

Print one integer: the minimum number of coins you should pay for operations to avoid rainbow cycles in the obtained graph.

NoteIn the first test, you can make such operations:  Delete element $$$1$$$ from set $$$1$$$. You should pay $$$a_1 + b_1 = 5$$$ coins for that.  Delete element $$$1$$$ from set $$$2$$$. You should pay $$$a_2 + b_1 = 6$$$ coins for that. You pay $$$11$$$ coins in total. After these operations, the first and the second sets will be equal to $$$\{2\}$$$ and the third set will be equal to $$$\{1, 2\}$$$.So, the graph will consist of one edge $$$(1, 2)$$$ of color $$$3$$$.In the second test, you can make such operations:  Delete element $$$1$$$ from set $$$1$$$. You should pay $$$a_1 + b_1 = 11$$$ coins for that.  Delete element $$$4$$$ from set $$$2$$$. You should pay $$$a_2 + b_4 = 13$$$ coins for that.  Delete element $$$7$$$ from set $$$3$$$. You should pay $$$a_3 + b_7 = 13$$$ coins for that.  Delete element $$$4$$$ from set $$$4$$$. You should pay $$$a_4 + b_4 = 16$$$ coins for that.  Delete element $$$7$$$ from set $$$6$$$. You should pay $$$a_6 + b_7 = 13$$$ coins for that. You pay $$$66$$$ coins in total.After these operations, the sets will be:  $$$\{2, 3\}$$$;  $$$\{1\}$$$;  $$$\{1, 3\}$$$;  $$$\{3\}$$$;  $$$\{3, 4, 5, 6, 7\}$$$;  $$$\{5\}$$$;  $$$\{8\}$$$. We will get the graph:There are no rainbow cycles in it.

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

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

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

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

int root(int[] uf, int u) {
  return (uf[u] < 0) ? u : (uf[u] = uf.root(uf[u]));
}
bool connect(int[] uf, int u, int v) {
  u = uf.root(u);
  v = uf.root(v);
  if (u == v) return false;
  if (uf[u] > uf[v]) swap(u, v);
  uf[u] += uf[v];
  uf[v] = u;
  return true;
}

void main() {
  try {
    for (; ; ) {
      const M = readInt();
      const N = readInt();
      auto A = new long[M];
      foreach (i; 0 .. M) {
        A[i] = readLong();
      }
      auto B = new long[N + 1];
      foreach (j; 1 .. N + 1) {
        B[j] = readLong();
      }
      auto S = new int[M];
      auto C = new int[][M];
      foreach (i; 0 .. M) {
        S[i] = readInt();
        C[i] = new int[S[i]];
        foreach (s; 0 .. S[i]) {
          C[i][s] = readInt();
        }
      }

      alias Edge = Tuple!(long, "c", int, "u", int, "v");
      Edge[] edges;
      foreach (i; 0 .. M) {
        foreach (s; 0 .. S[i]) {
          edges ~= Edge(A[i] + B[C[i][s]], i, M + C[i][s]);
        }
      }
      edges.sort!"a.c > b.c";
      auto uf = new int[M + N + 1];
      uf[] = -1;
      long ans;
      foreach (ref e; edges) {
        if (!uf.connect(e.u, e.v)) {
          ans += e.c;
        }
      }
      writeln(ans);
    }
  } catch (EOFException e) {
  }
}


This is an interactive problem.A legendary tree rests deep in the forest. Legend has it that individuals who realize this tree would eternally become a Legendary Grandmaster.To help you determine the tree, Mikaela the Goddess has revealed to you that the tree contains $$$n$$$ vertices, enumerated from $$$1$$$ through $$$n$$$. She also allows you to ask her some questions as follows. For each question, you should tell Mikaela some two disjoint non-empty sets of vertices $$$S$$$ and $$$T$$$, along with any vertex $$$v$$$ that you like. Then, Mikaela will count and give you the number of pairs of vertices $$$(s, t)$$$ where $$$s \in S$$$ and $$$t \in T$$$ such that the simple path from $$$s$$$ to $$$t$$$ contains $$$v$$$.Mikaela the Goddess is busy and will be available to answer at most $$$11\,111$$$ questions.This is your only chance. Your task is to determine the tree and report its edges.

The first line contains an integer $$$n$$$ ($$$2 \leq n \leq 500$$$) — the number of vertices in the tree.

When program has realized the tree and is ready to report the edges, print "ANSWER" in a separate line. Make sure that all letters are capitalized. Then, print $$$n-1$$$ lines, each containing two space-separated integers, denoting the vertices that are the endpoints of a certain edge. Each edge should be reported exactly once. Your program should then immediately terminate.

NoteIn the sample, the tree is as follows.  $$$n = 5$$$ is given to the program. The program then asks Mikaela a question where $$$S = \{1, 2, 3\}$$$, $$$T = \{4, 5\}$$$, and $$$v = 2$$$, to which she replies with $$$5$$$ (the pairs $$$(s, t)$$$ are $$$(1, 4)$$$, $$$(1, 5)$$$, $$$(2, 4)$$$, $$$(2, 5)$$$, and $$$(3, 5)$$$).

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

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

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

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

int N;

version(LOCAL) {
  int[] A, B;
  int[][] D;
}

void Init() {
  version(LOCAL) {
    N = readInt();
    A = new int[N - 1];
    B = new int[N - 1];
    foreach (i; 0 .. N - 1) {
      A[i] = readInt() - 1;
      B[i] = readInt() - 1;
    }
    D = new int[][](N, N);
    foreach (u; 0 .. N) {
      D[u][] = N;
      D[u][u] = 0;
    }
    foreach (i; 0 .. N - 1) {
      D[A[i]][B[i]] = 1;
      D[B[i]][A[i]] = 1;
    }
    foreach (w; 0 .. N) foreach (u; 0 .. N) foreach (v; 0 .. N) {
      chmin(D[u][v], D[u][w] + D[w][v]);
    }
  } else {
    N = readInt();
  }
}

int Ask(int[] S, int[] T, int v) {
  int ret;
  version(LOCAL) {
    foreach (s; S) foreach (t; T) {
      if (D[s][t] == D[s][v] + D[v][t]) {
        ++ret;
      }
    }
  } else {
    writeln(S.length);
    writeln(S.map!(u => u + 1).to!string.replaceAll(regex(`[\[\],]`), ""));
    writeln(T.length);
    writeln(T.map!(u => u + 1).to!string.replaceAll(regex(`[\[\],]`), ""));
    writeln(v + 1);
    stdout.flush;
    ret = readInt();
  }
  return ret;
}

void Answer(int[] a, int[] b) {
  writeln("ANSWER");
  foreach (i; 0 .. N - 1) {
    writeln(a[i] + 1, " ", b[i] + 1);
  }
  stdout.flush;
}

void main() {
  Init();

  int rt = 0;
  auto sz = new int[N];
  sz[rt] = N;
  foreach (u; 0 .. N) {
    if (u != rt) {
      int[] T;
      foreach (v; 0 .. N) {
        if (v != rt) {
          T ~= v;
        }
      }
      sz[u] = Ask([rt], T, u);
    }
  }
  debug {
    writeln("sz = ", sz);
  }

  auto us = iota(N).array;
  us.sort!((u, v) => (sz[u] < sz[v]));
  int[] ansA, ansB;
  int[] des;
  foreach (j; 0 .. N) {
    for (int s = sz[us[j]] - 1; s > 0; ) {
      int lo = 0, hi = cast(int)(des.length);
      for (; lo + 1 < hi; ) {
        const mid = (lo + hi) / 2;
        ((Ask([rt], des[0 .. mid], us[j]) > 0) ? hi : lo) = mid;
      }
      ansA ~= us[j];
      ansB ~= des[lo];
      s -= sz[des[lo]];
      des = des[0 .. lo] ~ des[hi .. $];
    }
    des ~= us[j];
  }
  Answer(ansA, ansB);
}


You have a sequence of $$$n$$$ colored blocks. The color of the $$$i$$$-th block is $$$c_i$$$, an integer between $$$1$$$ and $$$n$$$.You will place the blocks down in sequence on an infinite coordinate grid in the following way.   Initially, you place block $$$1$$$ at $$$(0, 0)$$$.  For $$$2 \le i \le n$$$, if the $$$(i - 1)$$$-th block is placed at position $$$(x, y)$$$, then the $$$i$$$-th block can be placed at one of positions $$$(x + 1, y)$$$, $$$(x - 1, y)$$$, $$$(x, y + 1)$$$ (but not at position $$$(x, y - 1)$$$), as long no previous block was placed at that position. A tower is formed by $$$s$$$ blocks such that they are placed at positions $$$(x, y), (x, y + 1), \ldots, (x, y + s - 1)$$$ for some position $$$(x, y)$$$ and integer $$$s$$$. The size of the tower is $$$s$$$, the number of blocks in it. A tower of color $$$r$$$ is a tower such that all blocks in it have the color $$$r$$$.For each color $$$r$$$ from $$$1$$$ to $$$n$$$, solve the following problem independently:   Find the maximum size of a tower of color $$$r$$$ that you can form by placing down the blocks according to the rules.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases.  The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \le c_i \le n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output $$$n$$$ integers. The $$$r$$$-th of them should be the maximum size of an tower of color $$$r$$$ you can form by following the given rules. If you cannot form any tower of color $$$r$$$, the $$$r$$$-th integer should be $$$0$$$.

NoteIn the first test case, one of the possible ways to form a tower of color $$$1$$$ and size $$$3$$$ is:   place block $$$1$$$ at position $$$(0, 0)$$$;  place block $$$2$$$ to the right of block $$$1$$$, at position $$$(1, 0)$$$;  place block $$$3$$$ above block $$$2$$$, at position $$$(1, 1)$$$;  place block $$$4$$$ to the left of block $$$3$$$, at position $$$(0, 1)$$$;  place block $$$5$$$ to the left of block $$$4$$$, at position $$$(-1, 1)$$$;  place block $$$6$$$ above block $$$5$$$, at position $$$(-1, 2)$$$;  place block $$$7$$$ to the right of block $$$6$$$, at position $$$(0, 2)$$$.   The blocks at positions $$$(0, 0)$$$, $$$(0, 1)$$$, and $$$(0, 2)$$$ all have color $$$1$$$, forming an tower of size $$$3$$$.In the second test case, note that the following placement is not valid, since you are not allowed to place block $$$6$$$ under block $$$5$$$:  It can be shown that it is impossible to form a tower of color $$$4$$$ and size $$$3$$$.

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

void solve(){
    int n = scan!int;
    auto arr = scanArray!int;
    auto dp = new long[][](2, n);
    dp[0][] = 0;
    dp[1][] = 0;

    for(int i = 0; i < n; ++i){
        dp[i % 2][arr[i]-1] = max(1 + dp[!(i % 2)][arr[i]-1], dp[i % 2][arr[i]-1]);
    }

    auto res = new long[](n);
    for(int i = 0; i < n; ++i){
        res[arr[i]-1] = max(res[arr[i]-1], dp[0][arr[i]-1], dp[1][arr[i]-1]);
    }
    res.each!(a => write(a, " "));
    writeln;
}

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

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


An integer sequence is called beautiful if the difference between any two consecutive numbers is equal to $$$1$$$. More formally, a sequence $$$s_1, s_2, \ldots, s_{n}$$$ is beautiful if $$$|s_i - s_{i+1}| = 1$$$ for all $$$1 \leq i \leq n - 1$$$.Trans has $$$a$$$ numbers $$$0$$$, $$$b$$$ numbers $$$1$$$, $$$c$$$ numbers $$$2$$$ and $$$d$$$ numbers $$$3$$$. He wants to construct a beautiful sequence using all of these $$$a + b + c + d$$$ numbers.However, it turns out to be a non-trivial task, and Trans was not able to do it. Could you please help Trans?

The only input line contains four non-negative integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$d$$$ ($$$0 < a+b+c+d \leq 10^5$$$).

If it is impossible to construct a beautiful sequence satisfying the above constraints, print "NO" (without quotes) in one line. Otherwise, print "YES" (without quotes) in the first line. Then in the second line print $$$a + b + c + d$$$ integers, separated by spaces — a beautiful sequence. There should be $$$a$$$ numbers equal to $$$0$$$, $$$b$$$ numbers equal to $$$1$$$, $$$c$$$ numbers equal to $$$2$$$ and $$$d$$$ numbers equal to $$$3$$$. If there are multiple answers, you can print any of them.

NoteIn the first test, it is easy to see, that the sequence is beautiful because the difference between any two consecutive numbers is equal to $$$1$$$. Also, there are exactly two numbers, equal to $$$0$$$, $$$1$$$, $$$2$$$ and exactly one number, equal to $$$3$$$.It can be proved, that it is impossible to construct beautiful sequences in the second and third tests.

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

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

void solve(){
	int a = rint, b = rint, c = rint, d = rint;
	int[] ans;
	if(a == 0 && b == 0){
		if(c + 1 == d){
			ans ~= 3;
			foreach(i; 0 .. c) ans ~= 2, ans ~= 3;
		}
		else if(c == d){
			foreach(i; 0 .. d) ans ~= 2, ans ~= 3;
		}
		else if(c == d + 1){
			foreach(i; 0 .. d) ans ~= 2, ans ~= 3;
			ans ~= 2;
		}
	}
	else if(c == 0 && d == 0){
		if(a + 1 == b){
			ans ~= 1;
			foreach(i; 0 .. a) ans ~= 0, ans ~= 1;
		}
		else if(a == b){
			foreach(i; 0 .. a) ans ~= 0, ans ~= 1;
		}
		else if(a == b + 1){
			foreach(i; 0 .. b) ans ~= 0, ans ~= 1;
			ans ~= 0;
		}
	}
	else if(a == 0 && d == 0){
		if(b + 1 == c){
			foreach(i; 0 .. b) ans ~= 2, ans ~= 1;
			ans ~= 2;
		}
		else if(b == c){
			foreach(i; 0 .. b) ans ~= 2, ans ~= 1;
		}
		else if(b == c + 1){
			ans ~= 1;
			foreach(i; 0 .. c) ans ~= 2, ans ~= 1;
		}
	}
	else if(a > b){
	}
	else if(c < d){
	}
	else if(b - a == c - d){
		foreach(i; 0 .. a) ans ~= 0, ans ~= 1;
		foreach(i; 0 .. b - a) ans ~= 2, ans ~= 1;
		foreach(i; 0 .. d) ans ~= 2, ans ~= 3;
	}
	else if(b - a - 1 == c - d){
		ans ~= 1;
		foreach(i; 0 .. a) ans ~= 0, ans ~= 1;
		foreach(i; 0 .. b - a - 1) ans ~= 2, ans ~= 1;
		foreach(i; 0 .. d) ans ~= 2, ans ~= 3;
	}
	else if(b - a == c - d - 1){
		foreach(i; 0 .. a) ans ~= 0, ans ~= 1;
		foreach(i; 0 .. b - a) ans ~= 2, ans ~= 1;
		foreach(i; 0 .. d) ans ~= 2, ans ~= 3;
		ans ~= 2;
	}
	else if(b - a - 1 == c - d - 1){
		ans ~= 1;
		foreach(i; 0 .. a) ans ~= 0, ans ~= 1;
		foreach(i; 0 .. b - a - 1) ans ~= 2, ans ~= 1;
		foreach(i; 0 .. d) ans ~= 2, ans ~= 3;
		ans ~= 2;
	}

	if(ans.length == 0) "NO".writeln;
	else{
		"YES".writeln;
		ans.map!(to!string).array.join(" ").writeln;
	}
}

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

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

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

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

int[] solveGreedy(int[] as) {
  const n = as.sum;
  foreach (s; 0 .. 4) {
    int[] ps;
    auto bs = as.dup;
    if (bs[s] > 0) {
      --bs[s];
      ps ~= s;
      foreach (i; 1 .. n) {
        foreach (x; 0 .. 4) {
          if (bs[x] > 0 && abs(x - ps[i - 1]) == 1) {
            --bs[x];
            ps ~= x;
            goto found;
          }
        }
        goto failed;
       found:
      }
      return ps;
    }
   failed:
  }
  return null;
}

void main() {
  debug {
    foreach (a; 0 .. 10) foreach (b; 0 .. 10) foreach (c; 0 .. 10) foreach (d; 0 .. 10) {
      const n = a + b + c + d;
      if (0 < n && n <= 10) {
        int[] perm;
        perm ~= repeat(0, a).array;
        perm ~= repeat(1, b).array;
        perm ~= repeat(2, c).array;
        perm ~= repeat(3, d).array;
        int[] ans;
        do {
          bool ok = true;
          foreach (i; 0 .. n - 1) {
            ok = ok && (abs(perm[i + 1] - perm[i]) == 1);
          }
          if (ok) {
            ans = perm.dup;
            break;
          }
        } while (perm.nextPermutation);
        const res = solveGreedy([a, b, c, d]);
        writeln([a, b, c, d], ": ", ans, " ", res);
        assert((ans != null) == (res != null));
      }
    }
  }

  try {
    for (; ; ) {
      auto A = new int[4];
      foreach (x; 0 .. 4) {
        A[x] = readInt();
      }
      const res = solveGreedy(A);
      if (res) {
        writeln("YES");
        foreach (i, x; res) {
          if (i > 0) write(" ");
          write(x);
        }
        writeln();
      } else {
        writeln("NO");
      }
    }
  } catch (EOFException e) {
  }
}


You are given two even integers $$$n$$$ and $$$m$$$. Your task is to find any binary matrix $$$a$$$ with $$$n$$$ rows and $$$m$$$ columns where every cell $$$(i,j)$$$ has exactly two neighbours with a different value than $$$a_{i,j}$$$.Two cells in the matrix are considered neighbours if and only if they share a side. More formally, the neighbours of cell $$$(x,y)$$$ are: $$$(x-1,y)$$$, $$$(x,y+1)$$$, $$$(x+1,y)$$$ and $$$(x,y-1)$$$.It can be proven that under the given constraints, an answer always exists.

Each test contains multiple test cases. The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The following lines contain the descriptions of the test cases. The only line of each test case contains two even integers $$$n$$$ and $$$m$$$ ($$$2 \le n,m \le 50$$$) — the height and width of the binary matrix, respectively.

For each test case, print $$$n$$$ lines, each of which contains $$$m$$$ numbers, equal to $$$0$$$ or $$$1$$$ — any binary matrix which satisfies the constraints described in the statement. It can be proven that under the given constraints, an answer always exists.

NoteWhite means $$$0$$$, black means $$$1$$$. The binary matrix from the first test caseThe binary matrix from the second test caseThe binary matrix from the third test case

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

void solve()
{
    static immutable string[] lookup = ["0110", "1001", "1001", "0110"];
    int n, m;
    readf!(" %s %s")(n, m);
    foreach (i; 0 .. n)
    {
        foreach (j; 0 .. m)
            writef!("%s ")(lookup[i%4][j%4]);
        writeln();
    }
}

void main()
{
    size_t TC = 1;
    TC = readln.strip.to!int;
    foreach (_; 0 .. TC)
        solve();
}


After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game «Call of Soldiers 3».The game has (m + 1) players and n types of soldiers in total. Players «Call of Soldiers 3» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each player has an army. Army of the i-th player can be described by non-negative integer xi. Consider binary representation of xi: if the j-th bit of number xi equal to one, then the army of the i-th player has soldiers of the j-th type. Fedor is the (m + 1)-th player of the game. He assume that two players can become friends if their armies differ in at most k types of soldiers (in other words, binary representations of the corresponding numbers differ in at most k bits). Help Fedor and count how many players can become his friends.

The first line contains three integers n, m, k (1 ≤ k ≤ n ≤ 20; 1 ≤ m ≤ 1000). The i-th of the next (m + 1) lines contains a single integer xi (1 ≤ xi ≤ 2n - 1), that describes the i-th player's army. We remind you that Fedor is the (m + 1)-th player.

Print a single integer — the number of Fedor's potential friends.

import std.stdio;

void main() {
  int n, m, k; readf(" %s %s %s", &n, &m, &k);
  auto mask = new int [m];
  for (int i = 0; i < m; i++) {
    readf(" %s", &mask[i]);
  }
  int cur; readf(" %s", &cur);
  int ans = 0;
  for (int i = 0; i < m; i++) {
    int count = 0;
    for (int j = 0; j < n; j++) {
      if ((mask[i] & (1 << j)) != (cur & (1 << j))) {
        count++;
      }
    }
    ans += count <= k;
  }
  writeln(ans);
}

// https://codeforces.com/problemset/problem/467/B
import std.stdio;
import std.conv;
import std.array;
import std.algorithm;

void main() {
    int[] words = readln.split.map!(x => x.to!int).array;
    int n = words[0];
    int m = words[1];
    int k = words[2];

    int[] armies;

    foreach(x; stdin.byLine)
        armies ~= x.to!int;

    int answer = 0;

    foreach(army; armies) {
        int xor = army^armies[m];
        int differ = 0;
        for(int bit = 0; bit < n; bit++)
            if((xor&(1<<bit)) > 0)
                differ += 1;
        if(differ <= k)
            answer += 1;
    }

    answer -= 1;
    answer.writeln;
}


Let's consider a k × k square, divided into unit squares. Please note that k ≥ 3 and is odd. We'll paint squares starting from the upper left square in the following order: first we move to the right, then down, then to the left, then up, then to the right again and so on. We finish moving in some direction in one of two cases: either we've reached the square's border or the square following after the next square is already painted. We finish painting at the moment when we cannot move in any direction and paint a square. The figure that consists of the painted squares is a spiral.   The figure shows examples of spirals for k = 3, 5, 7, 9.  You have an n × m table, each of its cells contains a number. Let's consider all possible spirals, formed by the table cells. It means that we consider all spirals of any size that don't go beyond the borders of the table. Let's find the sum of the numbers of the cells that form the spiral. You have to find the maximum of those values among all spirals.

The first line contains two integers n and m (3 ≤ n, m ≤ 500) — the sizes of the table. Each of the next n lines contains m space-separated integers: the j-th number in the i-th line aij ( - 1000 ≤ aij ≤ 1000) is the number recorded in the j-th cell of the i-th row of the table.

Print a single number — the maximum sum of numbers among all spirals.

NoteIn the first sample the spiral with maximum sum will cover all 1's of the table.In the second sample the spiral may cover only six 1's.

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

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

    auto arr = new int[][] (n+1);
    arr[0] = (0).repeat(m+1).array;
    foreach (i; 1 .. n+1) { arr[i] = 0 ~ readln.chomp.split.map!(to!int).array; }

    debug { arr.writeln; }

    auto sm = new int[][] (n+1, m+1);
    foreach (i; 1 .. n+1) {
        int smRw = 0;
        foreach (j; 1 .. m+1) {
            smRw += arr[i][j];
            sm[i][j] = sm[i-1][j] + smRw;
        }
    }

    debug { sm.each!writeln; }

    int getSm(int lux, int luy, int rdx, int rdy) {
        return sm[rdx][rdy] - sm[rdx][luy-1] - sm[lux-1][rdy] + sm[lux-1][luy-1];
    }

    auto score = new int[][] (n+1, m+1);
    foreach (i; 1 .. n+1) { score[i][] = arr[i][]; }

    auto chks = recurrence!"a[n-1] + 2"(3).until!(x => x > n || x > m);

    int ans = - (10 ^^ 9);
    foreach (v; chks) {
        foreach (i; 1 .. n+1 - v + 1) {
            foreach (j; 1 .. m+1 - v + 1) {
                score[i][j] = getSm(i, j, i + v - 1, j + v - 1) - score[i+1][j+1] - arr[i+1][j];
                ans = max(ans, score[i][j]);
            }
        }

        debug { writeln; score.each!writeln; }
    }

    ans.writeln;
}


Polycarp found a rectangular table consisting of $$$n$$$ rows and $$$m$$$ columns. He noticed that each cell of the table has its number, obtained by the following algorithm "by columns":   cells are numbered starting from one;  cells are numbered from left to right by columns, and inside each column from top to bottom;  number of each cell is an integer one greater than in the previous cell. For example, if $$$n = 3$$$ and $$$m = 5$$$, the table will be numbered as follows:$$$$$$ \begin{matrix} 1 & 4 & 7 & 10 & 13 \\ 2 & 5 & 8 & 11 & 14 \\ 3 & 6 & 9 & 12 & 15 \\ \end{matrix} $$$$$$However, Polycarp considers such numbering inconvenient. He likes the numbering "by rows":   cells are numbered starting from one;  cells are numbered from top to bottom by rows, and inside each row from left to right;  number of each cell is an integer one greater than the number of the previous cell. For example, if $$$n = 3$$$ and $$$m = 5$$$, then Polycarp likes the following table numbering: $$$$$$ \begin{matrix} 1 & 2 & 3 & 4 & 5 \\ 6 & 7 & 8 & 9 & 10 \\ 11 & 12 & 13 & 14 & 15 \\ \end{matrix} $$$$$$Polycarp doesn't have much time, so he asks you to find out what would be the cell number in the numbering "by rows", if in the numbering "by columns" the cell has the number $$$x$$$?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case consists of a single line containing three integers $$$n$$$, $$$m$$$, $$$x$$$ ($$$1 \le n, m \le 10^6$$$, $$$1 \le x \le n \cdot m$$$), where $$$n$$$ and $$$m$$$ are the number of rows and columns in the table, and $$$x$$$ is the cell number. Note that the numbers in some test cases do not fit into the $$$32$$$-bit integer type, so you must use at least the $$$64$$$-bit integer type of your programming language.

For each test case, output the cell number in the numbering "by rows".

import std.stdio;
void main()
{
    int q;
    readf!"%d"(q);
    foreach (_; 0 .. q)
    {
        long n, m, x;
        readf!" %d %d %d"(n, m, x);
        x--;
        long r = x % n, c = x / n;
        writeln(m * r + c + 1);
    }
}

// Vicfred
// https://codeforces.com/contest/1506/problem/A
// math
import std.stdio;

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

while(t--) {
    long n, m, x;
    readf("%s %s %s\n", &n, &m, &x);

    x -= 1;

    long row = x % n;
    long column = x / n;

    writefln("%s", (row*m) + column + 1);
}
}


You are given a string $$$s$$$ consisting of lowercase Latin letters and $$$q$$$ queries for this string.Recall that the substring $$$s[l; r]$$$ of the string $$$s$$$ is the string $$$s_l s_{l + 1} \dots s_r$$$. For example, the substrings of "codeforces" are "code", "force", "f", "for", but not "coder" and "top".There are two types of queries:   $$$1~ pos~ c$$$ ($$$1 \le pos \le |s|$$$, $$$c$$$ is lowercase Latin letter): replace $$$s_{pos}$$$ with $$$c$$$ (set $$$s_{pos} := c$$$);  $$$2~ l~ r$$$ ($$$1 \le l \le r \le |s|$$$): calculate the number of distinct characters in the substring $$$s[l; r]$$$.

The first line of the input contains one string $$$s$$$ consisting of no more than $$$10^5$$$ lowercase Latin letters. The second line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. The next $$$q$$$ lines contain queries, one per line. Each query is given in the format described in the problem statement. It is guaranteed that there is at least one query of the second type.

For each query of the second type print the answer for it — the number of distinct characters in the required substring in this query.

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

string FMT_F = "%.10f";

static 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; }
string RDR()() { return readln.chomp; }
T[] ARR(T = long)(in string str, T fix = 0) { auto r = str.split.to!(T[]); r[] += fix; return r; }
T[] RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[][] RDA2(T = long)(size_t n, T[] fix = []) { auto r = new T[][](n); foreach (i; 0..n) { r[i] = readln.chomp.split.to!(T[]); foreach (j, e; fix) r[i][j] += e; } return r; }
size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

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

long mod = 10^^9 + 7;
//long mod = 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; }

struct SegTree(T)
{
	T delegate(const(T), const(T)) f;
	T[] data;
	T init;
    this(T[] _data, T delegate(const(T), const(T)) _f, T _init)
    {
		f = _f; init = _init;
		size_t n = 1; while (n < _data.length) n *= 2; data.length = n*2-1;
		foreach (i; 0.._data.length) data[i+n-1] = _data[i];
		foreach (i; _data.length..n) data[i+n-1] = _init;
		foreach_reverse (i; 0..n-1) data[i] = f(data[i*2+1], data[i*2+2]);
	}
    T query(size_t l, size_t r) const
	{
        size_t n = (data.length+1) / 2; l += n-1; r += n-1; T res = f(init, data[l]);
        while (l < r)
		{
            if ((l & 1) == 0) res = f(res, data[l]);
            if ((r & 1) == 0) res = f(res, data[r-1]);
            l = l/2; r = (r-1)/2;
        }
        return res;
    }
	void update(size_t i, T v)
	{
		i += (data.length+1) / 2 - 1; data[i] = v;
		while (i != 0) { i = (i-1)/2; data[i] = f(data[i*2+1], data[i*2+2]); }
    }
}

void main()
{
	auto s = RD!string;

	auto a = new int[][](s.length, 26);
	foreach (i, c; s)
	{
		auto pos = c-'a';
		a[i][pos] = 1;
	}
	auto ini = new int[](26);
	auto st = SegTree!(int[])(a, (const(int[]) _a, const(int[]) _b){ auto c = _a.dup; c[] += _b[]; return c; }, ini);

	auto q = RD!int;
	long[] ans;
	foreach (i; 0..q)
	{
		auto num = RD!int;
		if (num == 1)
		{
			auto pos = RD!int-1;
			auto c = RD!string;
			auto tmp = new int[](26);
			tmp[c[0]-'a'] = 1;
			st.update(pos, tmp);
		}
		else
		{
			auto l = RD!int-1;
			auto r = RD!int;
			auto tmp = st.query(l, r);
			long cnt;
			foreach (e; tmp)
				if (e >= 1) ++cnt;
			ans ~= cnt;
		}
	}

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


Theofanis has a string $$$s_1 s_2 \dots s_n$$$ and a character $$$c$$$. He wants to make all characters of the string equal to $$$c$$$ using the minimum number of operations.In one operation he can choose a number $$$x$$$ ($$$1 \le x \le n$$$) and for every position $$$i$$$, where $$$i$$$ is not divisible by $$$x$$$, replace $$$s_i$$$ with $$$c$$$. Find the minimum number of operations required to make all the characters equal to $$$c$$$ and the $$$x$$$-s that he should use in his operations.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains the integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$) and a lowercase Latin letter $$$c$$$ — the length of the string $$$s$$$ and the character the resulting string should consist of. The second line of each test case contains a string $$$s$$$ of lowercase Latin letters — the initial string. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case, firstly print one integer $$$m$$$ — the minimum number of operations required to make all the characters equal to $$$c$$$. Next, print $$$m$$$ integers $$$x_1, x_2, \dots, x_m$$$ ($$$1 \le x_j \le n$$$) — the $$$x$$$-s that should be used in the order they are given. It can be proved that under given constraints, an answer always exists. If there are multiple answers, print any.

NoteLet's describe what happens in the third test case:   $$$x_1 = 2$$$: we choose all positions that are not divisible by $$$2$$$ and replace them, i. e. bzyx $$$\rightarrow$$$ bzbx;  $$$x_2 = 3$$$: we choose all positions that are not divisible by $$$3$$$ and replace them, i. e. bzbx $$$\rightarrow$$$ bbbb.

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

void solve(){
    ll n = scan;
    dchar c = scan!(dchar);
    auto word = scan!(dchar[]);
    ll cnt = 0;
    for(int i = 0; i < n; ++i){
        cnt += (word[i] == c);
    }
    if(cnt == n){
        writeln(0);
        writeln;
        return;
    }
    for(ll k = 1; k <= n; ++k){
        bool f = 1;
        for(ll m = k-1; m < n; m += k){
            if(word[to!int(m)] != c){ f = 0; break; }
        }
        if(f){
            writeln(1);
            writeln(k);
            return;
        }
    }
    writeln(2);
    writeln(n, " ", n-1);
}

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

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

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

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        auto params = readln.split();
        int n = to!int(params[0]);
        string s = readln.strip();
        if (to!string(uniq(s)) == params[1]) {
            writeln(0);
            continue;
        }
        else {
            Nullable!(ulong) oneind;
            foreach(ind, el; s) {
                if ((el == to!char(params[1])) && (2*(ind + 1) > n))
                    oneind = ind;
            }
            if (!oneind.isNull) {
                writeln(1);
                writeln(oneind + 1);
            }
            else {
                writeln(2);
                writeln(n-1, ' ', n);
            }
        }
    }
}

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

void solve(){
    ll n = scan;
    dchar c = scan!(dchar);
    auto word = scan!(dchar[]);
    ll cnt = 0;
    for(int i = 0; i < n; ++i){
        cnt += (word[i] == c);
    }
    if(cnt == n){
        writeln(0);
        writeln;
        return;
    }
    for(ll k = 1; k < n; ++k){
        bool f = 1;
        for(ll m = k-1; m < n; m += k){
            if(word[to!int(m)] != c){ f = 0; break; }
        }
        if(f){
            writeln(1);
            writeln(k);
            return;
        }
    }
    writeln(2);
    writeln(n, " ", n-1);
}

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

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

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

void solve(){
    ll n = scan;
    dchar c = scan!(dchar);
    auto word = scan!(dchar[]);
    ll cnt = 0;
    for(int i = 0; i < n; ++i){
        cnt += (word[i] == c);
    }
    if(cnt == n){
        writeln(0);
        writeln;
        return;
    }
    for(ll k = 1; k < n; ++k){
        ll seen = 0;
        for(ll j = k; j < n; j += k){
            seen += (word[to!int(j)] == c);
        }
        if(seen == cnt){
            writeln(1);
            writeln(k);
            return;
        }
        if(k*cnt > n){
            break;
        }
    }
    writeln(2);
    writeln(n, " ", n-1);
}

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

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

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

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        auto params = readln.split();
        int n = to!int(params[0]);
        string s = readln.strip();
        if (to!string(uniq(s)) == params[1]) {
            writeln(0);
            continue;
        }
        else {
            Nullable!(ulong) oneind;
            foreach(ind, el; s) {
                if ((el == to!char(params[1])) && (2*(ind + 1) > n))
                    oneind = ind;
            }
            if (!oneind.isNull) {
                writeln(1);
                writeln(oneind);
            }
            else {
                writeln(2);
                writeln(n-1, ' ', n);
            }
        }
    }
}

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

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        auto params = readln.split();
        int n = to!int(params[0]);
        string s = readln.strip();
        if (to!string(uniq(s)) == params[1]) {
            writeln(0);
            continue;
        }
        else {
            if (s[n - 1] == to!char(params[1])) {
                writeln(1);
                writeln(n);
            }
            else {
                if (s[n - 2] == to!char(params[1])) {
                    if (to!string(uniq(s[0..n - 2])) == params[1])
                    {
                        writeln(1);
                        writeln(n - 1);
                    }
                    else {
                        writeln(2);
                        writeln(n-1, ' ', n);
                    }
                }
                else {
                    writeln(2);
                    writeln(n-1, ' ', n);
                }
            }
        }
    }
}

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

void main()
{
    int t;
    scanf("%d", &t);
    getchar();
    foreach(_; 0..t)
    {
        auto params = readln.split();
        int n = to!int(params[0]);
        string s = readln.strip();
        if (to!string(uniq(s)) == params[1]) {
            writeln(0);
            continue;
        }
        else {
            if (s[n - 1] == to!char(params[1])) {
                writeln(1);
                writeln(n);
            }
            else {
                writeln(2);
                writeln(n-1, ' ', n);
            }
        }
    }
}


You are given three integers $$$a$$$, $$$b$$$, and $$$c$$$. Determine if one of them is the sum of the other two.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 9261$$$) — the number of test cases. The description of each test case consists of three integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$0 \leq a, b, c \leq 20$$$).

For each test case, output "YES" if one of the numbers is the sum of the other two, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

NoteIn the first test case, $$$1 + 3 = 4$$$.In the second test case, none of the numbers is the sum of the other two.In the third test case, $$$9 + 11 = 20$$$.

import std;

void main()
{
    int w;
    scanf("%d\n", &w);
    foreach(_; 0..w)
    {
        int a,b,c;
        scanf("%d %d %d\n", &a, &b, &c);
        int max_el = max(a,b,c);
        if (a+b+c - max_el == max_el)
            writeln("YES");
        else
            writeln("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; }

void solve() {
    auto s = readarray!int;
    bool f() {
        int sum = s.reduce!"a + b";
        for (int i = 0; i < 3; i++) {
            if (sum - s[i] == s[i]) {
                return true;
            }
        }
        return false;
    }
    writeln(f() ? "YES" : "NO");
}

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

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    long a, b, c;
    readf!" %d %d %d "(a, b, c);
    writeln(a + b == c || a + c == b || b + c == a ? "YES" : "NO");
  }
}


Alperen has two strings, $$$s$$$ and $$$t$$$ which are both initially equal to "a". He will perform $$$q$$$ operations of two types on the given strings:  $$$1 \;\; k \;\; x$$$ — Append the string $$$x$$$ exactly $$$k$$$ times at the end of string $$$s$$$. In other words, $$$s := s + \underbrace{x + \dots + x}_{k \text{ times}}$$$.  $$$2 \;\; k \;\; x$$$ — Append the string $$$x$$$ exactly $$$k$$$ times at the end of string $$$t$$$. In other words, $$$t := t + \underbrace{x + \dots + x}_{k \text{ times}}$$$. After each operation, determine if it is possible to rearrange the characters of $$$s$$$ and $$$t$$$ such that $$$s$$$ is lexicographically smaller$$$^{\dagger}$$$ than $$$t$$$.Note that the strings change after performing each operation and don't go back to their initial states.$$$^{\dagger}$$$ Simply speaking, the lexicographical order is the order in which words are listed in a dictionary. A formal definition is as follows: string $$$p$$$ is lexicographically smaller than string $$$q$$$ if there exists a position $$$i$$$ such that $$$p_i < q_i$$$, and for all $$$j < i$$$, $$$p_j = q_j$$$. If no such $$$i$$$ exists, then $$$p$$$ is lexicographically smaller than $$$q$$$ if the length of $$$p$$$ is less than the length of $$$q$$$. For example, $$$\texttt{abdc} < \texttt{abe}$$$ and $$$\texttt{abc} < \texttt{abcd}$$$, where we write $$$p < q$$$ if $$$p$$$ is lexicographically smaller than $$$q$$$.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$q$$$ $$$(1 \leq q \leq 10^5)$$$ — the number of operations Alperen will perform. Then $$$q$$$ lines follow, each containing two positive integers $$$d$$$ and $$$k$$$ ($$$1 \leq d \leq 2$$$; $$$1 \leq k \leq 10^5$$$) and a non-empty string $$$x$$$ consisting of lowercase English letters — the type of the operation, the number of times we will append string $$$x$$$ and the string we need to append respectively. It is guaranteed that the sum of $$$q$$$ over all test cases doesn't exceed $$$10^5$$$ and that the sum of lengths of all strings $$$x$$$ in the input doesn't exceed $$$5 \cdot 10^5$$$.

For each operation, output "YES", if it is possible to arrange the elements in both strings in such a way that $$$s$$$ is lexicographically smaller than $$$t$$$ and "NO" otherwise.

3

5

2 1 aa

1 2 a

2 3 a

1 2 b

2 3 abca

2

1 5 mihai

2 2 buiucani

3

1 5 b

2 3 a

2 4 paiu

NoteIn the first test case, the strings are initially $$$s = $$$ "a" and $$$t = $$$ "a". After the first operation the string $$$t$$$ becomes "aaa". Since "a" is already lexicographically smaller than "aaa", the answer for this operation should be "YES".After the second operation string $$$s$$$ becomes "aaa", and since $$$t$$$ is also equal to "aaa", we can't arrange $$$s$$$ in any way such that it is lexicographically smaller than $$$t$$$, so the answer is "NO".After the third operation string $$$t$$$ becomes "aaaaaa" and $$$s$$$ is already lexicographically smaller than it so the answer is "YES".After the fourth operation $$$s$$$ becomes "aaabb" and there is no way to make it lexicographically smaller than "aaaaaa" so the answer is "NO".After the fifth operation the string $$$t$$$ becomes "aaaaaaabcaabcaabca", and we can rearrange the strings to: "bbaaa" and "caaaaaabcaabcaabaa" so that $$$s$$$ is lexicographically smaller than $$$t$$$, so we should answer "YES".

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

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    long q, d, k;
    string x;
    readf!" %d "(q);
    long[26] ft, fs;
    long totals = 1, totalt = 1;
    ft[0] = 1;
    fs[0] = 1;
    foreach (_ ; 0 .. q) {
      auto tmp = readln.splitter.array;
      d = tmp[0].to!long;
      k = tmp[1].to!long;
      x = tmp[2].strip;
      if (d == 1) {
        foreach (ch ; x) {
          fs[cast(size_t)(ch - 'a')] += k;
          totals += k;
        }
      } else {
        foreach (ch ; x) {
          ft[cast(size_t)(ch - 'a')] += k;
          totalt += k;
        }
      }

      if (totalt != ft[0]) {
        writeln("YES");
        continue;
      }

      if (totals == fs[0]) {
        writeln(totals < totalt ? "YES" : "NO");
        continue;
      }

      writeln("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; }

void solve() {
    int Q = read!int;
    long[] s = new long[26], t = new long[26];
    s[0] = 1;
    t[0] = 1;

    bool cmp(long[] x, long[] y) {
        for (int i = 25; i >= 0; i--) {
            for (int j = 0; j < i; j++) {
                if (y[i] > 0 && x[j] > 0) return true;
            }
        }
        if (x.count!(c => c > 0) == 1 && y.count!(c => c > 0) == 1) {
            int i = 26 - x.find!(c => c > 0).length;
            int j = 26 - y.find!(c => c > 0).length;
            if (i == j) {
                return x[j] < y[j];
            }
        }
        return false;
    }

    foreach (q; 0 .. Q) {
        int d, k;
        string x;
        readf("%d %d %s\n", &d, &k, &x);
        if (d == 1) {
            foreach (c; x) {
                int i = cast(int)(c - 'a');
                s[i] += k;
            }
            writeln(cmp(s, t) ? "YES" : "NO");
        } else {
            assert(d == 2);
            foreach (c; x) {
                int i = cast(int)(c - 'a');
                t[i] += k;
            }
            writeln(cmp(s, t) ? "YES" : "NO");
        }
    }
}

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