C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following:  if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem);  otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza
OutputCopyYES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO

import static java.lang.Math.max;

import static java.lang.Math.min;

import static java.lang.Math.abs;

import java.util.*;

import java.io.*;

import java.math.*;

public class C_Perfect_Keyboard {

    static long mod = Long.MAX_VALUE;

    static OutputStream outputStream = System.out;

    static PrintWriter out = new PrintWriter(outputStream);

    static FastReader f = new FastReader();

    public static void main(String[] args) {

        int t = f.nextInt();

        while(t-- > 0){

            solve();

        }

        out.close();

    }

    public static void solve() {

        String s = f.nextLine();

        int n = s.length();

        if(n == 1) {

            out.println("YES");

            for(int i = 0; i < 26; i++) {

                out.print((char)('a'+i));

            }

            out.println();

            return;

        }

        ArrayList<ArrayList<Integer>> adj = new ArrayList<>();

        for(int i = 0; i < 26; i++) {

            adj.add(new ArrayList<>());

        }

        int deg[] = new int[26];

        for(int i = 1; i < n; i++) {

            int u = s.charAt(i)-'a';

            int v = s.charAt(i-1)-'a';

            boolean flag = true;

            for(int x: adj.get(u)) {

                if(x == v) {

                    flag = false;

                    break;

                }

            }

            if(flag) {

                adj.get(u).add(v);

                adj.get(v).add(u);

                deg[u]++;

                deg[v]++;

                if(deg[u] > 2 || deg[v] > 2) {

                    out.println("NO");

                    return;

                }

            }

        }

        if(detectCycle(adj)) {

            out.println("NO");

            return;

        }

        boolean taken[] = new boolean[26];

        StringBuilder sb = new StringBuilder();

        for(int i = 0; i < 26; i++) {

            if(deg[i] == 1) {

                dfs(adj, i, taken, sb);

                break;

            }

        }

        for(int i = 0; i < 26; i++) {

            if(!taken[i]) {

                sb.append((char)('a'+i));

            }

        }

        out.println("YES");

        out.println(sb);

    }

    public static void dfs(ArrayList<ArrayList<Integer>> adj, int s, boolean taken[], StringBuilder sb) {

        taken[s] = true;

        sb.append((char)('a'+s));

        for(int v: adj.get(s)) {

            if(!taken[v]) {

                dfs(adj, v, taken, sb);

            }

        }

    }

    public static boolean detectCycle(ArrayList<ArrayList<Integer>> adj) {

        boolean visited[] = new boolean[26];

        for(int i = 0; i < 26; i++) {

            if(!visited[i]) {

                if(dfs(adj, i, -1, visited)) {

                    return true;

                }

            }

        }

        return false;

    }

    public static boolean dfs(ArrayList<ArrayList<Integer>> adj, int u, int p, boolean visited[]) {

        visited[u] = true;

        for(int v: adj.get(u)) {

            if(!visited[v]) {

                if(dfs(adj, v, u, visited)) {

                    return true;

                }

            } else if(v != p) {

                return true;

            }

        }

        return false;

    }

    // Sort an array

    public static void sort(int arr[]) {

        ArrayList<Integer> al = new ArrayList<>();

        for(int i: arr) {

            al.add(i);

        }

        Collections.sort(al);

        for(int i = 0; i < arr.length; i++) {

            arr[i] = al.get(i);

        }

    }

    // Find all divisors of n

    public static void allDivisors(int n) {

        for(int i = 1; i*i <= n; i++) {

            if(n%i == 0) {

                System.out.println(i + " ");

                if(i != n/i) {

                    System.out.println(n/i + " ");

                }

            }

        }

    }

    // Check if n is prime or not

    public static boolean isPrime(int n) {

        if(n < 1) return false;

        if(n == 2 || n == 3) return true;

        if(n % 2 == 0 || n % 3 == 0) return false;

        for(int i = 5; i*i <= n; i += 6) {

            if(n % i == 0 || n % (i+2) == 0) {

                return false;

            }

        }

        return true;

    }

    // Find gcd of a and b

    public static long gcd(long a, long b) {

        long dividend = a > b ? a : b;

        long divisor =  a < b ? a : b;

        while(divisor > 0) {

            long reminder = dividend % divisor;

            dividend = divisor;

            divisor = reminder;

        }

        return dividend;

    }

    // Find lcm of a and b

    public static long lcm(long a, long b) {

        long lcm = gcd(a, b);

        long hcf = (a * b) / lcm;

        return hcf;

    }

    // Find factorial in O(n) time

    public static long fact(int n) {

        long res = 1;

        for(int i = 2; i <= n; i++) {

            res = res * i;

        }

        return res;

    }

    // Find power in O(logb) time

    public static long power(long a, long b) {

        long res = 1;

        while(b > 0) {

            if((b&1) == 1) {

                res = (res * a)%mod;

            }

            a = (a * a)%mod;

            b >>= 1;

        }

        return res;

    }

    // Find nCr

    public static long nCr(int n, int r) {

        if(r < 0 || r > n) {

            return 0;

        }

        long ans = fact(n) / (fact(r) * fact(n-r));

        return ans;

    }

    // Find nPr

    public static long nPr(int n, int r) {

        if(r < 0 || r > n) {

            return 0;

        }

        long ans = fact(n) / fact(r);

        return ans;

    }

    // sort all characters of a string

    public static String sortString(String inputString) {

        char tempArray[] = inputString.toCharArray();

        Arrays.sort(tempArray);

        return new String(tempArray);

    }

    // User defined class for fast I/O

    static class FastReader {

        BufferedReader br;

        StringTokenizer st;

        public FastReader() {

            br = new BufferedReader(new InputStreamReader(System.in));

        }

        String next() {

            while (st == null || !st.hasMoreElements()) {

                try {

                    st = new StringTokenizer(br.readLine());

                }

                catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        boolean hasNext() {

            if (st != null && st.hasMoreTokens()) {

                return true;

            }

            String tmp;

            try {

                br.mark(1000);

                tmp = br.readLine();

                if (tmp == null) {

                    return false;

                }

                br.reset();

            } catch (IOException e) {

                return false;

            }

            return true;

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

        float nextFloat() {

            return Float.parseFloat(next());

        }

        boolean nextBoolean() {

            return Boolean.parseBoolean(next());

        }

        String nextLine() {

            String str = "";

            try {

                str = br.readLine();

            }

            catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

        int[] nextArray(int n) {

            int[] a = new int[n];

            for(int i=0; i<n; i++) {

                a[i] = nextInt();

            }

            return a;

        }

    }

}

/**

Dec  Char                           Dec  Char     Dec  Char     Dec  Char

---------                           ---------     ---------     ----------

  0  NUL (null)                      32  SPACE     64  @         96  `

  1  SOH (start of heading)          33  !         65  A         97  a

  2  STX (start of text)             34  "         66  B         98  b

  3  ETX (end of text)               35  #         67  C         99  c

  4  EOT (end of transmission)       36  $         68  D        100  d

  5  ENQ (enquiry)                   37  %         69  E        101  e

  6  ACK (acknowledge)               38  &         70  F        102  f

  7  BEL (bell)                      39  '         71  G        103  g

  8  BS  (backspace)                 40  (         72  H        104  h

  9  TAB (horizontal tab)            41  )         73  I        105  i

 10  LF  (NL line feed, new line)    42  *         74  J        106  j

 11  VT  (vertical tab)              43  +         75  K        107  k

 12  FF  (NP form feed, new page)    44  ,         76  L        108  l

 13  CR  (carriage return)           45  -         77  M        109  m

 14  SO  (shift out)                 46  .         78  N        110  n

 15  SI  (shift in)                  47  /         79  O        111  o

 16  DLE (data link escape)          48  0         80  P        112  p

 17  DC1 (device control 1)          49  1         81  Q        113  q

 18  DC2 (device control 2)          50  2         82  R        114  r

 19  DC3 (device control 3)          51  3         83  S        115  s

 20  DC4 (device control 4)          52  4         84  T        116  t

 21  NAK (negative acknowledge)      53  5         85  U        117  u

 22  SYN (synchronous idle)          54  6         86  V        118  v

 23  ETB (end of trans. block)       55  7         87  W        119  w

 24  CAN (cancel)                    56  8         88  X        120  x

 25  EM  (end of medium)             57  9         89  Y        121  y

 26  SUB (substitute)                58  :         90  Z        122  z

 27  ESC (escape)                    59  ;         91  [        123  {

 28  FS  (file separator)            60  <         92  \        124  |

 29  GS  (group separator)           61  =         93  ]        125  }

 30  RS  (record separator)          62  >         94  ^        126  ~

 31  US  (unit separator)            63  ?         95  _        127  DEL

 */

// (a/b)%mod == (a * moduloInverse(b)) % mod;

// moduloInverse(b) = power(b, mod-2);


E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3
3 1 2
7 1 4
OutputCopy4
InputCopy4
2 4 1 3
5 9 8 3
OutputCopy3
InputCopy6
3 5 1 6 2 4
9 1 9 9 1 9
OutputCopy2

import java.util.*;
import java.io.*;

public class Main {
	public static void main(String args[]) {new Main().run();}

	FastReader in = new FastReader();
	PrintWriter out = new PrintWriter(System.out);
	void run(){
		work();
		out.flush();
	}
	long mod=998244353;
	long gcd(long a,long b) {
		return a==0?b:gcd(b%a,a);
	}
	void work() {
		int n=ni();
		int[] A=nia(n);
		long[] W=na(n);
		long[] sum=new long[n];
		for(int i=0;i<n;i++) {
			sum[A[i]]=W[i];
		}
		for(int i=1;i<n;i++) {
			sum[i]+=sum[i-1];
		}
		Node root=new Node();
		for(int i=0;i<n;i++) {
			update(root,0,n-1,i,i,sum[i]);
		}
		long ret=Long.MAX_VALUE;
		long s=0;
		for(int i=0;i<n-1;i++) {
			int node=A[i];
			long w=W[i];
			s+=w;//前缀空集
			update(root,0,n-1,node,n-1,-w);
			if(node!=0)update(root,0,n-1,0,node-1,w);
			ret=Math.min(ret, root.min);
			ret=Math.min(ret, s);
		}
		out.println(ret);
	}

	void u2(Node node,long v) {
		node.min+=v;
		node.lazy+=v;
	}
	void updatelazy(Node node) {
		u2(getLnode(node),node.lazy);
		u2(getRnode(node),node.lazy);
		node.lazy=0;
	}
	private void update(Node node, int l, int r, int s,int e,long v) {
		if(l>=s&&r<=e) {
			node.min+=v;
			node.lazy+=v;
			return;
		}
		updatelazy(node);
		int m=l+(r-l)/2;
		if(m>=s) {
			update(getLnode(node),l,m,s,e,v);
		}
		if(m+1<=e) {
			update(getRnode(node),m+1,r,s,e,v);
		}
		node.min=Math.min(getLnode(node).min,getRnode(node).min);//左右节点可能有lazy标记
	}

	private Node getLnode(Node node) {
		if(node.lnode==null)node.lnode=new Node();
		return node.lnode;
	}
	private Node getRnode(Node node) {
		if(node.rnode==null)node.rnode=new Node();
		return node.rnode;
	}
	class Node{
		Node lnode,rnode;
		long lazy;
		long min;
	}

	//input
	private ArrayList<Integer>[] ng(int n, int m) {
		ArrayList<Integer>[] graph=(ArrayList<Integer>[])new ArrayList[n];
		for(int i=0;i<n;i++) {
			graph[i]=new ArrayList<>();
		}
		for(int i=1;i<=m;i++) {
			int s=in.nextInt()-1,e=in.nextInt()-1;
			graph[s].add(e);
			graph[e].add(s);
		}
		return graph;
	}

	private int ni() {
		return in.nextInt();
	}

	private long nl() {
		return in.nextLong();
	}

	private long[] na(int n) {
		long[] A=new long[n];
		for(int i=0;i<n;i++) {
			A[i]=in.nextLong();
		}
		return A;
	}
	private int[] nia(int n) {
		int[] A=new int[n];
		for(int i=0;i<n;i++) {
			A[i]=in.nextInt()-1;//
		}
		return A;
	}
}

class FastReader
{
	BufferedReader br;
	StringTokenizer st;

	public FastReader()
	{
		br=new BufferedReader(new InputStreamReader(System.in));
	}

	public String next()
	{
		while(st==null || !st.hasMoreElements())//回车，空行情况
		{
			try {
				st = new StringTokenizer(br.readLine());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return st.nextToken();
	}

	public int nextInt()
	{
		return Integer.parseInt(next());
	}

	public long nextLong()
	{
		return Long.parseLong(next());
	}
}


A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4
aaa
bbb
ccc
abc
bca
bca
aabb
bbaa
baba
imi
mii
iim
OutputCopyNO
YES
YES
NO
NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb.

import java.io.BufferedReader;

import java.io.InputStreamReader;

public class App

{

    public static void main(String[] args) throws Exception

    {

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        int t = Integer.parseInt(reader.readLine());

        while(t > 0)

        {

            System.out.println(solve(reader) ? "YES" : "NO");

            t -= 1;

        }

        reader.close();

    }

    public static boolean solve(BufferedReader reader) throws Exception

    {

        String a = reader.readLine();

        String b = reader.readLine();

        String c = reader.readLine();

        int n = a.length();

        for (int i = 0; i < n; i++)

        {

            char currentA = a.charAt(i);

            char currentB = b.charAt(i);

            char currentC = c.charAt(i);

            if(currentC != currentA && currentC != currentB)

            {

                return false;

            }

        }

        return true;

    }

}


B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string:   Pick an integer kk, (1≤k≤n1≤k≤n).  For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through:   qwer (original string)  wqer (after reversing the first substring of length 22)  weqr (after reversing the second substring of length 22)  werq (after reversing the last substring of length 22)  Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds:   aa is a prefix of bb, but a≠ba≠b;  in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6
4
abab
6
qwerty
5
aaaaa
6
alaska
9
lfpbavjsm
1
p
OutputCopyabab
1
ertyqw
3
aaaaa
1
aksala
6
avjsmbpfl
5
p
1
NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows :   for k=1k=1 : abab  for k=2k=2 : baba  for k=3k=3 : abab  for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11.

import java.util.*;

import java.lang.*;

import java.io.*;

public class Solution {

    public static void main(String[] args) throws IOException {

        Reader.init(System.in);

        BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));

        int t = Reader.nextInt();

//        int t = 1;

        while(t-->0) {

            int n = Reader.nextInt();

            String s = Reader.next();

            ArrayList<String> arr = new ArrayList<>();

            for(int k = 1;k<=n;k++){

                int len = n-k-1;

                if(len%2==0){

                    String c = s.substring(k-1) + s.substring(0,k-1);

                    arr.add(c);

                }

                else{

                    StringBuilder temp = new StringBuilder(s.substring(0,k-1));

                    temp.reverse();

                    String c = s.substring(k-1) + temp.toString();

                    arr.add(c);

                }

            }

            ArrayList<String> copy = new ArrayList<>(arr);

            Collections.sort(arr);

            output.write(arr.get(0)+"\n");

            for(int i = 0;i<copy.size();i++){

                if(copy.get(i).equals(arr.get(0))){

                    output.write(i+1+"\n");

                    break;

                }

            }

        }

        output.close();

    }

//abab

//1

//ertyqw

//3

//aaaaa

//1

//aksala

//6

//avjsmbpfl

//5

//p

//1

    public static long[] factorial(int n){

        long[] factorials = new long[n+1];

        factorials[1] = 1;

        for(int i = 2;i<=n;i++){

            factorials[i] = (factorials[i-1]*i)%((int)1e9+7);

        }

        return factorials;

    }

    public static long numOfBits(long n){

        long ans = 0;

        while(n>0){

            n = n & (n-1);

            ans++;

        }

        return ans;

    }

    public static long ceilOfFraction(long x, long y){

        // ceil using integer division: ceil(x/y) = (x+y-1)/y

        // using double may go out of range.

        return (x+y-1)/y;

    }

    public static int power(int x, int y, int p) {

        int res = 1;

        x = x % p;

        while (y > 0) {

            if (y % 2 == 1) res = (res * x) % p;

            y = y >> 1;

            x = (x * x) % p;

        }

        return res;

    }

    // Returns n^(-1) mod p

    public static int modInverse(int n, int p) {

        return power(n, p - 2, p);

    }

    // Returns nCr % p using Fermat's

    // little theorem.

    public static int nCrModPFermat(int n, int r, int p) {

        if (n<r) return 0;

        if (r == 0) return 1;

        // Fill factorial array so that we

        // can find all factorial of r, n

        // and n-r

        int[] fac = new int[n + 1];

        fac[0] = 1;

        for (int i = 1; i <= n; i++)

            fac[i] = fac[i - 1] * i % p;

        return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p;

    }

    public static long ncr(long n, long r) {

        long p = 1, k = 1;

        if (n - r < r) {

            r = n - r;

        }

        if (r != 0) {

            while (r > 0) {

                p *= n;

                k *= r;

                long m = gcd(p, k);

                p /= m;

                k /= m;

                n--;

                r--;

            }

        } else {

            p = 1;

        }

        return p;

    }

    public static boolean isPrime(long n){

        if (n <= 1) return false;

        if (n <= 3) return true;

        if (n % 2 == 0 || n % 3 == 0) return false;

        for (int i = 5; (long) i * i <= n; i = i + 6){

            if (n % i == 0 || n % (i + 2) == 0) {

                return false;

            }

        }

        return true;

    }

    public static int powOf2JustSmallerThanN(int n) {

        n |= n >> 1;

        n |= n >> 2;

        n |= n >> 4;

        n |= n >> 8;

        n |= n >> 16;

        return n ^ (n >> 1);

    }

    public static int mergeSortAndCount(int[] arr, int l, int r) {

        int count = 0;

        if (l < r) {

            int m = (l + r) / 2;

            count += mergeSortAndCount(arr, l, m);

            count += mergeSortAndCount(arr, m + 1, r);

            count += mergeAndCount(arr, l, m, r);

        }

        return count;

    }

    public static int mergeAndCount(int[] arr, int l, int m, int r) {

        int[] left = Arrays.copyOfRange(arr, l, m + 1);

        int[] right = Arrays.copyOfRange(arr, m + 1, r + 1);

        int i = 0, j = 0, k = l, swaps = 0;

        while (i < left.length && j < right.length) {

            if (left[i] <= right[j])

                arr[k++] = left[i++];

            else {

                arr[k++] = right[j++];

                swaps += (m + 1) - (l + i);

            }

        }

        while (i < left.length)

            arr[k++] = left[i++];

        while (j < right.length)

            arr[k++] = right[j++];

        return swaps;

    }

    public static void reverseArray(int[] arr,int start, int end) {

        int temp;

        while (start < end) {

            temp = arr[start];

            arr[start] = arr[end];

            arr[end] = temp;

            start++;

            end--;

        }

    }

    public static long gcd(long a, long b){

        if(a==0){

            return b;

        }

        return gcd(b%a,a);

    }

    public static long lcm(long a, long b){

        if(a>b) return a/gcd(b,a) * b;

        return b/gcd(a,b) * a;

    }

    public static long largeExponentMod(long x,long y,long mod){

        // computing (x^y) % mod

        x%=mod;

        long ans = 1;

        while(y>0){

            if((y&1)==1){

                ans = (ans*x)%mod;

            }

            x = (x*x)%mod;

            y = y >> 1;

        }

        return ans;

    }

    public static boolean[] numOfPrimesInRange(long L, long R){

        boolean[] isPrime = new boolean[(int) (R-L+1)];

        Arrays.fill(isPrime,true);

        long lim = (long) Math.sqrt(R);

        for (long i = 2; i <= lim; i++){

            for (long j = Math.max(i * i, (L + i - 1) / i * i); j <= R; j += i){

                isPrime[(int) (j - L)] = false;

            }

        }

        if (L == 1) isPrime[0] = false;

        return isPrime;

    }

    public static ArrayList<Long> primeFactors(long n){

        ArrayList<Long> factorization = new ArrayList<>();

        if(n%2==0){

            factorization.add(2L);

        }

        while(n%2==0){

            n/=2;

        }

        if(n%3==0){

            factorization.add(3L);

        }

        while(n%3==0){

            n/=3;

        }

        if(n%5==0){

            factorization.add(5L);

        }

        while(n%5==0){

//            factorization.add(5L);

            n/=5;

        }

        int[] increments = {4, 2, 4, 2, 4, 6, 2, 6};

        int i = 0;

        for (long d = 7; d * d <= n; d += increments[i++]) {

            if(n%d==0){

                factorization.add(d);

            }

            while (n % d == 0) {

//                factorization.add(d);

                n /= d;

            }

            if (i == 8)

                i = 0;

        }

        if (n > 1)

            factorization.add(n);

        return factorization;

    }

}

class DSU {

    int[] size, parent;

    int n;

    public DSU(int n){

        this.n = n;

        size = new int[n];

        parent = new int[n];

        for(int i = 0;i<n;i++){

            parent[i] = i;

            size[i] = 1;

        }

    }

    public int find(int u){

        if(parent[u]==u){

            return u;

        }

        return parent[u] = find(parent[u]);

    }

    public void merge(int u, int v){

        u = find(u);

        v = find(v);

        if(u!=v){

            if(size[u]>size[v]){

                parent[v] = u;

                size[u] += size[v];

            }

            else{

                parent[u] = v;

                size[v] += size[u];

            }

        }

    }

}

class Reader {

    static BufferedReader reader;

    static StringTokenizer tokenizer;

    /** call this method to initialize reader for InputStream */

    static void init(InputStream input) {

        reader = new BufferedReader(

                new InputStreamReader(input) );

        tokenizer = new StringTokenizer("");

    }

    /** get next word */

    static String next() throws IOException {

        while ( ! tokenizer.hasMoreTokens() ) {

            //TODO add check for eof if necessary

            tokenizer = new StringTokenizer(

                    reader.readLine() );

        }

        return tokenizer.nextToken();

    }

    static String nextLine() throws IOException {

        return reader.readLine();

    }

    static int nextInt() throws IOException {

        return Integer.parseInt( next() );

    }

    static long nextLong() throws IOException{

        return Long.parseLong(next() );

    }

    static double nextDouble() throws IOException {

        return Double.parseDouble( next() );

    }

}


B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3
1
7
4
1 1 3 5
6
3 2 1 5 6 4
OutputCopy7
1 5 1 3
2 4 6 1 3 5

// package com.company.Codeforces;

import java.util.*;

import java.lang.*;

import java.io.*;

public class aaaaaa

{

    public static void solve() {

        int n = sc.nextInt();

        int [] arr = sc.nextIntArray(n);

        Arrays.sort(arr);

        StringBuilder sb = new StringBuilder();

        for(int i=n-1; i>=0; i--){

            sb.append(arr[i]).append(" ");

        }

        out.println(sb.toString());

    }

    static PrintWriter out;

    static StringBuilder str;

    static Scanner sc;

    public static void main (String[] args) throws java.lang.Exception

    {

        sc = new Scanner();

        str = new StringBuilder();

        out = new PrintWriter(System.out);

        int t = sc.nextInt();

//        int t = 1;

        while(t-->0){

            solve();

//            str.append('\n');

        }

//        out.println(str);

        out.close();

    }

    private static long power(long a, long b) {

        long res = 1;

        while (b > 0) {

            if ((b & 1)==1)

                res = res * a;

            a = a * a;

            b >>= 1;

        }

        return res;

    }

    private static long power(long a, long b, long m) {

        a %= m;

        long res = 1;

        while (b > 0) {

            if ((b & 1)==1)

                res = res * a % m;

            a = a * a % m;

            b >>= 1;

        }

        return res;

    }

    private static long lcm(long a, long b) {

        return a * b / gcd(a, b);

    }

    private static long gcd(long a, long b) {

        return (b == 0) ? a : gcd(b, a % b);

    }

    static class Scanner {

        BufferedReader br;

        StringTokenizer st;

        public Scanner() {

            br = new BufferedReader(new

                    InputStreamReader(System.in));

/*

            try {

                br = new BufferedReader(new

                        InputStreamReader(new FileInputStream(new File("file_i_o\\input.txt"))));

            } catch (FileNotFoundException e) {

                e.printStackTrace();

            }

*/

        }

        String next() {

            while (st == null || !st.hasMoreElements()) {

                try {

                    st = new StringTokenizer(br.readLine());

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

        String nextLine() {

            String str = "";

            try {

                str = br.readLine();

            } catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

        int[] nextIntArray(int n) {

            int[] array = new int[n];

            for (int i = 0; i < n; i++) {

                array[i] = nextInt();

            }

            return array;

        }

        Integer[] nextIntegerArray(int n) {

            Integer[] array = new Integer[n];

            for (int i = 0; i < n; i++) {

                array[i] = nextInt();

            }

            return array;

        }

        long[] nextLongArray(int n) {

            long[] array = new long[n];

            for (int i = 0; i < n; i++) {

                array[i] = nextLong();

            }

            return array;

        }

        String[] nextStringArray() {

            return nextLine().split(" ");

        }

        String[] nextStringArray(int n) {

            String[] array = new String[n];

            for (int i = 0; i < n; i++) {

                array[i] = next();

            }

            return array;

        }

    }

}


B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk  — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm  — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am  — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()((
OutputCopy1
2
1 3
InputCopy)(
OutputCopy0
InputCopy(()())
OutputCopy1
4
1 2 5 6
NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations.

import java.util.*;

public class sol

{

	public static void main(String[] args) {

// 		System.out.println("Hello World");

        Scanner sc= new Scanner(System.in);

        char ar[]=sc.next().toCharArray();

        int n=ar.length;

        String ans="";

         Queue<Integer> q

            = new LinkedList<>();

             Stack<Integer> q2

            = new Stack<>();

        for(int i=0;i<n;i++){

            if(ar[i]=='('){

                q.add(i+1);

            }

            else if(ar[i]==')') {

                q2.push(i+1);

            }

        }

        int count=0;

        String ans1="";

        String ans2="";

        // System.out.println(q);

        // System.out.println(q2);

        while(!q.isEmpty()&&!q2.isEmpty()){

            // System.out.println("jdkljds");

            int v1=q.remove();

            int v2=q2.pop();

            if(v1<v2){

                ans1+=v1+" ";

                StringBuilder sn2= new StringBuilder(String.valueOf(v2));

            ans2+=sn2.reverse().toString()+" ";

            count+=2;

            }

        }

          if(count==0){

            System.out.println("0");

        }

        else{

        StringBuilder sb= new StringBuilder(ans2.substring(0,ans2.length()-1));

        ans2=sb.reverse().toString();

        System.out.println("1");

        System.out.println(count);

        System.out.println(ans1+ans2);

        }

	}

}


A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00:  You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2);  then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4
3
1 1 3
4
1 1 2 1
2
11 11
1
100
OutputCopyYES
NO
YES
YES
NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.

import java.util.Scanner;

import java.util.Arrays;

import java.util.HashSet;

import java.util.HashMap;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Random;

import java.util.TreeSet;

import java.util.PriorityQueue;

public class Solution{

    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);

        int test_cases = sc.nextInt();

        outer : for(int h=0;h<test_cases;h++){

            //scan the input

           int n = sc.nextInt();

           int a[] = new int[n];

           scan_array(a, n, sc);

           boolean flag = false;

           for(int i=0;i<n-1;i++){

            if(Math.abs(a[i]-a[i+1])%2==1){

                flag = true;

                break;

            }

           }

           if(flag){

            System.out.println("NO");

           }

           else{

            System.out.println("YES");

           }

        }

        sc.close();

    }

    public static void scan_string_array(String s[] , int n, Scanner sc){

        for(int i=0;i<n;i++){

            s[i] = sc.next();

        }

    }

    public static void swap_elements(int a[], int s_index, int e_index){

        int temp = a[s_index];

        a[s_index] = a[e_index];

        a[e_index] = temp;

    }

    public static void scan_array_long(long a[], int n, Scanner sc){

        for(int i=0;i<n;i++){

            a[i] = sc.nextLong();

        }

    }

    public static void scan_array(int a[], int n, Scanner sc){

        for(int i=0;i<n;i++){

            a[i] = sc.nextInt();

        }

    }

    public static void print_array(int a[]){

        for(int i=0;i<a.length;i++){

            if(i==a.length-1){

                System.out.println(a[i]);

                return;

            }

            System.out.print(a[i]+" ");

        }

    }

    public static long sum_array(long a[]){

        long sum = 0;

        for(int i=0;i<a.length;i++){

            sum+=a[i];

        }

        return sum;

    }

    public static boolean perfect_square(double num){

        boolean isSq = false;

        double b = Math.sqrt(num);

        double c = Math.sqrt(num) - Math.floor(b);

        if(c==0){

            isSq=true;

        }

        return isSq;

    }

    public static boolean ispalindrome(String s){

        int i=0, j =s.length()-1;

        while(i<=j){

            if(s.charAt(i)!=s.charAt(j)){

                return false;

            }

            i++;

            j--;

        }

        return true;

    }

    public static boolean ispowerOftwo(int n){

        if(n>0 && (int)(n & (n-1))==0){

            return true;

        }

        else{

            return false;

        }

    }

    public static int calculate_gcd(int x,int y){

        int gcd = 1;

        if(x%y==0){

            return y;

        }

        else if(y%x==0){

            return x;

        }

        else{

            for(int i=2;i<=x && i<=y;i++){

                if(x%i==0 && y%i==0){

                    gcd = i;

                }

            }

            return gcd;

        }

    }

    public static long calculate_factorial(long x){

        long ans = 1;

        for(int i=1;i<=x;i++){

            ans*=i;

        }

        return ans;

    }

    public static void swap(int a[], int b[], int index_a, int index_b){

        int temp = a[index_a];

        a[index_a] = b[index_b];

        b[index_b] = temp;

    }

    public static int find_maximum(int a[]){

        int max = Integer.MIN_VALUE;

        for(int i=0;i<a.length;i++){

            max = Math.max(a[i], max);

        }

        return max;

    }

    public static int find_minimum(int a[]){

        int min = Integer.MAX_VALUE;

        for(int i=0;i<a.length;i++){

            min = Math.min(a[i], min);

        }

        return min;

    }

    public static void ruffleSort(int[] a) {

        int n=a.length;//shuffle, then sort

        Random random = new Random();

        for (int i=0; i<n; i++) {

            int oi=random.nextInt(n);

            int temp=a[oi];

            a[oi]=a[i];

            a[i]=temp;

        }

        Arrays.sort(a);

    }

    public static int sum_of_digits(int n){

        int s =0;

        while(n!=0){

            s+=n%10;

            n/=10;

        }

        return s;

    }

    public static int[] mergeSort(int[] array) {

        if (array.length <= 1) {

            return array;

        }

        int midpoint = array.length / 2;

        int[] left = new int[midpoint];

        int[] right;

        if (array.length % 2 == 0) {

            right = new int[midpoint];

        } else {

            right = new int[midpoint + 1];

        }

        for (int i = 0; i < left.length; i++) {

            left[i] = array[i];

        }

        for (int i = 0; i < right.length; i++) {

            right[i] = array[i + midpoint];

        }

        int[] result = new int[array.length];

        left = mergeSort(left);

        right = mergeSort(right);

        result = merge(left, right);

        return result;

    }

    public static int[] merge(int[] left, int[] right) {

        int[] result = new int[left.length + right.length];

        int leftPointer = 0, rightPointer = 0, resultPointer = 0;

        while (leftPointer < left.length || rightPointer < right.length) {

            if (leftPointer < left.length && rightPointer < right.length) {

                if (left[leftPointer] < right[rightPointer]) {

                    result[resultPointer++] = left[leftPointer++];

                } else {

                    result[resultPointer++] = right[rightPointer++];

                }

            } else if (leftPointer < left.length) {

                result[resultPointer++] = left[leftPointer++];

            } else {

                result[resultPointer++] = right[rightPointer++];

            }

        }

        return result;

    }

}


C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6
LRLRRLL
L
LLR
RRRR
LLLLLL
R
OutputCopy3
2
3
1
7
1
NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right.

import java.io.*;

public class w15q2

{

    public static void main(String[] args) throws IOException

    {

        InputStreamReader r = new InputStreamReader(System.in);

        BufferedReader br = new BufferedReader(r);

        int t = Integer.parseInt(br.readLine());

        for (int i = 0; i < t; i++)

        {

            String str = br.readLine();

            int L = 0;

            int con = 0;

            for (int j = 0; j < str.length(); j++)

            {

                if (str.charAt(j) == 'L')

                {

                    con += 1;

                }

                else

                {

                    con = 0;

                }

                if (con > L)

                {

                    L = con;

                }

            }

            System.out.println(L+1);

        }

    }

}


A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5
2 3
1 4
2 4
2 3
1 4
OutputCopyYes
No
No
No
Yes
NoteWe'll crack down the example test here:  After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5).  After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3).  After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal.  After the fifth query, the column barrier has been lifted, thus she can go to the final goal again.

import java.util.*;

import java.lang.*;

import java.io.*;

public class Main

{

    static final PrintWriter out =new PrintWriter(System.out);

    static final FastReader sc = new FastReader();

    /*

                       _oo0oo_

                      o8888888o

                      88" . "88

                      (| -_- |)

                      0\  =  /0

                    ___/`---'\___

                  .' \\|     |// '.

                 / \\|||  :  |||// \

                / _||||| -:- |||||- \

               |   | \\\  -  /// |   |

               | \_|  ''\---/''  |_/ |

               \  .-\__  '-'  ___/-. /

             ___'. .'  /--.--\  `. .'___

          ."" '<  `.___\_<|>_/___.' >' "".

         | | :  `- \`.;`\ _ /`;.`/ - ` : | |

         \  \ `_.   \_ __\ /__ _/   .-` /  /

     =====`-.____`.___ \_____/___.-`___.-'=====

                       `=---='

    */

     static class Pair{

          int f,l;

          public Pair(int first,int last)

          {

                this.f=first;

                this.l=last;

          }

    }

    public static boolean sorted(int a[])

    {

        int n=a.length,i;

        int b[]=new int[n];

        for(i=0;i<n;i++)

        b[i]=a[i];

        Arrays.sort(b);

        for(i=0;i<n;i++)

        {

            if(a[i]!=b[i])

            return false;

        }

        return true;

    }

	public static void main (String[] args) throws java.lang.Exception

	{

	      int n=sc.nextInt();

	      int a[][]=new int[2][n];

	      for(int it[]:a)

	      Arrays.fill(it,1);

	      int c=0;

	      int tes=sc.nextInt();

	    while(tes-->0)

	    {

	          int x=sc.nextInt();

	          int y=sc.nextInt();

	          x--; y--;

	          int i,k=(a[x][y]==1)?1:-1;

	          a[x][y]*=-1;

	          for(i=-1;i<=1;i++)

	          {

	                if(y+i<0 || y+i>=n)

	                continue;

	                if(a[1-x][y+i]==-1)

	                c+=k;

	          }

	          //for(int it[]:a)

	          //System.out.println(Arrays.toString(it));

	          if(c==0)

	          System.out.println("Yes");

	          else

	          System.out.println("NO");

	    }

	}

	public static int first(ArrayList<Integer> arr, int low, int high, int x, int n)

    {

        if (high >= low) {

            int mid = low + (high - low) / 2;

            if ((mid == 0 || x > arr.get(mid-1)) && arr.get(mid) == x)

                return mid;

            else if (x > arr.get(mid))

                return first(arr, (mid + 1), high, x, n);

            else

                return first(arr, low, (mid - 1), x, n);

        }

        return -1;

    }

	public static int last(ArrayList<Integer> arr, int low, int high, int x, int n)

    {

        if (high >= low) {

            int mid = low + (high - low) / 2;

            if ((mid == n - 1 || x < arr.get(mid+1)) && arr.get(mid) == x)

                return mid;

            else if (x < arr.get(mid))

                return last(arr, low, (mid - 1), x, n);

            else

                return last(arr, (mid + 1), high, x, n);

        }

        return -1;

    }

	public static int lis(int[] arr) {

	int n = arr.length;

	ArrayList<Integer> al = new ArrayList<Integer>();

	al.add(arr[0]);

	for(int i = 1 ; i<n;i++) {

		int x = al.get(al.size()-1);

		if(arr[i]>=x) {

			al.add(arr[i]);

		}else {

			int v = upper_bound(al, 0, al.size(), arr[i]);

			al.set(v, arr[i]);

		}

	}

	return al.size();

}

	public static int lower_bound(ArrayList<Long> ar,int lo , int hi , long k)

{

    Collections.sort(ar);

    int s=lo;

    int e=hi;

    while (s !=e)

    {

        int mid = s+e>>1;

        if (ar.get((int)mid) <k)

        {

            s=mid+1;

        }

        else

        {

            e=mid;

        }

    }

    if(s==ar.size())

    {

        return -1;

    }

    return s;

}

public static int upper_bound(ArrayList<Integer> ar,int lo , int hi, int k)

{

    Collections.sort(ar);

    int s=lo;

    int e=hi;

    while (s !=e)

    {

        int mid = s+e>>1;

        if (ar.get(mid) <=k)

        {

            s=mid+1;

        }

        else

        {

            e=mid;

        }

    }

    if(s==ar.size())

    {

        return -1;

    }

    return s;

}

static boolean isPrime(long N)

    {

        if (N<=1)  return false;

        if (N<=3)  return true;

        if (N%2 == 0 || N%3 == 0) return false;

        for (int i=5; i*i<=N; i=i+6)

            if (N%i == 0 || N%(i+2) == 0)

                return false;

        return true;

    }

    static int countBits(long a)

    {

        return (int)(Math.log(a)/Math.log(2)+1);

    }

    static long fact(long N)

    {

        long mod=1000000007;

        long n=2;

        if(N<=1)return 1;

        else

        {

            for(int i=3; i<=N; i++)n=(n*i)%mod;

        }

        return n;

    }

    private static boolean isInteger(String s) {

        try {

            Integer.parseInt(s);

        } catch (NumberFormatException e) {

            return false;

        } catch (NullPointerException e) {

            return false;

        }

        return true;

    }

    private static long gcd(long a, long b) {

        if (b == 0)

            return a;

        return gcd(b, a % b);

    }

    private static long lcm(long a, long b) {

        return (a / gcd(a, b)) * b;

    }

    private static boolean isPalindrome(String str) {

        int i = 0, j = str.length() - 1;

        while (i < j)

            if (str.charAt(i++) != str.charAt(j--))

                return false;

        return true;

    }

    private static String reverseString(String str) {

        StringBuilder sb = new StringBuilder(str);

        return sb.reverse().toString();

    }

	static class FastReader {

        BufferedReader br;

        StringTokenizer st;

        public FastReader()

        {

            br = new BufferedReader(

                new InputStreamReader(System.in));

        }

        String next()

        {

            while (st == null || !st.hasMoreElements()) {

                try {

                    st = new StringTokenizer(br.readLine());

                }

                catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt() { return Integer.parseInt(next()); }

        long nextLong() { return Long.parseLong(next()); }

        double nextDouble()

        {

            return Double.parseDouble(next());

        }

        String nextLine()

        {

            String str = "";

            try {

                str = br.readLine();

            }

            catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

    }

}


B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
OutputCopy0
1
5
NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.

import java.awt.image.AreaAveragingScaleFilter;
import java.io.*;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;

public class Pratice {

    static final long mod = 1000000007;
    static StringBuilder sb = new StringBuilder();
    static int xn = (int) (2e5 + 10);
    static long ans;
    static boolean prime[] = new boolean[1000001];

    // calculate sqrt and cuberoot
//    static Set<Long> set=new TreeSet<>();
//    static
//    {
//        long n=1000000001;
//
//
//        for(int i=1;i*i<=n;i++)
//        {
//            long x=i*i;
//            set.add(x);
//        }

//        for(int i=1;i*i*i<=n;i++)
//        {
//            long x=i*i*i;
//            set.add(x);
//        }

//    }

    static void sieveOfEratosthenes() {

        for (int i = 0; i <= 1000000; i++)
            prime[i] = true;
        prime[0] = false;
        prime[1] = false;

        for (int p = 2; p * p <= 1000000; p++) {

            if (prime[p] == true) {

                for (int i = p * p; i <= 1000000; i += p)
                    prime[i] = false;
            }
        }

    }

    public static void main(String[] args) throws IOException {
        Reader reader = new Reader();
        int t = reader.nextInt();
        while (t-- > 0) {

            int n=reader.nextInt();
            int arr[]=new int[2*n];
            Map<Integer,Integer> map=new HashMap<>();
            Set<Integer> set=new HashSet<>();
            for (int i = 0; i <2* n; i++) {
                arr[i]=reader.nextInt();
            }

            Arrays.sort(arr);

                System.out.println(Math.abs(arr[n-1]-arr[n]));

        }
    }

//    }

//    static void SieveOfEratosthenes(int n, boolean prime[],
//                                    boolean primesquare[], int a[])
//    {
//        // Create a boolean array "prime[0..n]" and
//        // initialize all entries it as true. A value
//        // in prime[i] will finally be false if i is
//        // Not a prime, else true.
//        for (int i = 2; i <= n; i++)
//            prime[i] = true;
//
//        /* Create a boolean array "primesquare[0..n*n+1]"
//         and initialize all entries it as false.
//         A value in squareprime[i] will finally
//         be true if i is square of prime,
//         else false.*/
//        for (int i = 0; i < ((n * n) + 1); i++)
//            primesquare[i] = false;
//
//        // 1 is not a prime number
//        prime[1] = false;
//
//        for (int p = 2; p * p <= n; p++) {
//            // If prime[p] is not changed,
//            // then it is a prime
//            if (prime[p] == true) {
//                // Update all multiples of p
//                for (int i = p * 2; i <= n; i += p)
//                    prime[i] = false;
//            }
//        }
//
//        int j = 0;
//        for (int p = 2; p <= n; p++) {
//            if (prime[p]) {
//
//                a[j] = p;
//
//
//                primesquare[p * p] = true;
//                j++;
//            }
//        }
//    }
//
//
//    static int countDivisors(int n)
//    {
//
//        if (n == 1)
//            return 1;
//
//        boolean prime[] = new boolean[n + 1];
//        boolean primesquare[] = new boolean[(n * n) + 1];
//
//        int a[] = new int[n];
//
//
//        SieveOfEratosthenes(n, prime, primesquare, a);
//
//
//        int ans = 1;
//
//        // Loop for counting factors of n
//        for (int i = 0;; i++) {
//            // a[i] is not less than cube root n
//            if (a[i] * a[i] * a[i] > n)
//                break;
//
//            int cnt = 1;
//
//            // if a[i] is a factor of n
//            while (n % a[i] == 0) {
//                n = n / a[i];
//
//                // incrementing power
//                cnt = cnt + 1;
//            }
//
//
//            ans = ans * cnt;
//        }
//
//
//        if (prime[n])
//            ans = ans * 2;
//
//            // Second case
//        else if (primesquare[n])
//            ans = ans * 3;
//
//            // Third case
//        else if (n != 1)
//            ans = ans * 4;
//
//        return ans; // Total divisors
//    }

    public static long[] inarr(long n) throws IOException {
        Reader reader = new Reader();
        long arr[]=new long[(int) n];
        for (long i = 0; i < n; i++) {
            arr[(int) i]=reader.nextLong();
        }

        return arr;

    }

    public static boolean checkPerfectSquare(int number)
    {
        int x=number % 10;

        if (x==2 || x==3 || x==7 || x==8)
        {
            return false;
        }
        for (int i=0; i<=number/2 + 1; i++)
        {
            if (i*i==number)
            {
                return true;
            }
        }
        return false;
    }

    // check number is prime or not
    public static boolean isPrime(int n) {
        return BigInteger.valueOf(n).isProbablePrime(1);
    }

    // return the gcd of two numbers
    public static long gcd(long a, long b)
    {
        BigInteger b1 = BigInteger.valueOf(a);
        BigInteger b2 = BigInteger.valueOf(b);
        BigInteger gcd = b1.gcd(b2);
        return gcd.longValue();
    }

    // return lcm of number
    static long lcm(int a, int b)
    {
        return (a / gcd(a, b)) * b;
    }

    // number of digits in the given number
    public static long numberOfDigits(long n)
    {
        long ans= (long) (Math.floor((Math.log10(n)))+1);
        return ans;
    }

    // return most significant bit in the number
    public static long mostSignificantNumber(long n)
    {
        double k=Math.log10(n);
        k=k-Math.floor(k);

        int ans=(int)Math.pow(10,k);
        return ans;
    }

    static class Reader {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader() {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1) {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.') {
                while ((c = read()) >= '0' && c <= '9') {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException {
            if (din == null)
                return;
            din.close();
        }
    }
}


B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
OutputCopyYES
NO
NO
NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.sort;

public class Codeforces {
     public static void main(String[] args) {
        FastReader fastReader = new FastReader();
        PrintWriter out = new PrintWriter(System.out);
        int tt = fastReader.nextInt();
        while(tt-->  0) {
            int n = fastReader.nextInt();
            int a[] = fastReader.ria(n);
            long cur = 0;
            long max = -(int)(1e9);
            long sum = 0;
            for(int i = 0 ;  i < n; i++){
                sum+=a[i];
            }

            for(int i = 0 ;  i < n-1; i++){
                cur+=a[i];
                max = max(cur,max);
                if(cur < 0){
                    cur = 0;
                }
            }
            cur = 0;
            for(int i = 1 ;  i < n; i++){
                cur+=a[i];
                if(cur < 0) cur = 0;
                max = max(cur,max);
            }

            if(sum > max){
                out.println("YES");
            }else{
                out.println("NO");
            }
        }

         out.close();
     }

    static class Pair{
        int x;
        int len;
        Pair(int x, int len){
            this.x  = x;
            this.len = len;
        }

        @Override
        public String toString() {
            return "Pair{" +
                    "x=" + x +
                    ", len=" + len +
                    '}';
        }
    }

    // constants
    static final int IBIG = 1000000007;
    static final int IMAX = 2147483647;
    static final long LMAX = 9223372036854775807L;
    static Random __r = new Random();

    // math util
    static int minof(int a, int b, int c) {
        return min(a, min(b, c));
    }

    static int minof(int... x) {
        if (x.length == 1)
            return x[0];
        if (x.length == 2)
            return min(x[0], x[1]);
        if (x.length == 3)
            return min(x[0], min(x[1], x[2]));
        int min = x[0];
        for (int i = 1; i < x.length; ++i)
            if (x[i] < min)
                min = x[i];
        return min;
    }

    static long minof(long a, long b, long c) {
        return min(a, min(b, c));
    }

    static long minof(long... x) {
        if (x.length == 1)
            return x[0];
        if (x.length == 2)
            return min(x[0], x[1]);
        if (x.length == 3)
            return min(x[0], min(x[1], x[2]));
        long min = x[0];
        for (int i = 1; i < x.length; ++i)
            if (x[i] < min)
                min = x[i];
        return min;
    }

    static int maxof(int a, int b, int c) {
        return max(a, max(b, c));
    }

    static int maxof(int... x) {
        if (x.length == 1)
            return x[0];
        if (x.length == 2)
            return max(x[0], x[1]);
        if (x.length == 3)
            return max(x[0], max(x[1], x[2]));
        int max = x[0];
        for (int i = 1; i < x.length; ++i)
            if (x[i] > max)
                max = x[i];
        return max;
    }

    static long maxof(long a, long b, long c) {
        return max(a, max(b, c));
    }

    static long maxof(long... x) {
        if (x.length == 1)
            return x[0];
        if (x.length == 2)
            return max(x[0], x[1]);
        if (x.length == 3)
            return max(x[0], max(x[1], x[2]));
        long max = x[0];
        for (int i = 1; i < x.length; ++i)
            if (x[i] > max)
                max = x[i];
        return max;
    }

    static int powi(int a, int b) {
        if (a == 0)
            return 0;
        int ans = 1;
        while (b > 0) {
            if ((b & 1) > 0)
                ans *= a;
            a *= a;
            b >>= 1;
        }
        return ans;
    }

    static long powl(long a, int b) {
        if (a == 0)
            return 0;
        long ans = 1;
        while (b > 0) {
            if ((b & 1) > 0)
                ans *= a;
            a *= a;
            b >>= 1;
        }
        return ans;
    }

    static int fli(double d) {
        return (int) d;
    }

    static int cei(double d) {
        return (int) ceil(d);
    }

    static long fll(double d) {
        return (long) d;
    }

    static long cel(double d) {
        return (long) ceil(d);
    }

    static int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }

    static int lcm(int a, int b) {
        return (a / gcd(a, b)) * b;
    }

    static long gcd(long a, long b) {
        return b == 0 ? a : gcd(b, a % b);
    }

    static long lcm(long a, long b) {
        return (a / gcd(a, b)) * b;
    }

    static int[] exgcd(int a, int b) {
        if (b == 0)
            return new int[] { 1, 0 };
        int[] y = exgcd(b, a % b);
        return new int[] { y[1], y[0] - y[1] * (a / b) };
    }

    static long[] exgcd(long a, long b) {
        if (b == 0)
            return new long[] { 1, 0 };
        long[] y = exgcd(b, a % b);
        return new long[] { y[1], y[0] - y[1] * (a / b) };
    }

    static int randInt(int min, int max) {
        return __r.nextInt(max - min + 1) + min;
    }

    static long mix(long x) {
        x += 0x9e3779b97f4a7c15L;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L;
        x = (x ^ (x >> 27)) * 0x94d049bb133111ebL;
        return x ^ (x >> 31);
    }

    public static boolean[] findPrimes(int limit) {
        assert limit >= 2;

        final boolean[] nonPrimes = new boolean[limit];
        nonPrimes[0] = true;
        nonPrimes[1] = true;

        int sqrt = (int) Math.sqrt(limit);
        for (int i = 2; i <= sqrt; i++) {
            if (nonPrimes[i])
                continue;
            for (int j = i; j < limit; j += i) {
                if (!nonPrimes[j] && i != j)
                    nonPrimes[j] = true;
            }
        }

        return nonPrimes;
    }

    // array util
    static void reverse(int[] a) {
        for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
            int swap = a[i];
            a[i] = a[n - i - 1];
            a[n - i - 1] = swap;
        }
    }

    static void reverse(long[] a) {
        for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
            long swap = a[i];
            a[i] = a[n - i - 1];
            a[n - i - 1] = swap;
        }
    }

    static void reverse(double[] a) {
        for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
            double swap = a[i];
            a[i] = a[n - i - 1];
            a[n - i - 1] = swap;
        }
    }

    static void reverse(char[] a) {
        for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
            char swap = a[i];
            a[i] = a[n - i - 1];
            a[n - i - 1] = swap;
        }
    }

    static void shuffle(int[] a) {
        int n = a.length - 1;
        for (int i = 0; i < n; ++i) {
            int ind = randInt(i, n);
            int swap = a[i];
            a[i] = a[ind];
            a[ind] = swap;
        }
    }

    static void shuffle(long[] a) {
        int n = a.length - 1;
        for (int i = 0; i < n; ++i) {
            int ind = randInt(i, n);
            long swap = a[i];
            a[i] = a[ind];
            a[ind] = swap;
        }
    }

    static void shuffle(double[] a) {
        int n = a.length - 1;
        for (int i = 0; i < n; ++i) {
            int ind = randInt(i, n);
            double swap = a[i];
            a[i] = a[ind];
            a[ind] = swap;
        }
    }

    static void rsort(int[] a) {
        shuffle(a);
        sort(a);
    }

    static void rsort(long[] a) {
        shuffle(a);
        sort(a);
    }

    static void rsort(double[] a) {
        shuffle(a);
        sort(a);
    }

    static int[] copy(int[] a) {
        int[] ans = new int[a.length];
        for (int i = 0; i < a.length; ++i)
            ans[i] = a[i];
        return ans;
    }

    static long[] copy(long[] a) {
        long[] ans = new long[a.length];
        for (int i = 0; i < a.length; ++i)
            ans[i] = a[i];
        return ans;
    }

    static double[] copy(double[] a) {
        double[] ans = new double[a.length];
        for (int i = 0; i < a.length; ++i)
            ans[i] = a[i];
        return ans;
    }

    static char[] copy(char[] a) {
        char[] ans = new char[a.length];
        for (int i = 0; i < a.length; ++i)
            ans[i] = a[i];
        return ans;
    }

    static class FastReader {

        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            br = new BufferedReader(
                    new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        int[] ria(int n) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++)
                a[i] = Integer.parseInt(next());
            return a;
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        long[] rla(int n) {
            long[] a = new long[n];
            for (int i = 0; i < n; i++)
                a[i] = Long.parseLong(next());
            return a;
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
}


import java.util.*;

import java.io.*;

import static java.lang.Math.*;

public class Main { public static void main(String[] args) { new MainClass().execute(); } }

class MainClass extends PrintWriter {

	MainClass() { super(System.out, true); }

	boolean cases = true;

	// Solution

	void solveIt(int testCaseNo) {

		char a[] = sc.next().toCharArray();

		HashMap<Character, Integer> map = new HashMap<>();

		TreeMap<Integer, Character> map2 = new TreeMap<>();

		int curr = 0;

		for (int i = 0; i < a.length; i++) {

			if (i == 0) {

				map.put(a[i], ++curr);

				map2.put(curr, a[i]);

				continue;

			}

			int val = map.get(a[i - 1]);

			if (map.containsKey(a[i])) {

				if (abs(map.get(a[i]) - val) > 1) {

					println("NO");

					return;

				}

				continue;

			}

			if (map2.containsKey(val + 1) && map2.get(val + 1) == a[i]) continue;

			if (map2.containsKey(val - 1) && map2.get(val - 1) == a[i]) continue;

			if (!map2.containsKey(val + 1)) {

				map2.put(val + 1, a[i]);

				map.put(a[i], val + 1);

				continue;

			}

			if (!map2.containsKey(val - 1)) {

				map2.put(val - 1, a[i]);

				map.put(a[i], val - 1);

				continue;

			}

			println("NO");

			return;

		}

		println("YES");

		for (int key : map2.keySet()) { print(map2.get(key)); }

		for (char ch = 'a'; ch <= 'z'; ch++) {

			if (map.containsKey(ch)) continue;

			print(ch);

		}

		println();

	}

	void sort(int a[], Comparator<Integer> cmp) {

		List<Integer> al = new ArrayList<>();

		for (int x : a) al.add(x);

		if (cmp != null) al.sort(cmp);

		else Collections.sort(al);

		for (int i = 0; i < a.length; i++) a[i] = al.get(i);

	}

	void solve() {

		int caseNo = 1;

		if (cases) for (int T = sc.nextInt(); T > 1; T--, caseNo++) { solveIt(caseNo); }

		solveIt(caseNo);

	}

	void execute() {

		long S = System.currentTimeMillis();

		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());

		out = new PrintWriter(System.out);

		this.sc = new FastIO();

		solve();

		out.flush();

		long G = System.currentTimeMillis();

		sc.tr(G - S + "ms");

	}

	class FastIO {

		private boolean endOfFile() {

			if (bufferLength == -1) return true;

			int lptr = ptrbuf;

			while (lptr < bufferLength) {

				// __

				if (!spaceChar(inputBuffer[lptr++])) return false;

			}

			try {

				is.mark(1000);

				while (true) {

					int b = is.read();

					if (b == -1) {

						is.reset();

						return true;

					} else if (!spaceChar(b)) {

						is.reset();

						return false;

					}

				}

			} catch (IOException e) {

				return true;

			}

		}

		private byte[] inputBuffer = new byte[1024];

		int bufferLength = 0, ptrbuf = 0;

		private int readByte() {

			if (bufferLength == -1) throw new InputMismatchException();

			if (ptrbuf >= bufferLength) {

				ptrbuf = 0;

				try {

					bufferLength = is.read(inputBuffer);

				} catch (IOException e) {

					throw new InputMismatchException();

				}

				if (bufferLength <= 0) return -1;

			}

			return inputBuffer[ptrbuf++];

		}

		private boolean spaceChar(int c) { return !(c >= 33 && c <= 126); }

		private int skipIt() {

			int b;

			while ((b = readByte()) != -1 && spaceChar(b));

			return b;

		}

		private double nextDouble() { return Double.parseDouble(next()); }

		private char nextChar() { return (char) skipIt(); }

		private String next() {

			int b = skipIt();

			StringBuilder sb = new StringBuilder();

			while (!(spaceChar(b))) {

				sb.appendCodePoint(b);

				b = readByte();

			}

			return sb.toString();

		}

		private char[] readCharArray(int n) {

			char[] buf = new char[n];

			int b = skipIt(), p = 0;

			while (p < n && !(spaceChar(b))) {

				buf[p++] = (char) b;

				b = readByte();

			}

			return n == p ? buf : Arrays.copyOf(buf, p);

		}

		private char[][] readCharMatrix(int n, int m) {

			char[][] map = new char[n][];

			for (int i = 0; i < n; i++) map[i] = readCharArray(m);

			return map;

		}

		private int[] readIntArray(int n) {

			int[] a = new int[n];

			for (int i = 0; i < n; i++) a[i] = nextInt();

			return a;

		}

		private long[] readLongArray(int n) {

			long[] a = new long[n];

			for (int i = 0; i < n; i++) a[i] = nextLong();

			return a;

		}

		private int nextInt() {

			int num = 0, b;

			boolean minus = false;

			while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));

			if (b == '-') {

				minus = true;

				b = readByte();

			}

			while (true) {

				if (b >= '0' && b <= '9') {

					num = num * 10 + (b - '0');

				} else {

					return minus ? -num : num;

				}

				b = readByte();

			}

		}

		private long nextLong() {

			long num = 0;

			int b;

			boolean minus = false;

			while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));

			if (b == '-') {

				minus = true;

				b = readByte();

			}

			while (true) {

				if (b >= '0' && b <= '9') {

					num = num * 10 + (b - '0');

				} else {

					return minus ? -num : num;

				}

				b = readByte();

			}

		}

		private void tr(Object... o) {

			if (INPUT.length() != 0) System.out.println(Arrays.deepToString(o));

		}

	}

	InputStream is;

	PrintWriter out;

	String INPUT = "";

	final int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE;

	final long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE;

	final long mod = (long) 1e9 + 7;

	FastIO sc;

}