D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4
OutputCopy2
3 1InputCopy1 3
OutputCopy3
1 1 1InputCopy8 5
OutputCopy-1InputCopy0 0
OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty.

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.Comparator;

import java.util.Deque;

import java.util.HashMap;

import java.util.HashSet;

import java.util.Iterator;

import java.util.LinkedList;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import java.util.PriorityQueue;

import java.util.Queue;

import java.util.Random;

import java.util.Stack;

import java.util.StringTokenizer;

import java.util.TreeMap;

import java.util.TreeSet;

public class hacker49 {

	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;

        }

    }

	static long[] x= {1,1,1,0,0,0,-1,-1,-1};

	static long[] y= {1,-1,0,-1,0,1,1,-1,0};

	public static void main(String[] args) {

		OutputStream outputStream =System.out;

	    PrintWriter out =new PrintWriter(outputStream);

		FastReader s=new FastReader();

	long x=s.nextLong();

	long n=s.nextLong();

	if(x>n) {

		System.out.println(-1);

	}else {

	if(n==0 && x==0) {

		System.out.println(0);

	}

	else if(n==x) {

			System.out.println(1);

			System.out.println(x);

		}else if(((n-1)^1) ==x){

			System.out.println(2);

			System.out.println((n-1)+" "+1);

		}

		else if((n-x)%2==0) {

			if(x==0) {

				System.out.println(2);

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

			}

			else {

				boolean p=false;

				long d=(n^x);

				d/=2;

				long k=n-d;

				if((d^k)==x) {

					System.out.println(2);

					System.out.println(d+" "+k);

				}else {

			System.out.println(3);

			System.out.println(x+" "+(n-x)/2+" "+(n-x)/2);

		}}

	}else {

		System.out.println(-1);

	}

		}

			out.close();

	}

	public static int[] KMP( String str) {

		int[] a=new int[str.length()];

		int j;

		int i;

     for(i=1,j=0;i<str.length();) {

    	 if(str.charAt(i)==str.charAt(j)) {

    		 a[i]=j+1;

    		 j++;

    		 i++;

    	 }else {

    		 if(j!=0) {

    			 j=a[j-1];

    		  }else {

    			 a[j]=0;

    			 i++;

    		 }

    	 }

     }

		return a;

	}

	static int[] k=new int[200001];

	public static void CS(long[] arr,long[] segtree,int low,int high,int pos) {

		if(low==high) {

			segtree[pos]=arr[low];

			return;

		}

		int mid=(low+high)/2;

		CS(arr,segtree,low,mid,2*pos+1);

		CS(arr,segtree,mid+1,high,2*pos+2);

		segtree[pos]=GCD(segtree[2*pos+1],segtree[2*pos+2]);

		}

	public static long RS(long[] segtree,int qlow,int qhigh,int low,int high,int pos) {

		if(low>=qlow && high<=qhigh) {

			return segtree[pos];

		}

		if(qhigh<low || qlow>high) {

			return 0;

		}

		int mid=(low+high)/2;

	return GCD(RS(segtree,qlow,qhigh,low,mid,2*pos+1),RS(segtree,qlow,qhigh,mid+1,high,2*pos+2));

	}

	public static void US(long[] segtree,int low,int high,int pos ,long new_val,int index,long prev_val,int c,int n) {

//		if(index>high || index<low) {

//			return ;

//		}

		if(low==high) {

			segtree[pos]=new_val;

			return;

		}

//		segtree[pos]+=diff;

//		 segtree[pos] = (segtree[pos] ^ prev_val) ^ new_val;

		if(high!=low) {

			int mid=(high+low)/2;

			if(index<=mid) {

			US(segtree,low,mid,2*pos+1,new_val,index,prev_val,c+1,n);}else {

			US(segtree,mid+1,high,2*pos+2,new_val,index,prev_val,c+1,n);}

			if((n-c)%2!=0) {

				segtree[pos]=(segtree[2*pos+1]|segtree[2*pos+2]);

			}else {

				segtree[pos]=(segtree[2*pos+1]^segtree[2*pos+2]);

			}

		}

	}

	static int nextPowerOf2(int n)

	{

	    n--;

	    n |= n >> 1;

	    n |= n >> 2;

	    n |= n >> 4;

	    n |= n >> 8;

	    n |= n >> 16;

	    n++;

	    return n;

	}

	public static int longest_Repeating_Subsequence(String str,int n) {

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

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

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

				if(str.charAt(i-1)==str.charAt(j-1) &&  i!=j) {

					dp[i][j]=1+dp[i-1][j-1];

				}else {

					dp[i][j]=Math.max(dp[i][j-1], dp[i-1][j]);

				}

			}

		}

		return dp[n][n];

	}

	public static int d1(ArrayList<Integer> e,int n,int i) {

		int l=-1;

		int r=n;

				;

		while(r>l+1) {

			int mid=(l+r)/2;

//			long h=mid^n;

//			System.out.println(e.get(mid)+" "+mid);

			if(e.get(mid)>i) {

				r=mid;

			}else {

				l=mid;

			}

		}

		return r;

	}

	public static int upper_bound(int[] a ,int x,int n) {

		int l=-1;

		int r=n;

		while(r>l+1) {

			int mid=(l+r)/2;

			if(a[mid]>x) {

				r=mid;

			}else {

				l=mid;

			}

		}

		return r;

	}

	public static int lower_bound(long[] a ,long x,int n) {

		int l=-1;

		int r=n;

		while(r>l+1) {

			int mid=(l+r)/2;

			if(a[mid]<=x) {

				l=mid;

			}else {

				r=mid;

			}

		}

		return l;

	}

	static long get=0;

	static int[] ans=new int[200001];

//	static int[] dx= {2,2,-2,-2,-1,-1,1,1};

//	static int[] dy= {1,-1,-1,1,-2,2,-2,2};

//	static int[][] vis1=new int[101][101];

//	static boolean valid(int x,int y,int n) {

//		if(x>=1 && x<=n && y>=1 && y<=n) {

//			return true;

//		}

//		return false;

//	}

//	static void dfs(int x,int y,char[][] a,int n,char t) {

//		a[x][y]=t;

//		vis1[x][y]=1;

//		for(int i=0;i<8;i++) {

//			if(valid(x+dx[i],y+dy[i],n) && vis1[x+dx[i]][y+dy[i]]==0) {

//				dfs(x+dx[i],y+dy[i],a,n,(t=='W')?'B':'W');

//			}

//		}

//	}

	static int[] par=new int[200001];

	static void bfs() {

		Queue<Integer> q=new LinkedList<>();

		q.add(1);

		vis[1]=1;

		h[1]=1;

		while(!q.isEmpty()) {

			int node=q.poll();

			for(int i=0;i<f1[node].size();i++) {

				if(vis[f1[node].get(i)]==0) {

					q.add(f1[node].get(i));

					vis[f1[node].get(i)]=1;

					h[f1[node].get(i)]=h[node]+1;

					par[f1[node].get(i)]=node;

				}

			}

		}

	}

	static int[] h=new int[200001];

	static int[] subtree=new int[200001];

	static int[] vis=new int[200001];

	static HashMap<Integer,pair> e=new HashMap<>();

	static ArrayList<Integer>[] f1=new ArrayList[200001];

	static PriorityQueue<pair> q=new PriorityQueue<>();

	static ArrayList<pair>[] f=new ArrayList[200001];

//	static void bfs() {

//		Queue<node> q=new LinkedList<>();

//		q.add(new node(1,0));

//		h[1]=0;

//		vis[1]=1;

//		while(!q.isEmpty()) {

//			node p=q.poll();

////			h[p.a]=p.b;

//			for(int i=0;i<f1[p.a].size();i++) {

//				if(vis[f1[p.a].get(i)]==0) {

//					q.add(new node(f1[p.a].get(i),p.b+1));

//					h[f1[p.a].get(i)]=p.b+1;

//					vis[f1[p.a].get(i)]=1;

//				}

//			}

//		}

//	}

	static int dfs(int node) {

		int c=1;

		vis[node]=1;

		for(int i=0;i<f1[node].size();i++) {

			if(vis[f1[node].get(i)]==0) {

				c+=dfs(f1[node].get(i));

			}

		}

		subtree[node]=c;

		return c;

	}

	static void dfs2(int node,int v) {

		vis[node]=1;

		if(ans[node]==1) {

			get+=v;

		}

		for(int i=0;i<f1[node].size();i++) {

			if(vis[f1[node].get(i)]==0) {

				dfs2(f1[node].get(i),v+((ans[node]==0)?1:0));

			}

		}

	}

static long m=-1;

static void sf(long[] min){

        int n = min.length;

        Random rnd = new Random();

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

            long tmp = min[i];

            int randomPos = i + rnd.nextInt(n-i);

            min[i] = min[randomPos];

            min[randomPos] = tmp;

        }

}

	static class pair implements Comparable<pair>{

		private long a;

		private long b;

		private long c;

		pair(long a,long b,long c){

			this.a=a;

//			this.f=f;

			this.b=b;

			this.c=c;

//			this.d=d;

//			this.e=e;

		}

		public int compareTo(pair o) {

			if(o.c!=this.c) {

//			return Integer.compare(o.c, this.c);}

//		else {

				return Long.compare(this.c,o.c);

			}else {

				return Long.compare(this.a*this.b,o.a*o.b);

			}

		}

//

	}

	static class node implements Comparable<node>{

		private long a;

		private long b;

		private long c;

		node(long a,long b,long c){

			this.a=a;

			this.b=b;

			this.c=c;

		}

		public int compareTo(node o) {

//			return Long.compare(arg0, arg1)

			if(this.c!=o.c) {

				return Long.compare(o.c, this.c);

			}else {

				return Long.compare(this.b, o.b);

			}

		}

	}

//	public static int upper_bound(long[] a ,long x,int n) {

//		int l=-1;

//		int r=n;

//		while(r>l+1) {

//			int mid=(l+r)/2;

//			if(a[mid]<x) {

//				l=mid;

//			}else {

//				r=mid;

//			}

//		}

//		return r;

//

//	}

//	public static int lower_bound(long[] a ,long x,int m) {

//		int l=0;

//		int r=m+1;

//		while(r>l+1) {

//			int mid=(l+r)/2;

//			if(a[mid]>=x) {

//				r=mid;

//			}else {

//				l=mid;

//			}

//		}

//		return r;

//

//	}

	public static long lb(int n,long[] pre,long k,long a,long b,long x,long y) {

		long l=0;

		long r=n+1;

		while(l<r) {

			long mid=(l+r)/2;

			long sum=0;

			long gcd=GCD(a,b);

			long g=mid/(a*b/gcd);

			long a1=mid/a;

			long b1=mid/b;

			sum+=(pre[(int) g]*(x+y))/100;

			if(x>=y) {

				sum+=((pre[(int) a1]-pre[(int) g])*x)/100;

				sum+=(((pre[(int)(a1+b1-g)]-pre[(int)(a1)])*y))/100;

			}else {

				sum+=((pre[(int) b1]-pre[(int) g])*y)/100;

				sum+=(((pre[(int)(a1+b1-g)]-pre[(int)(b1)])*x))/100;

			}

			if(sum>=k) {

				r=mid;

			}else {

				l=mid+1;

			}

//			System.out.println(mid+" "+h);

		}

		return r;

	}

	public static long[] merge_sort(long[] A, int start, int end) {

		if (end > start) {

			int mid = (end + start) / 2;

			long[] v = merge_sort(A, start, mid);

			long[] o = merge_sort(A, mid + 1, end);

			return (merge(v, o));

		} else {

			long[] y = new long[1];

			y[0] = A[start];

			return y;

		}

	}

	public static long[] merge(long a[], long b[]) {

		long[] temp = new long[a.length + b.length];

		int m = a.length;

		int n = b.length;

		int i = 0;

		int j = 0;

		int c = 0;

		while (i < m && j < n) {

			if (a[i] < b[j]) {

				temp[c++] = a[i++];

			} else {

				temp[c++] = b[j++];

			}

		}

		while (i < m) {

			temp[c++] = a[i++];

		}

		while (j < n) {

			temp[c++] = b[j++];

		}

		return temp;

	}

	public static int[] Create(int[] a,int n) {

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

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

			int j=i;

			int h=a[i];

			while(i<=n) {

				b[i]+=h;

				i=get_next(i);

			}

			i=j;

		}

		return b;

	}

public static int get_next(int a) {

	return a+(a&-a);

}

public static int get_parent(int a) {

	return a-(a&-a);

}

public static int query_1(int[] b,int index) {

	int sum=0;

	if(index<=0) {

		return 0;

	}

	while(index>0) {

		sum+=b[index];

		index=get_parent(index);

	}

	return sum;

}

public static int query(int[] b,int n,int l,int r) {

	int sum=0;

	sum+=query_1(b,r);

	sum-=query_1(b,l-1);

	return sum;

}

public static void update(int[] a,int[] b,int n,int index,int val) {

	int diff=val-a[index];

	a[index]+=diff;

	while(index<=n) {

		b[index]+=diff;

		index=get_next(index);

	}

}

//	public static void Create(int[] a,pair[] segtree,int low,int high,int pos) {

//		if(low>high) {

//			return;

//		}

//		if(low==high) {

//			segtree[pos].b.add(a[low]);

//			return ;

//		}

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

//		Create(a,segtree,low,mid,2*pos);

//		Create(a,segtree,mid+1,high,2*pos+1);

//		segtree[pos].b.addAll(segtree[2*pos].b);

//		segtree[pos].b.addAll(segtree[2*pos+1].b);

//	}

//	public static void update(pair[] segtree,int low,int high,int index,int pos,int val,int prev) {

//		if(index>high || index<low) {

//			return ;

//		}

//		if(low==high && low==index) {

//			segtree[pos].b.remove(prev);

//			segtree[pos].b.add(val);

//			return;

//		}

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

//			 update(segtree,low,mid,index,2*pos,val,prev);

//			 update(segtree,mid+1,high,index,2*pos+1,val,prev);

//			 segtree[pos].b.clear();

//			  segtree[pos].b.addAll(segtree[2*pos].b);

//			  segtree[pos].b.addAll(segtree[2*pos+1].b);

//

//	}

//	public static pair query(pair[] segtree,int low,int high,int qlow,int qhigh ,int pos) {

//		if(low>=qlow && high<=qhigh) {

//			return segtree[pos];

//		}

//		if(qhigh<low || qlow>high) {

//			return new pair();

//		}

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

//	  pair a1=query(segtree,low,mid,qlow,qhigh,2*pos);

//	  pair a2=query(segtree,mid+1,high,qlow,qhigh,2*pos+1);

//	  pair a3=new pair();

//	  a3.b.addAll(a1.b);

//	  a3.b.addAll(a2.b);

//	  return a3;

//

//	}

//

//	public static int nextPowerOf2(int n)

//	{

//	    n--;

//	    n |= n >> 1;

//	    n |= n >> 2;

//	    n |= n >> 4;

//	    n |= n >> 8;

//	    n |= n >> 16;

//	    n++;

//	    return n;

//	}

//

////	static class pair implements Comparable<pair>{

////		private int a;

////		private long b;

//////		private long c;

////		pair(int a,long b){

////			this.a=a;

////			this.b=b;

//////			this.c=c;

////		}

////		public int compareTo(pair o) {

//////		if(this.a!=o.a) {

//////			return Long.compare(this.a, o.a);

//////		}else {

////			return Long.compare(o.b,this.b);

//////		}

////		}

////	}

//	static class pair implements Comparable<pair>{

//		private int a;

//		private int b;

//		pair(int a,int b){

////			this.b=new HashSet<>();

//			this.a=a;

//			this.b=b;

//		}

//		public int compareTo(pair o) {

//			return Integer.compare(this.b, o.b);

//		}

//	}

	public static int lower_bound(ArrayList<Long> a ,int n,long x) {

		int l=0;

		int r=n;

		while(r>l+1) {

			int mid=(l+r)/2;

			if(a.get(mid)<=x) {

				l=mid;

			}else {

				r=mid;

			}

		}

		return l;

	}

	public static int[] is_prime=new int[10000001];

	public static ArrayList<Long> primes=new ArrayList<>();

 	public static void sieve() {

		long maxN=100000000;

		for(long i=1;i<=maxN;i++) {

			is_prime[(int) i]=1;

		}

		is_prime[0]=0;

		is_prime[1]=0;

		for(long i=2;i*i<=maxN;i++) {

			if(is_prime[(int) i]==1) {

//				primes.add((int) i);

				for(long j=i*i;j<=maxN;j+=i) {

					is_prime[(int) j]=0;

				}

			}

		}

		for(long i=0;i<=maxN;i++) {

			if(is_prime[(int) i]==1) {

				primes.add(i);

			}

		}

	}

//	public static pair[] merge_sort(pair[] A, int start, int end) {

//		if (end > start) {

//			int mid = (end + start) / 2;

//			pair[] v = merge_sort(A, start, mid);

//			pair[] o = merge_sort(A, mid + 1, end);

//			return (merge(v, o));

//		} else {

//			pair[] y = new pair[1];

//			y[0] = A[start];

//			return y;

//		}

//	}

//	public static pair[] merge(pair a[], pair b[]) {

//		pair[] temp = new pair[a.length + b.length];

//		int m = a.length;

//		int n = b.length;

//		int i = 0;

//		int j = 0;

//		int c = 0;

//		while (i < m && j < n) {

//			if (a[i].b >= b[j].b) {

//				temp[c++] = a[i++];

//

//			} else {

//				temp[c++] = b[j++];

//			}

//		}

//		while (i < m) {

//			temp[c++] = a[i++];

//		}

//		while (j < n) {

//			temp[c++] = b[j++];

//		}

//		return temp;

//	}

	public static long im(long a) {

		return binary_exponentiation_1(a,mod-2)%mod;

	}

	public static long binary_exponentiation_1(long a,long n) {

		long res=1;

		while(n>0) {

			if(n%2!=0) {

				res=((res)%(mod) * (a)%(mod))%(mod);

				n--;

			}else {

				a=((a)%(mod) *(a)%(mod))%(mod);

				n/=2;

			}

		}

		return (res)%(mod);

	}

	public static long b1(long a,long n) {

		long res=1;

		while(n>0) {

			if(n%2!=0) {

				res=((res)%(mod) * (a)%(mod))%(mod);

				n--;

			}else {

				a=((a)%(mod) *(a)%(mod))%(mod);

				n/=2;

			}

		}

		return (res)%(mod);

	}

	public static double bn1(double a,double n) {

		double res=1;

		while(n>0) {

			if(n%2!=0) {

//				res=((res)%(1000000007) * (a)%(1000000007))%(1000000007);

				res=(res*a);

				n--;

			}else {

//				a=((a)%(1000000007) *(a)%(1000000007))%(1000000007);

				a=(a*a);

				n/=2;

			}

		}

		return (res);

	}

	public static long bn(long a,long n) {

		long res=1;

		while(n>0) {

			if(n%2!=0) {

				res=res*a;

				n--;

			}else {

				a*=a;

				n/=2;

			}

		}

		return res;

	}

public static long[] fac=new long[300001];

public static void ff() {

		fac[0]=(long)1;

		fac[1]=(long)1;

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

			fac[(int) i]=(fac[(int) (i-1)]*i)%(mod);

		}

	}

public static long mod=1000000007;

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

		if(b==(long)0) {

			return a;

		}

		return GCD(b , a%b);

	}

public static long c=0;

}


A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb.  For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
OutputCopy2
-1
10
-1
1
NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.

import java.util.Scanner;

public class CFR620D2 {

    public static void main(String[] args) {

        Scanner sc=new Scanner(System.in);

        int n=sc.nextInt();

        while(n>0){

            n--;

            int x=sc.nextInt();

            int y=sc.nextInt();

            int a=sc.nextInt();

            int b=sc.nextInt();

           int L=(y-x);

           int jump=a+b;

           if(L%jump==0){

            System.out.println((int)L/jump);

           }else{

            System.out.println("-1");

           }

        }

    }

}


A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.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. Each test case is given on a new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5
5 3 2 8
100 101 102 105
3 2 1 100000000
10 20 15 14
101 101 101 3
OutputCopyYES
YES
NO
NO
YES

import java.util.*;

public class Main

{

	public static void main(String[] args) {

        Scanner s=new Scanner(System.in);

        int n=s.nextInt();

        while(n-->0)

        {

           int a=s.nextInt();

           int b=s.nextInt();

           int c=s.nextInt();

           int q=s.nextInt();

           int target=(a+b+c+q)/3;

           if((a<=target)&&(b<=target)&&(c<=target)&&((a+b+c+q)%3==0))

           {

               System.out.println("YES");

           }

           else

           {

               System.out.println("NO");

           }

        }

}

}


A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.

import java.math.BigInteger;

import java.util.Scanner;

public class Main {

    public static void main(String[] args){

        Scanner in = new Scanner(System.in);

        int num = in.nextInt();

        int div;

        int radix = 2;

        int res = 0;

        while(radix <= num-1){

            div = num;

            while(div >= radix){

                res += div%radix;

                div /= radix;

            }

            res += div;

            radix += 1;

        }

        int count = num-2;

        int gcd = BigInteger.valueOf(res).gcd(BigInteger.valueOf(count)).intValue();

        System.out.println(res/gcd + "/" + count/gcd);

    }

}


B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4
6 10
010010
5 3
10101
1 0
0
2 0
01
OutputCopy3
0
1
-1
NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.

import java.util.*;

import java.io.*;

public class Main {

  static StringBuilder sb;

  static dsu dsu;

  static long fact[];

  static int mod = (int) (1e9 + 7);

  static void solve() {

    int n = i();

    int x = i();

    String str = s();

    int cnt0 = 0;

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

        if(str.charAt(i)=='0') cnt0++;

    }

    int obal = 2*cnt0-n; // cnt0 - cnt1 , cnt0 - (n-cnt0)

    int cbal = 0;

    int ans = 0;

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

        if(obal==0&&cbal==x){

            System.out.println(-1);

            return;

        }

        if(obal!=0&&((x-cbal)%(obal))==0){

            if((x-cbal)/obal>=0){

                ans++;

            }

        }

        if(str.charAt(i)=='0') cbal++;

        else cbal--;

    }

    System.out.println(ans);

  }

  public static void main(String[] args) {

    sb = new StringBuilder();

    int test = i();

    while (test-- > 0) {

      solve();

    }

    System.out.println(sb);

  }

  /*

   * fact=new long[(int)1e6+10]; fact[0]=fact[1]=1; for(int i=2;i<fact.length;i++)

   * { fact[i]=((long)(i%mod)1L(long)(fact[i-1]%mod))%mod; }

   */

//**************NCR%P******************

  static long ncr(int n, int r) {

    if (r > n)

      return (long) 0;

    long res = fact[n] % mod;

    // System.out.println(res);

    res = ((long) (res % mod) * (long) (p(fact[r], mod - 2) % mod)) % mod;

    res = ((long) (res % mod) * (long) (p(fact[n - r], mod - 2) % mod)) % mod;

    // System.out.println(res);

    return res;

  }

  static long p(long x, long y)// POWER FXN //

  {

    if (y == 0)

      return 1;

    long res = 1;

    while (y > 0) {

      if (y % 2 == 1) {

        res = (res * x) % mod;

        y--;

      }

      x = (x * x) % mod;

      y = y / 2;

    }

    return res;

  }

//**************END******************

  // *************Disjoint set

  // union*********//

  static class dsu {

    int parent[];

    dsu(int n) {

      parent = new int[n];

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

        parent[i] = -1;

    }

    int find(int a) {

      if (parent[a] < 0)

        return a;

      else {

        int x = find(parent[a]);

        parent[a] = x;

        return x;

      }

    }

    void merge(int a, int b) {

      a = find(a);

      b = find(b);

      if (a == b)

        return;

      parent[b] = a;

    }

  }

//**************PRIME FACTORIZE **********************************//

  static TreeMap<Integer, Integer> prime(long n) {

    TreeMap<Integer, Integer> h = new TreeMap<>();

    long num = n;

    for (int i = 2; i <= Math.sqrt(num); i++) {

      if (n % i == 0) {

        int nt = 0;

        while (n % i == 0) {

          n = n / i;

          nt++;

        }

        h.put(i, nt);

      }

    }

    if (n != 1)

      h.put((int) n, 1);

    return h;

  }

//****CLASS PAIR ************************************************

  static class Pair implements Comparable<Pair> {

    int x;

    long y;

    Pair(int x, long y) {

      this.x = x;

      this.y = y;

    }

    public int compareTo(Pair o) {

      return (int) (this.y - o.y);

    }

  }

//****CLASS PAIR **************************************************

  static class InputReader {

    private InputStream stream;

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

    private int curChar;

    private int numChars;

    private SpaceCharFilter filter;

    public InputReader(InputStream stream) {

      this.stream = stream;

    }

    public int read() {

      if (numChars == -1)

        throw new InputMismatchException();

      if (curChar >= numChars) {

        curChar = 0;

        try {

          numChars = stream.read(buf);

        } catch (IOException e) {

          throw new InputMismatchException();

        }

        if (numChars <= 0)

          return -1;

      }

      return buf[curChar++];

    }

    public int Int() {

      int c = read();

      while (isSpaceChar(c))

        c = read();

      int sgn = 1;

      if (c == '-') {

        sgn = -1;

        c = read();

      }

      int res = 0;

      do {

        if (c < '0' || c > '9')

          throw new InputMismatchException();

        res *= 10;

        res += c - '0';

        c = read();

      } while (!isSpaceChar(c));

      return res * sgn;

    }

    public String String() {

      int c = read();

      while (isSpaceChar(c))

        c = read();

      StringBuilder res = new StringBuilder();

      do {

        res.appendCodePoint(c);

        c = read();

      } while (!isSpaceChar(c));

      return res.toString();

    }

    public boolean isSpaceChar(int c) {

      if (filter != null)

        return filter.isSpaceChar(c);

      return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;

    }

    public String next() {

      return String();

    }

    public interface SpaceCharFilter {

      public boolean isSpaceChar(int ch);

    }

  }

  static class OutputWriter {

    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {

      writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));

    }

    public OutputWriter(Writer writer) {

      this.writer = new PrintWriter(writer);

    }

    public void print(Object... objects) {

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

        if (i != 0)

          writer.print(' ');

        writer.print(objects[i]);

      }

    }

    public void printLine(Object... objects) {

      print(objects);

      writer.println();

    }

    public void close() {

      writer.close();

    }

    public void flush() {

      writer.flush();

    }

  }

  static InputReader in = new InputReader(System.in);

  static OutputWriter out = new OutputWriter(System.out);

  public static long[] sort(long[] a2) {

    int n = a2.length;

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

    for (long i : a2)

      l.add(i);

    Collections.sort(l);

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

      a2[i] = l.get(i);

    return a2;

  }

  public static char[] sort(char[] a2) {

    int n = a2.length;

    ArrayList<Character> l = new ArrayList<>();

    for (char i : a2)

      l.add(i);

    Collections.sort(l);

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

      a2[i] = l.get(i);

    return a2;

  }

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

    long res = 1;

    while (y > 0) {

      if (y % 2 != 0) {

        res = (res * x);// % modulus;

        y--;

      }

      x = (x * x);// % modulus;

      y = y / 2;

    }

    return res;

  }

//GCD___+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

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

    if (x == 0)

      return y;

    else

      return gcd(y % x, x);

  }

  // ******LOWEST COMMON MULTIPLE

  // *********************************************

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

    return (x * (y / gcd(x, y)));

  }

//INPUT PATTERN********************************************************

  public static int i() {

    return in.Int();

  }

  public static long l() {

    String s = in.String();

    return Long.parseLong(s);

  }

  public static String s() {

    return in.String();

  }

  public static int[] readArrayi(int n) {

    int A[] = new int[n];

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

      A[i] = i();

    }

    return A;

  }

  public static long[] readArray(long n) {

    long A[] = new long[(int) n];

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

      A[i] = l();

    }

    return A;

  }

}


E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]:   if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2];  if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2];  if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4
3 5 1 4
OutputCopy1 3
2 5
1 4
1 5
1 5
InputCopy4 3
1 2 4
OutputCopy1 3
1 2
3 4
1 4
NoteIn the first example; Polycarp's recent chat list looks like this:   [1,2,3,4,5][1,2,3,4,5]  [3,1,2,4,5][3,1,2,4,5]  [5,3,1,2,4][5,3,1,2,4]  [1,5,3,2,4][1,5,3,2,4]  [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this:   [1,2,3,4][1,2,3,4]  [1,2,3,4][1,2,3,4]  [2,1,3,4][2,1,3,4]  [4,2,1,3][4,2,1,3]

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

public class E
{
    static class SegNode
    {
        int lo, hi, mid;
        int sum, id = -1;
        SegNode left, right;

        SegNode(int a, int b)
        {
            lo = a;
            hi = b;
            mid = (lo + hi) / 2;

            if (lo != hi)
            {
                left = new SegNode(lo, mid);
                right = new SegNode(mid+1, hi);
            }
        }

        void set(int pos, int val, int id)
        {
            if (lo == hi)
            {
                sum = val;
                this.id = id;
                return;
            }

            if (pos <= mid)
                left.set(pos, val, id);
            else
                right.set(pos, val, id);

            sum = left.sum + right.sum;
        }

        int sum(int a, int b)
        {
            if (a <= lo && hi <= b)
                return sum;

            int val = 0;

            if (a <= mid)
                val += left.sum(a, Math.min(mid, b));
            if (mid+1 <= b)
                val += right.sum(Math.max(mid+1, a), b);

            return val;
        }

        int getId(int pos)
        {
            if (lo == hi)
                return id;

            if (pos <= mid)
                return left.getId(pos);
            else
                return right.getId(pos);
        }

    }
    static void solve(FastIO io)
    {
        int n = io.nextInt();
        int m = io.nextInt();

        int[] msg = new int[m];
        int[] min = new int[n];
        int[] max = new int[n];

        for (int i = 0; i < n; i++)
            min[i] = max[i] = i;

        for (int i = 0; i < m; i++)
        {
            msg[i] = io.nextInt() - 1;

            min[msg[i]] = 0;
        }

        int[] pos = new int[n];
        SegNode root = new SegNode(0, n + m);

        for (int i = 0; i < n; i++)
        {
            pos[i] = m + i;
            root.set(m+i, 1, i);
        }

        int ptr = m - 1;

        for (int i = 0; i < m; i++)
        {
            int k = msg[i];
            int p = root.sum(0, pos[k] - 1);

            max[k] = Math.max(max[k], p);

            root.set(pos[k], 0, -1);

            pos[k] = ptr--;

            root.set(pos[k], 1, k);
        }

        ptr = 0;

        for (int i = 0; i < n + m; i++)
        {
            int k = root.getId(i);
            if (k != -1)
                max[k] = Math.max(max[k], ptr++);
        }

        for (int i = 0; i < n; i++)
            io.println((min[i] + 1) + " " + (max[i] + 1));
    }

    public static void main(String[] args)
    {
        FastIO io = new FastIO();

        solve(io);

        io.close();
    }

    static class FastIO extends PrintWriter
    {
        StringTokenizer st = new StringTokenizer("");
        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));

        FastIO()
        {
            super(System.out);
        }

        String next()
        {
            while (!st.hasMoreTokens())
            {
                try {
                    st = new StringTokenizer(r.readLine());
                } catch (Exception e) { }
            }
            return st.nextToken();
        }

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

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

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


F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9
0 1 1 1 0 0 0 0 1
1 2
1 3
3 4
3 5
2 6
4 7
6 8
5 9
OutputCopy2 2 2 2 2 1 1 0 2
InputCopy4
0 0 1 0
1 2
1 3
1 4
OutputCopy0 -1 1 -1
NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33.

import java.lang.*;
import java.math.*;
import java.io.*;
import java.security.SecureRandom;
import java.util.*;
public class Main{
    public static int mod=(int)(1e9) + 7;

    public static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    public static PrintWriter ot=new PrintWriter(System.out);

    public static int[] take_arr(int n){
        int a[]=new int[n];
        try {
            String s[]=br.readLine().trim().split(" ");
            for(int i=0;i<n;i++)
            a[i]=Integer.parseInt(s[i]);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return a;
    }
    public static List<Integer> take_list(int n){
        List<Integer> a=new ArrayList<>();
        try {
            String s[]=br.readLine().trim().split(" ");
            for(int i=0;i<n;i++)
            a.add(Integer.parseInt(s[i]));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return a;
    }
	public static void main (String[] args) throws java.lang.Exception
	{
		try{
            int t=1;//Integer.parseInt(br.readLine().trim());

            int cno=1;
            while(t-->0){

                String s[]=br.readLine().trim().split(" ");

                int n = Integer.parseInt(s[0]);
                // int m = Integer.parseInt(s[1]);
                // solve(br.readLine());
                // int k = Integer.parseInt(s[2]);
                // char ch[] = br.readLine().trim().toCharArray();
                // int a[] = take_arr(n);
                // int b[] = take_arr(m);
                // long n = Long.parseLong(s[0]);
                // long m = Long.parseLong(s[1]);
                solve(n);
                // solve()
                // solve(n, m);

                // solve(ch);
            }
            ot.close();
            br.close();
        }catch(Exception e){
            e.printStackTrace();
            return;
        }
    }
    static void solve(int n) throws IOException{
        String s[] = br.readLine().trim().split(" ");
        c = new int[n + 1];
        for(int i = 1; i <= n; i++)
            c[i] = Integer.parseInt(s[i - 1]);
        adj = new ArrayList<>();
        for(int i = 0; i <= n; i++)
            adj.add(new ArrayList<>());
        for(int i = 1; i < n; i++){
            s = br.readLine().trim().split(" ");
            int u = Integer.parseInt(s[0]);
            int v = Integer.parseInt(s[1]);
            adj.get(u).add(v);
            adj.get(v).add(u);
        }
        dp = new int[n + 1];
        ans = new int[n + 1];
        dfs(1, -1);
        dfs2(1, -1);
        for(int i = 1; i <= n; i++)
            ot.print(ans[i] + " ");
        ot.println();
    }
    static void dfs2(int node, int par){
        ans[node] = dp[node];
        for(int ngr : adj.get(node)){
            if(ngr != par){
                dp[node] -= Math.max(0, dp[ngr]);
                dp[ngr] += Math.max(0, dp[node]);
                dfs2(ngr, node);
                dp[ngr] -= Math.max(0, dp[node]);
                dp[node] += Math.max(0, dp[ngr]);
            }
        }
    }
    static int dfs(int node, int par){
        int ans = (c[node] == 0 ? -1 : 1);
        for(int ngr : adj.get(node)){
            if(ngr != par){
               ans += Math.max(0, dfs(ngr, node));
            }
        }
        return dp[node] = ans;
    }
    static int ans[];
    static int c[];
    static int dp[];
    static List<List<Integer>> adj;
}


C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4
7 5 5 7
OutputCopy5.666666667
5.666666667
5.666666667
7.000000000
InputCopy5
7 8 8 10 12
OutputCopy7.000000000
8.000000000
8.000000000
10.000000000
12.000000000
InputCopy10
3 9 5 5 1 7 5 3 8 7
OutputCopy3.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
5.000000000
7.500000000
7.500000000
NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence.

import java.io.IOException;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.util.StringTokenizer;

import java.io.BufferedWriter;

import java.io.OutputStreamWriter;

public class Solution {

    static Reader input = new Reader();

    static int n;

    static int[] a;

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

        n = input.nextInt();

        a = new int[n];

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

            a[i] = input.nextInt();

        }

        long[] dp = new long[n];

        int[] next = new int[n];

        double[] answer = new double[n];

        answer[n-1] = a[n-1];

        next[n-1] = n-1;

        dp[n-1] = a[n-1];

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

            dp[i] = a[i];

            next[i] = i;

            for(int j = i+1; j < n; j = next[j]+1) {

                if(((double)dp[i]/(double)(next[i]-i+1)) >= answer[j]) {

                    next[i] = next[j];

                    dp[i] += dp[j];

                } else break;

            }

            answer[i] = (double)dp[i]/(double)(next[i]-i+1);

        }

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

        int i = 0, j;

        String temp;

        while(i < n) {

            temp = String.format("%.9f", answer[i]);

            for(j = i; j <= next[i]; ++j) {

                writer.write(temp+"\n");

            }

            i = j;

        }

        writer.flush();

    }

    static class Reader {

        BufferedReader reader;

        StringTokenizer string;

        public Reader() {

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

        }

        public String next() throws IOException {

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

                string = new StringTokenizer(reader.readLine());

            }

            return string.nextToken();

        }

        public int nextInt() throws IOException {

            return Integer.parseInt(next());

        }

    }

}


D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters  — UU, DD, LL, RR or XX  — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote:   a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy).  or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103)  — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2
1 1 1 1
2 2 2 2
OutputCopyVALID
XL
RX
InputCopy3
-1 -1 -1 -1 -1 -1
-1 -1 2 2 -1 -1
-1 -1 -1 -1 -1 -1
OutputCopyVALID
RRD
UXD
ULLNoteFor the sample test 1 :The given grid in output is a valid one.   If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there.  If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1).  If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2).  If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below :   For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below :

/*

 * To change this license header, choose License Headers in Project Properties.

 * To change this template file, choose Tools | Templates

 * and open the template in the editor.

 */

import java.io.BufferedWriter;

import java.io.DataInputStream;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStreamWriter;

/**

 *

 * @author kacho

 */

public class Codeforce {

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

        }

    }

    static int n;

    static int arr[][][];

    static char res[][];

    /**

     * @param args the command line arguments

     */

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

        Reader rd = new Reader();

        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new

         FileOutputStream(java.io.FileDescriptor.out), "ASCII"), 512);

        n = rd.nextInt();

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

        res = new char[n][n];

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

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

                arr[i][j][0] = rd.nextInt();

                arr[i][j][1] = rd.nextInt();

            }

        }

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

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

                if (arr[i][j][0] == -1) {

                    if (res[i][j] != '\u0000') continue;

                    if (i < n - 1 && arr[i + 1][j][0] == -1) {

                        res[i][j] = 'D';

                        res[i + 1][j] = 'U';

                    } else if (j < n - 1 && arr[i][j + 1][0] == -1) {

                        res[i][j] = 'R';

                        res[i][j + 1] = 'L';

                    } else if (i > 0 && arr[i - 1][j][0] == -1) {

                        res[i][j] = 'U';

                        res[i - 1][j] = 'D';

                    } else if (j > 0 && arr[i][j - 1][0] == -1) {

                        res[i][j] = 'L';

                        res[i][j - 1] = 'R';

                    } else {

                        System.out.println("INVALID");

                        return;

                    }

                } else if (i == arr[i][j][0] - 1 && j == arr[i][j][1] - 1) {

                    dfs(arr[i][j][0] - 1, arr[i][j][1] - 1, 'X');

                }

            }

        }

        for (char[] charr : res) {

            for (char ch : charr)

                if (ch == '\u0000') {

                    System.out.println("INVALID");

                    return;

                }

        }

        System.out.println("VALID");

        for (char[] charr : res) {

            for (char ch : charr)

                out.write(ch);

            out.write('\n');

        }

        out.flush();

    }

    static void dfs(int i, int j, char ch) {

        if (res[i][j] != '\u0000') return;

        res[i][j] = ch;

        if (i < n - 1 && arr[i + 1][j][0] == arr[i][j][0] && arr[i + 1][j][1] == arr[i][j][1])

            dfs(i + 1, j, 'U');

        if (j < n - 1 && arr[i][j + 1][0] == arr[i][j][0] && arr[i][j + 1][1] == arr[i][j][1])

            dfs(i, j + 1, 'L');

        if (i > 0 && arr[i - 1][j][0] == arr[i][j][0] && arr[i - 1][j][1] == arr[i][j][1])

            dfs(i - 1, j, 'D');

        if (j > 0 && arr[i][j - 1][0] == arr[i][j][0] && arr[i][j - 1][1] == arr[i][j][1])

            dfs(i, j - 1, 'R');

    }

}


A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way:  Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x;  choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.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.Then tt test cases follow. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5
2 3
10 10
2 4
7 4
9 3
OutputCopy1
0
2
2
1
NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.

import java.util.*;

public class AddOddSubEven {

    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);

        int t = sc.nextInt();

        while (t-- > 0) {

            long a = sc.nextLong();

            long b = sc.nextLong();

            if (a == b)

                System.out.println(0);

            else {

                long sub = b - a;

                if (sub > 0) {

                    if (sub % 2 != 0)

                        System.out.println(1);

                    else

                        System.out.println(2);

                } else {

                    if (sub % 2 == 0)

                        System.out.println(1);

                    else

                        System.out.println(2);

                }

            }

        }

    }

}


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 java.io.*;

import java.util.*;

public class CF1303C {

    static String alp = "abcdefghijklmnopqrstuvwxyz";

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

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

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

        Outer:

        for (int x = 0; x < t; x++) {

            String s = in.readLine();

            String result = ""+s.charAt(0);

            for (int i = 1; i < s.length(); i++) {

                char c = s.charAt(i);

                char d = s.charAt(i-1);

                int idx1 = result.indexOf(c);

                int idx2 = result.indexOf(d);

                if (idx1 == idx2) {

                    System.out.println("NO");

                    continue Outer;

                }

                if (idx1 < 0) {

                    if (idx2 == 0) result = c+result;

                    else if (idx2 == result.length()-1) result += c;

                    else {

                        System.out.println("NO");

                        continue Outer;

                    }

                }

                else {

                    if (Math.abs(idx1-idx2) != 1) {

                        System.out.println("NO");

                        continue Outer;

                    }

                }

            }

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

                if (!result.contains(""+alp.charAt(i))) result += alp.charAt(i);

            }

            System.out.println("YES");

            System.out.println(result);

        }

    }

}


A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4
4 0 11 6
OutputCopy11 6 4 0InputCopy1
13
OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Manav
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        AAnuHasAFunction solver = new AAnuHasAFunction();
        solver.solve(1, in, out);
        out.close();
    }

    static class AAnuHasAFunction {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.nextInt();
            int[] a = in.nextIntArray(n);
            int[] bits = new int[32];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < 32; j++) {
                    if ((a[i] & (1 << j)) > 0) {
                        bits[j]++;
                    }
                }
            }
//        out.println(bits);
            int max = -1;
            for (int j = 31; j >= 0; j--) {
                if (bits[j] == 1) {
                    max = j;
                    break;
                }
            }
//        out.println(max);
            int[] ans = new int[n];
            if (max == -1) {
                ans = a;
            } else {
                int first = -1;
                for (int i = 0; i < n; i++) {
                    if ((a[i] & (1 << max)) > 0) {
                        first = a[i];
                        break;
                    }
                }
//            out.println(first,"first");
                int j = 1;
                if (max != -1 && first != -1) {
                    ans[0] = first;
                    for (int i = 0; i < n; i++) {
                        if (a[i] != first && first != 0) {
                            ans[j++] = a[i];
                        }
                    }
                } else {
                    Arrays.sort(a);
                    out.println(a);
                }

            }

            out.println(ans);
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public int[] nextIntArray(int n) {
            int[] array = new int[n];
            for (int i = 0; i < n; ++i) array[i] = nextInt();
            return array;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void print(int[] array) {
            for (int i = 0; i < array.length; i++) {
                if (i != 0) {
                    writer.print(' ');
                }
                writer.print(array[i]);
            }
        }

        public void println(int[] array) {
            print(array);
            writer.println();
        }

        public void close() {
            writer.close();
        }

    }
}


/**

 * 10/31/21 night

 * https://codeforces.com/problemset/problem/13/A

 */

// package codeforce.practice.L1000;

import java.util.*;

import java.io.*;

public class A13 {

    static PrintWriter pw;

    void solve(int a) {

        int res = 0, divide = a - 2;

        for (int base = 2; base < a; base++) {

            int sum = sumOfDigit(a, base);

            res += sum;

        }

        int g = gcd(res, divide);

        res /= g;

        divide /= g;

        pr(res + "/" + divide);

    }

    int sumOfDigit(int x, int base) {

        int res = 0;

        while (x > 0) {

            res += x % base;

            x /= base;

        }

        return res;

    }

    int gcd(int a, int b) {

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

    }

    private void run() {

        // read_write_file(); // comment this before submission

        FastScanner fs = new FastScanner();

        int a = fs.nextInt();

        solve(a);

    }

    private final String INPUT = "input.txt";

    private final String OUTPUT = "output.txt";

    void read_write_file() {

        FileInputStream instream = null;

        PrintStream outstream = null;

        try {

            instream = new FileInputStream(INPUT);

            outstream = new PrintStream(new FileOutputStream(OUTPUT));

            System.setIn(instream);

            System.setOut(outstream);

        } catch (Exception e) {

        }

    }

    public static void main(String[] args) {

        pw = new PrintWriter(System.out);

        new A13().run();

        pw.close();

    }

    void pr(int num) {

        pw.println(num);

    }

    void pr(long num) {

        pw.println(num);

    }

    void pr(double num) {

        pw.println(num);

    }

    void pr(String s) {

        pw.println(s);

    }

    void pr(char c) {

        pw.println(c);

    }

    class FastScanner {

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

        StringTokenizer st = new StringTokenizer("");

        String next() {

            while (!st.hasMoreTokens())

                try {

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

                } catch (IOException e) {

                    e.printStackTrace();

                }

            return st.nextToken();

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        int[] readArray(int n) {

            int[] a = new int[n];

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

                a[i] = nextInt();

            return a;

        }

        Integer[] readIntegerArray(int n) {

            Integer[] a = new Integer[n];

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

                a[i] = nextInt();

            return a;

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

    }

    void tr(Object... o) {

        pw.println(Arrays.deepToString(o));

    }

}


import java.util.Scanner;

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++){

            long x = sc.nextLong();

            long y = sc.nextLong();

            long a = sc.nextLong();

            long b = sc.nextLong();

            if((y-x)%(a+b)!=0){

                System.out.println(-1);

            }

            else{

                System.out.println((int)(y-x)/(a+b));

            }

        }

    }

    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 long find_maximum(long a[]){

        long max = Long.MIN_VALUE;

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

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

        }

        return max;

    }

    public static long find_minimum(long a[]){

        long min = Long.MAX_VALUE;

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

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

        }

        return min;

    }

}


B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.

import java.util.*;

import java.math.*;

import java.io.*;

public class Main {

	static ArrayList<Integer> prime = new ArrayList<>();

	static int mod = (int)(1e9	+ 7 ) ;

	static ArrayList<Integer> arr;

	static ArrayList<Long> prefix;

	static ArrayList<Long> pre = new ArrayList<>();

	static final long LMAX = 9223372036854775807L;

	static ArrayList<Integer> arr1 = new ArrayList<>();

	static ArrayList<ArrayList<Integer>> vis = new ArrayList<>();

	static int dr[] = {1, 0, -1, 0};

	static int dc[] = {0, -1, 0, 1};

	static class FastReader {

		BufferedReader br;

		StringTokenizer st;

		public FastReader() {

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

		}

		String next() {

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

				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().trim();

			} catch (Exception e) {

				e.printStackTrace();

			}

			return str;

		}

	}

	static class FastWriter {

		private final BufferedWriter bw;

		public FastWriter() {

			this.bw = new BufferedWriter(new OutputStreamWriter(System.out));

		}

		public void print(Object object) throws IOException {

			bw.append("" + object);

		}

		public void println(Object object) throws IOException {

			print(object);

			bw.append("\n");

		}

		public void close() throws IOException {

			bw.close();

		}

	}

	public static class Pair {

		int first;

		int second;

		Pair(int first , int second ) {

			this.first = first ;

			this.second = second;

		}

	}

	public static void main(String[] args) {

		try {

			FastReader in = new FastReader();

			FastWriter out = new FastWriter();

			// Collections.sort(arr, new Comparator<Pair>() {

			// 		@Override public int compare(Pair o1, Pair o2) {

			// 			if (o1.second < o2.second ) { // change (>) for desending order

			// 				return -1;

			// 			} else if (o1.second == o2.second ) {

			// 				return 0;

			// 			} else {

			// 				return 1;

			// 			}

			// 		}

			// 	});

			// int testcases = in.nextInt();

			int testcases = 1;

			while ( testcases -- > 0 ) {

				long ans1 = 0, ans2 = 0, ans3 = 0, ans4 = 0;

				double n = in.nextDouble();

				double ans = 0.0 ;

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

					double x = (double) 1 / i ;

					ans += x ;

					// out.print(x);

				}

				out.println(ans);

			}

			out.close();

		} catch (Exception e) {

			return;

		}

	}

	private static void dfs(int i, int j , int  n , int m , char arr[][] ) {

		if  ( arr[i][j] == '#' ) return ;

		arr[i][j] = '#';

		// ~~~~~

		for ( int k = 0; k < 4; ++k ) {

			int x = dr[k] + i;

			int y = dc[k] + j;

			if ( x >= 0 && x < n && y >= 0 && y < m && arr[x][y] == '.'  ) {

				dfs(x, y, n , m , arr );

			}

		}

		// ~~~~~

	}

	private static void bfs( Stack<Pair> q, char[][] arr , int[][] vis ) {

		int n = arr.length;

		int m = arr[0].length;

		while (!q.isEmpty()) {

			int i = q.peek().first;

			int j = q.peek().second;

			vis[i][j] = 1;

			q.pop();

			int dr[] = {1, 0, -1, 0};

			int dc[] = {0, -1, 0, 1};

			for ( int k = 0; k < 4; ++k ) {

				int x = dr[k] + i;

				int y = dc[k] + j;

				if ( x >= 0 && x < n && y >= 0 && y < m  && arr[x][y] == '.' && vis[x][y] != 1 ) {

					q.add(new Pair(x, y));

				}

			}

		}

	}

	public static boolean isSatisfy( ArrayList<Integer> arr , int l , int r ) {

		int ans = 0;

		if ( l == 0 || arr.get(l) < arr.get(l - 1) ) ans++;

		if ( r == arr.size() - 1 || arr.get(r) < arr.get(r + 1) ) ans++;

		if ( ans == 2 ) return true;

		return false;

	}

	public static ArrayList<Long> prefixSum() {

		int mod = 100000;

		// ArrayList<Integer> arr ;

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

		long prev = 0;

		for ( long i = 0; i <= mod; ++i ) {

			prev += i;

			prefix.add(prev);

		}

		return prefix;

	}

	public static long sumRem(int x ) {

		if ( x <= 1 ) return 1;

		return x + sumRem(x - 1);

	}

	public static boolean isSquare( int n ) {

		int sqrt = (int) Math.sqrt(n);

		return (sqrt * sqrt == n );

	}

	public static void swap ( int l , int r , ArrayList<Integer> a ) {

		int t = a.get(l) ;

		a.add(l, a.get(r) );

		a.add(r, t);

	}

	public static void fib( int a , int b , int n) {

		int x = Math.floorMod(a, mod);

		int y = Math.floorMod(b, mod);

		arr = new ArrayList<>();

		arr.add(a);

		arr.add(b);

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

			int cur = Math.floorMod((y - x), mod);

			x = y;

			y = cur;

			arr.add(y);

		}

	}

	public static String reverseString( String s1 ) {

		String s = "";

		for ( int i = s1.length() - 1; i >= 0; --i ) {

			s += s1.charAt(i);

		}

		return s;

	}

	public static long countSetBits(long n) {

		long count = 0;

		while (n > 0) {

			count += n & 1;

			n >>= 1;

		}

		return count;

	}

	public static void sortbykey(HashMap<Long, Long> map) {

		TreeMap<Long, Long> sorted = new TreeMap<>();

		sorted.putAll(map);

	}

	public static long sum(int n) {

		if ( n <= 1 ) return n;

		return n + sum(n - 1);

	}

	public static ArrayList<Long> prefix( ArrayList<Long> arr1 ) {

		Collections.sort(arr1);

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

		long prefix = 0;

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

			prefix += arr1.get(i);

			arr.add(prefix);

		}

		return arr;

	}

	public static int solve(int[][] m, int n) {

		int ans = 0;

		int vis[][] = new int[n][n];

		int di[] = {1, 0, 0, -1};

		int dj[] = {0, -1, 1, 0};

		if (m[0][0] == 1) mazerunner(0, 0, m, n, ans, "", vis, di, dj);

		return ans;

	}

	public static void mazerunner(int i, int j, int m[][], int n, int ans, String move, int vis[][], int di[] , int dj[]) {

		if ( i == n - 1 && j == n - 1) {

			ans++;

			return;

		}

		String dir = "DLRU";

		for (int ind = 0; ind < 4; ind++) {

			int nexti = i + di[ind];

			int nextj = j + dj[ind];

			if (nexti >= 0 && nextj >= 0 && nexti < n && nextj < n && vis[nexti][nextj] == 0 && m[nexti][nextj] == 1) {

				vis[i][j] = 0;

				mazerunner(nexti, nextj, m, n, ans, move + dir.charAt(ind), vis, di, dj);

				vis[i][j] = -1;

			}

		}

	}

	public static long pow( long k , long n ) {

		long ans = 1;

		while ( n > 0 ) {

			if ( n % 2 == 1 ) {

				ans = (ans * k) % mod;

				n--;

			} else {

				k = (k * k) % mod;

				n /= 2;

			}

		}

		return ans % mod;

	}

	public static long fact(long n ) {

		long ans = 0;

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

			ans += (long)i;

		}

		return ans;

	}

	public static boolean isValid( long mid, long arr[] , long k ) {

		long req = 0;

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

			req += Math.min( (arr[i] - arr[i - 1] ) , mid );

		}

		req += mid;

		if ( req >= k ) return true;

		return false;

	}

	public static String sortString(String inputString) {

		char tempArray[] = inputString.toCharArray();

		Arrays.sort(tempArray);

		return new String(tempArray);

	}

	private static void reverse( ArrayList<Long> arr , int i, int j ) {

		while ( i <= j ) {

			swap( arr, i, j);

			i++; j--;

		}

	}

	private static void swap( ArrayList<Long> arr , int i, int j ) {

		long temp = arr.get(i);

		arr.set(i, arr.get(j));

		arr.set(j, temp);

	}

	private static boolean isPrime(long n ) {

		if ( n == 1 ) return true;

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

			if ( n % i == 0 ) {

				return false ;

			}

		}

		return true;

	}

	private static boolean[] sieve() {

		int n = 100000000;

		boolean sieve[] = new boolean[n + 1];

		Arrays.fill(sieve, true);

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

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

				sieve[j] = false;

			}

		}

		return sieve;

	}

	private static ArrayList<Integer> generatePrimes(int n ) {

		boolean sieve[] = sieve();

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

			if ( sieve[i] == true ) {

				prime.add(i);

			}

		}

		return prime;

	}

	private static void segmentedSieve( int l  , int r ) {

		int n = (int) Math.sqrt(r);

		ArrayList<Integer> pr = generatePrimes(n);

		int dummy[] = new int[r - l + 1];

		Arrays.fill(dummy, 1);

		for ( int p : pr ) {

			int firstMultiple = (l / p) * p;

			if ( firstMultiple < l ) firstMultiple += p;

			for ( int j = Math.max(firstMultiple, p * p); j <= r; j += p) {

				dummy[j - l] = 0;

			}

		}

		for ( int i = l; i <= r; i++) {

			if ( dummy[i - l] == 1 ) {

				System.out.println(i);

			}

		}

	}

	private static int[] primeFactors() {

		int n = 1000000;

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

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

			prime[i] = i;

		}

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

			if ( prime[i] == i ) {

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

					if ( prime[j] == j ) {

						prime[j] = i;

					}

				}

			}

		}

		return prime;

	}

	private 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;

	}

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

		long ans = 1;

		while ( b > 0 ) {

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

				ans = binMultiply(ans, a);

			}

			a = binMultiply(a, a );

			b >>= 1;

		}

		return ans;

	}

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

		long ans = 0;

		while ( b > 0 ) {

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

				ans = (ans + a % mod ); // if  m is given in ques than use ans = ans+a % m ;

			}

			a = (a + a) % mod; // if m is given in ques than use a = (a+a)%m;

			b >>= 1;

		}

		return ans;

	}

	private static int GCD ( int a , int b ) {

		if ( b == 0) return a;

		return GCD( b , a % b);

	}

	private static int binarySearch(int l , int r , int[] arr , int find ) {

		int mid = l + (r - l) / 2;

		if ( arr[mid] == find ) {

			return mid;

		} else if ( arr[mid] > find ) {

			return binarySearch(l, mid - 1, arr, find);

		}

		return binarySearch(mid + 1, r, arr, find);

	}

	private static int upper_bound(ArrayList<Integer> arr , int element ) {

		int l = 0 ;

		int h = arr.size() - 1;

		int mid = 0;

		while ( h - l > 1 ) {

			mid = (h + l) / 2;

			if ( arr.get(mid) <=  element ) {

				l = mid + 1;

			} else {

				h = mid ;

			}

		}

		if ( arr.get(l) > element ) return l;

		if ( arr.get(h) > element ) return h;

		return -1;

	}

	private static int lower_bound( long arr[] , long element ) {

		int l = 0 ;

		int h = arr.length - 1;

		int mid = 0;

		while ( h - l > 1 ) {

			mid = (h - l) / 2;

			if ( arr[mid] < element ) {

				l = mid + 1;

			} else {

				h = mid ;

			}

		}

		if ( arr[l] >= element ) return l;

		if ( arr[h] >= element ) return h;

		return -1;

	}

}

class DisjointSet {

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

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

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

	public DisjointSet(int n ) {

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

			rank.add(0);

			parent.add(i);

			size.add(1);

		}

	}

	public int findUPar(int node ) {

		if ( node == parent.get(node) ) return node;

		int ulp = findUPar(parent.get(node));

		parent.set(node, ulp);

		return parent.get(node);

	}

	public void unionBySize(int u, int v) {

		int ulp_u = findUPar(u);

		int ulp_v = findUPar(v);

		if ( ulp_u == ulp_v ) return ;

		if ( size.get(ulp_u) < size.get(ulp_v) ) {

			parent.set(ulp_u, ulp_v);

			size.set(ulp_v, size.get(ulp_v) + size.get(ulp_u) );

		} else {

			parent.set(ulp_v, ulp_u);

			size.set(ulp_u, size.get(ulp_v) + size.get(ulp_u) );

		}

	}

	public void unionByRank(int u, int v) {

		int ulp_u = findUPar(u);

		int ulp_v = findUPar(v);

		if ( ulp_u == ulp_v ) return ;

		if ( rank.get(ulp_u) < rank.get(ulp_v) ) {

			parent.set(ulp_u, ulp_v);

		} else if ( rank.get(ulp_v) < rank.get(ulp_u) ) {

			parent.set(ulp_v, ulp_u);

		} else {

			parent.set(ulp_v, ulp_u);

			int rankU = rank.get(ulp_u);

			rank.set(ulp_u, rankU + 1);

		}

	}

}

class Pair {

	int first;

	int second;

	Pair(int first , int second ) {

		this.first = first ;

		this.second = second;

	}

}


D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.StringTokenizer;

/*

1

2 3

 */

public class D {

	static int ind1, ind2;

	public static void main(String[] args) {

		FastScanner fs=new FastScanner();

		int n=fs.nextInt(), m=fs.nextInt();

		int[][] arrays=new int[n][m];

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

			for (int j=0; j<m; j++)

				arrays[i][j]=fs.nextInt();

		int low=0, high=1000_000_001;

		while (low!=high) {

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

			if (possible(mid, arrays, n, m)) {

				low=mid;

			}

			else {

				high=mid-1;

			}

		}

		possible(low, arrays, n, m);

		System.out.println(ind1+" "+ind2);

	}

	static boolean possible(int min, int[][] arrays, int n, int m) {

		boolean[] possible=new boolean[1<<m];

		int[] used=new int[1<<m];

		int arrayInd=0;

		for (int[] a:arrays) {

			arrayInd++;

			int mask=0;

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

				if (a[i]>=min) mask+=1<<i;

			possible[mask]=true;

			used[mask]=arrayInd;

		}

		for (int i=0; i<1<<m; i++)

			for (int j=0; j<1<<m; j++)

				if (possible[i]&&possible[j]&&((i|j)==((1<<m)-1))) {

					ind1=used[i];

					ind2=used[j];

					return true;

				}

		return false;

	}

	static class FastScanner {

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

		StringTokenizer st=new StringTokenizer("");

		String next() {

			while (!st.hasMoreElements())

				try {

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

				} catch (IOException e) {

					e.printStackTrace();

				}

			return st.nextToken();

		}

		int nextInt() {

			return Integer.parseInt(next());

		}

	}

}


import java.util.*;

import java.io.*;

public class perfectkeyboard {

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

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

		PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

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

		int t = Integer.parseInt(st.nextToken());

		while (t-- > 0) {

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

			String str = st.nextToken();

			boolean[] vis = new boolean[26];

			ArrayList<Character> res = new ArrayList<Character>();

			boolean ispos = true;

			int ix = -1;

			for (char ch : str.toCharArray()) {

				if (vis[ch - 'a']) {

					if (ix - 1 >= 0 && res.get(ix - 1) == ch)

						ix--;

					else if (ix + 1 < res.size() && res.get(ix + 1) == ch)

						ix++;

					else {

						ispos = false;

						break;

					}

				} else {

					if (ix + 1 == res.size()) {

						res.add(ch);

						ix++;

					} else if (ix == 0) {

						res.add(0, ch);

						ix = 0;

					} else {

						ispos = false;

						break;

					}

					vis[ch - 'a'] = true;

				}

				if (!ispos)

					break;

			}

			if (!ispos) {

				pw.println("NO");

			} else {

				pw.println("YES");

				for (char ch : res) {

					pw.print(ch);

				}

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

					if (!vis[i]) {

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

					}

				}

				pw.println();

			}

		}

		pw.close();

	}

}


A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840
OutputCopy7
InputCopy42 42
OutputCopy0
InputCopy48 72
OutputCopy-1
NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.

import java.util.*;
public class Game23 {
    public static void main(String[]args){
        Scanner sc = new Scanner(System.in);
        int a= sc.nextInt();
        int b= sc.nextInt();
        int count=0;
        if(b%a!=0){
            System.out.println(-1);
            return;
        }
        int x=b/a;
        while(x%3==0){
            count++;
            x=x/3;
        }
        while(x%2==0){
            count++;
            x=x/2;
        }
        if(x!=1){
            System.out.println(-1);
            return;
        }
        System.out.println(count);
    }
}