C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105)  — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5
3 1
3 2
3 3
4 0
5 2
OutputCopy4
5
6
0
12
NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement.

import java.awt.MultipleGradientPaint.ColorSpaceType;

import java.io.*;

import java.sql.PreparedStatement;

import java.util.*;

public class cp {

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

//	static  Reader sc=new Reader();

	static FastReader sc=new FastReader(System.in);

	static int[] sp;

	static int size=(int)1e6;

	static int[] arInt;

	static long[] arLong;

	static long ans;

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

		long tc=sc.nextLong();

//		Scanner sc=new Scanner(System.in);

//			int tc=1;

//			print_int(pre);

//			primeSet=new HashSet<>();

//			primeCnt=new int[(int)1e9];

//			sieveOfEratosthenes((int)1e9);

//			factorial(mod);

//			InverseofNumber(mod);

//			InverseofFactorial(mod);

			while(tc-->0)

			{

				long n=sc.nextLong();

				long m=sc.nextLong();

				long ans=n*(n+1)/2;

				long zero=(n-m);

				long grps=m+1;

				long k=zero/grps;

				ans-=(k*(k+1)/2)*grps;

				ans-=(k+1)*(zero%grps);

				out.println(ans);

			}

//			System.out.flush();

			out.flush();

			out.close();

			System.gc();

	}

	/*

	   ...SOLUTION ENDS HERE...........SOLUTION ENDS HERE...

 */

	static class Node{

		int a;

		ArrayList<Pair> adj;

		public Node(int a) {

			this.a=a;

			this.adj=new ArrayList<>();

		}

	}

	static void dijkstra(Node[] g,int dist[],int parent[],int src)

	{

		Arrays.fill(dist, int_max);

		Arrays.fill(parent, -1);

		boolean vis[]=new boolean[dist.length];

//		vis[1]=true;

		PriorityQueue<Pair> q=new PriorityQueue<>();

		q.add(new Pair(1, 0));

		dist[1]=0;

		while(!q.isEmpty())

		{

			Pair curr=q.poll();

			vis[curr.x]=true;

			for(Pair edge:g[curr.x].adj)

			{

				if (vis[edge.x]) {

					continue;

				}

				if (dist[edge.x]>dist[curr.x]+edge.y) {

					dist[edge.x]=dist[curr.x]+edge.y;

					parent[edge.x]=curr.x;

					q.add(new Pair(edge.x, dist[edge.x]));

				}

			}

		}

	}

	static void mapping(int a[])

	{

		Pair[] temp=new Pair[a.length];

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

			temp[i]=new Pair(a[i], i);

		}

		Arrays.sort(temp);

		int k=0;

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

			a[temp[i].y]=k++;

		}

	}

	static boolean palin(String s)

	{

		for(int i=0;i<s.length()/2;i++)

			if(s.charAt(i)!=s.charAt(s.length()-i-1))

				return false;

		return true;

	}

	static class temp implements Comparable<temp>{

		int x;

		int y;

		int sec;

		public temp(int x,int y,int l) {

			// TODO Auto-generated constructor stub

			this.x=x;

			this.y=y;

			this.sec=l;

		}

		@Override

		public int compareTo(cp.temp o) {

			// TODO Auto-generated method stub

			return this.sec-o.sec;

		}

	}

//	static class Node{

//		int x;

//		int y;

//		ArrayList<Integer> edges;

//		public Node(int x,int y) {

//			// TODO Auto-generated constructor stub

//			this.x=x;

//			this.y=y;

//			this.edges=new ArrayList<>();

//		}

//	}

	static int lis(int arr[],int n)

	{

		int ans=0;

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

		Arrays.fill(dp, int_max);

		dp[0]=int_min;

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

		{

			int j=UpperBound(dp,arr[i]);

			if(dp[j-1]<=arr[i] && arr[i]<dp[j])

				dp[j]=arr[i];

		}

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

		{

			if(dp[i]<int_max)

				ans=i;

		}

		return ans;

	}

	static long get(long n)

	{

		return n*(n+1)/2L;

	}

	static boolean go(ArrayList<Pair> caves,int k)

	{

		for(Pair each:caves)

		{

			if(k<=each.x)

				return false;

			k+=each.y;

		}

		return true;

	}

	static String revString(String s)

	{

		char arr[]=s.toCharArray();

		int n=s.length();

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

		{

			char temp=arr[i];

			arr[i]=arr[n-i-1];

			arr[n-i-1]=temp;

		}

		return String.valueOf(arr);

	}

//	Fuction return the number of set bits in n

	static int SetBits(int n)

	{

		int cnt=0;

		while(n>0)

		{

			if((n&1)==1)

			{

				cnt++;

			}

			n=n>>1;

		}

		return cnt;

	}

	static boolean isPowerOfTwo(int n)

    {

        return (int)(Math.ceil((Math.log(n) / Math.log(2))))

            == (int)(Math.floor(((Math.log(n) / Math.log(2)))));

    }

	static void arrInt(int n) throws IOException

	{

		arInt=new int[n];

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

			arInt[i]=sc.nextInt();

		}

	}

	static void arrLong(int n) throws IOException

	{

		arLong=new long[n];

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

			arLong[i]=sc.nextLong();

		}

	}

	static ArrayList<Integer> add(int id,int c)

	{

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

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

			newArr.add(arInt[i]);

		newArr.add(c);

		for(int i=id;i<arInt.length;i++)

		{

			newArr.add(arInt[i]);

		}

		return newArr;

	}

	    // function to find first index >= y

    static int upper(ArrayList<Integer> arr, int n, int x)

    {

    	int l = 0, h = n - 1;

        while (h-l>1)

        {

            int mid = (l + h) / 2;

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

                l=mid+1;

            else

            {

            	h=mid;

            }

        }

        if(arr.get(l)>x)

        {

        	return l;

        }

        if(arr.get(h)>x)

        	return h;

        return -1;

    }

    static int upper(ArrayList<Long> arr, int n, long x)

    {

    	int l = 0, h = n - 1;

    	while (h-l>1)

    	{

    		int mid = (l + h) / 2;

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

    			l=mid+1;

    		else

    		{

    			h=mid;

    		}

    	}

    	if(arr.get(l)>x)

    	{

    		return l;

    	}

    	if(arr.get(h)>x)

    		return h;

    	return -1;

    }

	static int lower(ArrayList<Integer> arr, int n, int x)

    {

        int l = 0, h = n - 1;

        while (h-l>1)

        {

            int mid = (l + h) / 2;

            if (arr.get(mid) < x)

                l=mid+1;

            else

            {

            	h=mid;

            }

        }

        if(arr.get(l)>=x)

        {

        	return l;

        }

        if(arr.get(h)>=x)

        	return h;

        return -1;

    }

	static int N = (int)2e5+5;

	// Array to store inverse of 1 to N

	static long[] factorialNumInverse = new long[N + 1];

	// Array to precompute inverse of 1! to N!

	static long[] naturalNumInverse = new long[N + 1];

	// Array to store factorial of first N numbers

	static long[] fact = new long[N + 1];

	// Function to precompute inverse of numbers

	public static void InverseofNumber(int p)

	{

	    naturalNumInverse[0] = naturalNumInverse[1] = 1;

	    for(int i = 2; i <= N; i++)

	        naturalNumInverse[i] = naturalNumInverse[p % i] *

	                                 (long)(p - p / i) % p;

	}

	// Function to precompute inverse of factorials

	public static void InverseofFactorial(int p)

	{

	    factorialNumInverse[0] = factorialNumInverse[1] = 1;

	    // Precompute inverse of natural numbers

	    for(int i = 2; i <= N; i++)

	        factorialNumInverse[i] = (naturalNumInverse[i] *

	                           factorialNumInverse[i - 1]) % p;

	}

	// Function to calculate factorial of 1 to N

	public static void factorial(int p)

	{

	    fact[0] = 1;

	    // Precompute factorials

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

	    {

	        fact[i] = (fact[i - 1] * (long)i) % p;

	    }

	}

	// Function to return nCr % p in O(1) time

	public static long Binomial(int N, int R, int p)

	{

	    // n C r = n!*inverse(r!)*inverse((n-r)!)

	    long ans = ((fact[N] * factorialNumInverse[R]) %

	                       p * factorialNumInverse[N - R]) % p;

	    return ans;

	}

	static String tr(String s)

	{

		int now = 0;

		while (now + 1 < s.length() && s.charAt(now)== '0')

			++now;

		return s.substring(now);

	}

	static boolean isPrime(long n)

    {

        // Corner cases

        if (n <= 1)

            return false;

        if (n <= 3)

            return true;

        // This is checked so that we can skip

        // middle five numbers in below loop

        if (n % 2 == 0 || n % 3 == 0)

            return false;

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

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

                return false;

        return true;

    }

	static ArrayList<Integer> commDiv(int a, int b)

    {

        // find gcd of a, b

        int n = gcd(a, b);

        // Count divisors of n.

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

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

            // if 'i' is factor of n

            if (n % i == 0) {

                // check if divisors are equal

                if (n / i == i)

                    Div.add(i);

                else

                {

                	Div.add(i);

                	Div.add(n/i);

                }

            }

        }

        return Div;

    }

	static HashSet<Integer> factors(int x)

	{

		HashSet<Integer> a=new HashSet<Integer>();

		for(int i=2;i*i<=x;i++)

		{

			if(x%i==0)

			{

				a.add(i);

				a.add(x/i);

			}

		}

		return a;

	}

	static void primeFactors(int n,HashSet<Integer> factors)

    {

        // Print the number of 2s that divide n

        while (n%2==0)

        {

            factors.add(2);

            n /= 2;

        }

        // n must be odd at this point.  So we can

        // skip one element (Note i = i +2)

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

        {

            // While i divides n, print i and divide n

            while (n%i == 0)

            {

               factors.add(i);

                n /= i;

            }

        }

        // This condition is to handle the case when

        // n is a prime number greater than 2

        if (n > 2)

            factors.add(n);

    }

	static class Tuple{

		int a;

		int b;

		int c;

		public Tuple(int a,int b,int c) {

			this.a=a;

			this.b=b;

			this.c=c;

		}

	}

	//function to find prime factors of n

	static HashMap<Long,Long> findFactors(long n2)

	{

		HashMap<Long,Long> ans=new HashMap<>();

		if(n2%2==0)

		{

			ans.put(2L, 0L);

//			cnt++;

			while((n2&1)==0)

			{

				n2=n2>>1;

				ans.put(2L, ans.get(2L)+1);

//

			}

		}

		for(long i=3;i*i<=n2;i+=2)

		{

			if(n2%i==0)

			{

				ans.put((long)i, 0L);

//				cnt++;

				while(n2%i==0)

				{

					n2=n2/i;

					ans.put((long)i, ans.get((long)i)+1);

				}

			}

		}

		if(n2!=1)

		{

			ans.put(n2, ans.getOrDefault(n2, (long) 0)+1);

		}

		return ans;

	}

	//fenwick tree implementaion

	static class fwt

	{

		int n;

		long BITree[];

		fwt(int n)

		{

			this.n=n;

			BITree=new long[n+1];

		}

		fwt(int arr[], int n)

		{

			this.n=n;

			BITree=new long[n+1];

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

			updateBIT(n, i, arr[i]);

		 }

		   long getSum(int index)

		   {

		       long sum = 0;

		       index = index + 1;

		       while(index>0)

		       {

		           sum += BITree[index];

		           index -= index & (-index);

		       }

		       return sum;

		   }

		   void updateBIT(int n, int index,int val)

		   {

		       index = index + 1;

		       while(index <= n)

		       {

			       BITree[index] += val;

			       index += index & (-index);

		       }

		   }

		   long sum(int l, int r) {

		        return getSum(r) - getSum(l - 1);

		   }

		   void print()

		   {

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

			    out.print(getSum(i)+" ");

			    out.println();

		   }

	}

	static class sparseTable{

		int n;

		long[][]dp;

		int log2[];

		int P;

		void buildTable(long[] arr)

		{

			n=arr.length;

			P=(int)Math.floor(Math.log(n)/Math.log(2));

			log2=new int[n+1];

			log2[0]=log2[1]=0;

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

			{

				log2[i]=log2[i/2]+1;

			}

			dp=new long[P+1][n];

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

			{

				dp[0][i]=arr[i];

			}

			for(int p=1;p<=P;p++)

			{

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

				{

					long left=dp[p-1][i];

					long right=dp[p-1][i+(1<<(p-1))];

					dp[p][i]=Math.min(left, right);

				}

			}

		}

		long maxQuery(int l,int r)

		{

			int len=r-l+1;

			int p=(int)Math.floor(log2[len]);

			long left=dp[p][l];

			long right=dp[p][r-(1<<p)+1];

			return Math.min(left,right);

		}

	}

	//Function to find number of set bits

	static int setBitNumber(long n)

    {

        if (n == 0)

            return 0;

        int msb = 0;

        n = n / 2;

        while (n != 0) {

            n = n / 2;

            msb++;

        }

        return msb;

    }

	static int getFirstSetBitPos(long n)

    {

        return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1;

    }

	static ArrayList<Integer> primes;

	static HashSet<Integer> primeSet;

	static boolean prime[];

	static int primeCnt[];

	static void sieveOfEratosthenes(int n)

    {

       prime= new boolean[n + 1];

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

            prime[i] = true;

        for (int p = 2; p * p <= n; p++)

        {

            // If prime[p] is not changed, then it is a

            // prime

            if (prime[p] == true)

            {

                // Update all multiples of p

                for (int i = p * p; i <= n; i += p)

                    prime[i] = false;

            }

        }

        // Print all prime numbers

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

        {

            if (prime[i] == true)

               primeCnt[i]=primeCnt[i-1]+1;

        }

    }

	static long mod(long a, long b) {

		  long c = a % b;

		  return (c < 0) ? c + b : c;

		}

	static void swap(long arr[],int i,int j)

	{

		long temp=arr[i];

		arr[i]=arr[j];

		arr[j]=temp;

	}

	static boolean util(int a,int b,int c)

	{

		if(b>a)util(b, a, c);

		while(c>=a)

		{

			c-=a;

			if(c%b==0)

				return true;

		}

		return (c%b==0);

	}

	static void flag(boolean flag)

	   {

	       out.println(flag ? "YES" : "NO");

	       out.flush();

	   }

	static void print(int a[])

	  {

	     int n=a.length;

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

	       {

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

	       }

	     out.println();

	     out.flush();

	  }

	static void print(long a[])

	  {

	     int n=a.length;

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

	       {

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

	       }

	     out.println();

	     out.flush();

	  }

	static void print_int(ArrayList<Integer> al)

	  {

	     int si=al.size();

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

	       {

	          out.print(al.get(i)+" ");

	       }

	     out.println();

	     out.flush();

	  }

	static void print_long(ArrayList<Long> al)

	  {

	     int si=al.size();

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

	       {

	          out.print(al.get(i)+" ");

	       }

	     out.println();

	     out.flush();

	  }

	static void printYesNo(boolean condition)

	{

		if (condition) {

			out.println("YES");

		}

		else {

			out.println("NO");

		}

	}

	static int LowerBound(int a[], int x)

	 { // x is the target value or key

	  int l=-1,r=a.length;

	  while(l+1<r) {

	    int m=(l+r)>>>1;

	    if(a[m]>=x) r=m;

	    else l=m;

	  }

	  return r;

	}

	static int lowerIndex(int arr[], int n, int x)

    {

        int l = 0, h = n - 1;

        while (l<=h)

        {

            int mid = (l + h) / 2;

            if (arr[mid] >= x)

                h = mid -1 ;

            else

                l = mid + 1;

        }

        return l;

    }

	    // function to find last index <= y

    static int upperIndex(int arr[], int n, int y)

    {

        int l = 0, h = n - 1;

        while (l <= h)

        {

            int mid = (l + h) / 2;

            if (arr[mid] <= y)

                l = mid + 1;

            else

                h = mid - 1;

        }

        return h;

    }

    static int upperIndex(long arr[], int n, long y)

    {

    	int l = 0, h = n - 1;

    	while (l <= h)

    	{

    		int mid = (l + h) / 2;

    		if (arr[mid] <= y)

    			l = mid + 1;

    		else

    			h = mid - 1;

    	}

    	return h;

    }

	 static int UpperBound(int a[], int x)

	  {// x is the key or target value

	    int l=-1,r=a.length;

	    while(l+1<r) {

	       int m=(l+r)>>>1;

	       if(a[m]<=x) l=m;

	       else r=m;

	    }

	    return l+1;

	 }

	 static int UpperBound(long a[], long x)

	 {// x is the key or target value

		 int l=-1,r=a.length;

		 while(l+1<r) {

			 int m=(l+r)>>>1;

	       if(a[m]<=x) l=m;

	       else r=m;

		 }

		 return l+1;

	 }

	 static class DisjointUnionSets

	 {

	    int[] rank, parent;

	    int n;

	    // Constructor

	    public DisjointUnionSets(int n)

	    {

	        rank = new int[n];

	        parent = new int[n];

	        this.n = n;

	        makeSet();

	    }

	    // Creates n sets with single item in each

	    void makeSet()

	    {

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

	            parent[i] = i;

	    }

	    int find(int x)

	    {

	        if (parent[x] != x) {

	            parent[x] = find(parent[x]);

	        }

	        return parent[x];

	    }

	    // Unites the set that includes x and the set

	    // that includes x

	    void union(int x, int y)

	    {

	        int xRoot = find(x), yRoot = find(y);

	        if (xRoot == yRoot)

	            return;

	        if (rank[xRoot] < rank[yRoot])

	            parent[xRoot] = yRoot;

	        else if (rank[yRoot] < rank[xRoot])

	         parent[yRoot] = xRoot;

	        else // if ranks are the same

	        {

	         parent[yRoot] = xRoot;

	            rank[xRoot] = rank[xRoot] + 1;

	        }

//	        if(xRoot!=yRoot)

//	        	parent[y]=x;

	    }

	    int connectedComponents()

	    {

	    	int cnt=0;

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

	    	{

	    		if(parent[i]==i)

	    			cnt++;

	    	}

	    	return cnt;

	    }

	 }

//	static class Graph

//	  {

//	        int v;

//	        ArrayList<Integer> list[];

//	        Graph(int v)

//	        {

//	            this.v=v;

//	            list=new ArrayList[v+1];

//	            for(int i=1;i<=v;i++)

//	                list[i]=new ArrayList<Integer>();

//	        }

//	        void addEdge(int a, int b)

//	        {

//	            this.list[a].add(b);

//	        }

//

//

//

//	    }

	 static class Pair implements Comparable<Pair>

	    {

	       int x;

	       int y;

	       Pair(int x,int y)

	        {

	           this.x=x;

	           this.y=y;

	        }

		@Override

		public int compareTo(Pair o) {

			// TODO Auto-generated method stub

			return this.y-o.y;

		}

	    }

	 static class PairL implements Comparable<PairL>

	 {

		 long x;

		 long y;

		 PairL(long x,long y)

		 {

			 this.x=x;

			 this.y=y;

		 }

		 @Override

		 public int compareTo(PairL o) {

			 // TODO Auto-generated method stub

			 return (this.y>o.y)?1:-1;

		 }

	 }

	static long sum_array(int a[])

	 {

	    int n=a.length;

	    long sum=0;

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

	     sum+=a[i];

	    return sum;

	 }

	static long sum_array(long a[])

	 {

	    int n=a.length;

	    long sum=0;

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

	     sum+=a[i];

	    return sum;

	 }

	 static void sort(int[] a)

	   {

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

			for (int i:a) l.add(i);

			Collections.sort(l);

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

		}

	static void sort(long[] a)

	   {

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

			for (long i:a) l.add(i);

			Collections.sort(l);

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

		}

	static void reverse_array(int a[])

	 {

	    int n=a.length;

	    int i,t;

	    for (i = 0; i < n / 2; i++) {

	            t = a[i];

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

	            a[n - i - 1] = t;

	        }

	 }

	static void reverse_array(long a[])

	 {

	    int n=a.length;

	    int i; long t;

	    for (i = 0; i < n / 2; i++) {

	            t = a[i];

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

	            a[n - i - 1] = t;

	        }

	 }

//	 static long modInverse(long a, long m)

//		    {

//		        long g = gcd(a, m);

//

//		          return   power(a, m - 2, m);

//

//		    }

	static long power(long x, long y)

	 {

	   long res = 1;

	   x = x % mod;

	   if (x == 0)

	     return 0;

	   while (y > 0)

	   {

	    if ((y & 1) != 0)

	    res = (res * x) % mod;

	    y = y >> 1; // y = y/2

	    x = (x * x) % mod;

	   }

	   return res;

	 }

	static int power(int x, int y)

	{

		int res = 1;

		x = x % mod;

		if (x == 0)

			return 0;

		while (y > 0)

		{

			if ((y & 1) != 0)

				res = (res * x) % mod;

			y = y >> 1; // y = y/2

	    x = (x * x) % mod;

		}

		return res;

	}

	static long gcd(long a, long b)

	    {

	        if (a == 0)

	            return b;

	         //cnt+=a/b;

	        return gcd(b%a,a);

	    }

	static int gcd(int a, int b)

	    {

	        if (a == 0)

	            return b;

	        return gcd(b%a, a);

	    }

	   static class FastReader{

	        byte[] buf = new byte[2048];

	        int index, total;

	        InputStream in;

	        FastReader(InputStream is) {

	            in = is;

	        }

	        int scan() throws IOException {

	            if (index >= total) {

	                index = 0;

	                total = in.read(buf);

	                if (total <= 0) {

	                    return -1;

	                }

	            }

	            return buf[index++];

	        }

	        String next() throws IOException {

	            int c;

	            for (c = scan(); c <= 32; c = scan());

	            StringBuilder sb = new StringBuilder();

	            for (; c > 32; c = scan()) {

	                sb.append((char) c);

	            }

	            return sb.toString();

	        }

	        int nextInt() throws IOException {

	            int c, val = 0;

	            for (c = scan(); c <= 32; c = scan());

	            boolean neg = c == '-';

	            if (c == '-' || c == '+') {

	                c = scan();

	            }

	            for (; c >= '0' && c <= '9'; c = scan()) {

	                val = (val << 3) + (val << 1) + (c & 15);

	            }

	            return neg ? -val : val;

	        }

	        long nextLong() throws IOException {

	            int c;

	            long val = 0;

	            for (c = scan(); c <= 32; c = scan());

	            boolean neg = c == '-';

	            if (c == '-' || c == '+') {

	                c = scan();

	            }

	            for (; c >= '0' && c <= '9'; c = scan()) {

	                val = (val << 3) + (val << 1) + (c & 15);

	            }

	            return neg ? -val : val;

	        }

	    }

	    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  PrintWriter out=new PrintWriter(System.out);

	  static int int_max=Integer.MAX_VALUE;

	  static int int_min=Integer.MIN_VALUE;

	  static long long_max=Long.MAX_VALUE;

	  static long long_min=Long.MIN_VALUE;

}


import java.io.*;

import java.util.*;

public class CF1562C extends PrintWriter {

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

	public static Scanner sc = new Scanner(System.in);

	public static void main(String[] $) {

		CF1562C o = new CF1562C(); o.main(); o.flush();

	}

	static long calculate(long p, long q)

{

    long mod = 1000000007, expo;

    expo = mod - 2;

    // Loop to find the value

    // until the expo is not zero

    while (expo != 0)

    {

        // Multiply p with q

        // if expo is odd

        if ((expo & 1) == 1)

        {

            p = (p * q) % mod;

        }

        q = (q * q) % mod;

        // Reduce the value of

        // expo by 2

        expo >>= 1;

    }

    return p;

}

 static String longestPalSubstr(String str)

    {

        // The result (length of LPS)

        int maxLength = 1;

        int start = 0;

        int len = str.length();

        int low, high;

        // One by one consider every

        // character as center

        // point of even and length

        // palindromes

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

            // Find the longest even

            // length palindrome with

            // center points as i-1 and i.

            low = i - 1;

            high = i;

            while (low >= 0 && high < len

                   && str.charAt(low)

                          == str.charAt(high)) {

                --low;

                ++high;

            }

              // Move back to the last possible valid palindrom substring

            // as that will anyway be the longest from above loop

            ++low; --high;

            if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) {

                start = low;

                maxLength = high - low + 1;

            }

            // Find the longest odd length

            // palindrome with center point as i

            low = i - 1;

            high = i + 1;

            while (low >= 0 && high < len

                   && str.charAt(low)

                          == str.charAt(high)) {

                --low;

                ++high;

            }

              // Move back to the last possible valid palindrom substring

            // as that will anyway be the longest from above loop

            ++low; --high;

            if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) {

                start = low;

                maxLength = high - low + 1;

            }

        }

        return str.substring(start, start + maxLength - 1);

    }

long check(long a){

                 long ret=0;

                 for(long k=2;(k*k*k)<=a;k++){

                  ret=ret+(a/(k*k*k));

                 }

                 return ret;

}

/*public static int getFirstSetBitPos(int n)

	{

		return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1;

	}

	public static int bfsq(int n, int m, HashMap<Integer,ArrayList<Integer>>h,boolean v ){

	                 v[n]=true;

	                 if(n==m)

	                 return 1;

	                 else

	                 {

	                                  int a=h.get(n).get(0);

	                                  int b=h.get(n).get(1);

	                                  if(b>m)

	                                  return(m-n);

	                                  else

	                                  {

	                                                   int a1=bfsq(a,m,h,v);

	                                                   int b1=bfsq(b,m,h,v);

	                                                   return 1+Math.min(a1,b1);

	                                  }

	                 }

	}*/

	static long nCr(int n, int r)

{    return fact(n) / (fact(r) *

                  fact(n - r));

}

// Returns factorial of n

static long fact(long n)

{

    long res = 1;

    for (long i = 2; i <= n; i++)

        res = res * i;

    return res;

}

/*void bfs(int src, HashMap<Integer,ArrayList<Integer,Integer>>h,int deg, boolean v[] ){

                 a[src]=deg;

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

                 q.add(src);

                 while(!q.isEmpty()){

                                  (int a:h.get(src)){

                                                   if()

                                  }

                 }

}*/

	 /*   void dfs(int root, int par, HashMap<Integer,ArrayList<Integer>>h,int dp[], int child[]) {

     dp[root]=0;

    child[root]=1;

     for(int x: h.get(root)){

         if(x == par) continue;

         dfs(x,root,h,in,dp);

         child[root]+=child[x];

     }

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

         for(int x: h.get(root)) {

             if(x == par) continue;

             mine.add(x);

         }

         if(mine.size() >=2){

int y= Math.max(child[mine.get(0)] - 1 + dp[mine.get(1)] , child[mine.get(1)] -1 + dp[mine.get(0)]);

         dp[root]=y;}

else if(mine.size() == 1)

         dp[root]=child[mine.get(0)] - 1;

 }

	   */

class Pair implements Comparable<Pair>{

		int i;

		int j;

	Pair (int a, int b){

		i = a;

	j = b;

	}

	public int compareTo(Pair A){

		return (int)(this.i-A.i);

	}}

/*static class Pair {

        int i;

        int j;

        Pair() {

        }

        Pair(int i, int j) {

            this.i = i;

            this.j = j;

        }

    }*/

          public int[] check(String s) {

             int ans[]= new int[2];

        int maxans = 0;

        int dp[] = new int[s.length()];

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

            if (s.charAt(i) == ')') {

                if (s.charAt(i - 1) == '(') {

                    dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2;

                } else if (i - dp[i - 1] > 0 && s.charAt(i - dp[i - 1] - 1) == '(') {

                    dp[i] = dp[i - 1] + ((i - dp[i - 1]) >= 2 ? dp[i - dp[i - 1] - 2] : 0) + 2;

                }

                if(dp[i]==maxans)

            ans[1]=ans[1]+1;

            if(dp[i]>maxans){

            ans[0]=dp[i];

            ans[1]=1;

                    maxans = Math.max(maxans, dp[i]);}

            }

        }

        if(ans[0]==0)

        ans[1]=1;

        return ans;

    }

 void main() {

int g=sc.nextInt();

for(int w=0;w<g;w++){

long n=sc.nextLong();

long m=sc.nextLong();

	long ans =n *(n + 1) / 2;

	long z = n - m;

	long k = z / (m + 1);

	ans -= (m + 1)*k*(k + 1)/2;

	ans -= (z%(m + 1))*(k + 1);

	println(ans); }

    }

}


C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move:   'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y);  'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y);  'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1);  'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4
4
LRUD
4
LURD
5
RRUDU
5
LLDDR
OutputCopy1 2
1 4
3 4
-1

import static java.lang.Math.max;

import static java.lang.Math.min;

import static java.lang.Math.abs;

import java.util.*;

import java.io.*;

import java.math.*;

public class C_Yet_Another_Walking_Robot {

    static long mod = Long.MAX_VALUE;

    public static void main(String[] args) {

        OutputStream outputStream = System.out;

        PrintWriter out = new PrintWriter(outputStream);

        FastReader f = new FastReader();

        int t = f.nextInt();

        while(t-- > 0){

            solve(f, out);

        }

        out.close();

    }

    public static void solve(FastReader f, PrintWriter out) {

        int n = f.nextInt();

        String s = f.nextLine();

        HashMap<String, Integer> hm = new HashMap<>();

        int ansL = -1;

        int ansR = -1;

        int x = 0;

        int y = 0;

        hm.put(x+":"+y, 0);

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

            if(s.charAt(i) == 'U') {

                y++;

            } else if(s.charAt(i) == 'D') {

                y--;

            } else if(s.charAt(i) == 'L') {

                x--;

            } else {

                x++;

            }

            String pos = x + ":" + y;

            if(hm.containsKey(pos)) {

                int sInd = hm.get(pos)+1;

                int eInd = i+1;

                if((ansL == -1 && ansR == -1) || (eInd-sInd+1 < ansR-ansL+1)) {

                    ansL = sInd;

                    ansR = eInd;

                }

            }

            hm.put(pos, i+1);

        }

        if(ansL == -1 && ansR == -1) {

            out.println(-1);

        } else {

            out.println(ansL + " " + ansR);

        }

    }

    // Sort an array

    public static void sort(int arr[]) {

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

        for(int i: arr) {

            al.add(i);

        }

        Collections.sort(al);

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

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

        }

    }

    // Find all divisors of n

    public static void allDivisors(int n) {

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

            if(n%i == 0) {

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

                if(i != n/i) {

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

                }

            }

        }

    }

    // Check if n is prime or not

    public static boolean isPrime(int n) {

        if(n < 1) return false;

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

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

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

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

                return false;

            }

        }

        return true;

    }

    // Find gcd of a and b

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

        long dividend = a > b ? a : b;

        long divisor =  a < b ? a : b;

        while(divisor > 0) {

            long reminder = dividend % divisor;

            dividend = divisor;

            divisor = reminder;

        }

        return dividend;

    }

    // Find lcm of a and b

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

        long lcm = gcd(a, b);

        long hcf = (a * b) / lcm;

        return hcf;

    }

    // Find factorial in O(n) time

    public static long fact(int n) {

        long res = 1;

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

            res = res * i;

        }

        return res;

    }

    // Find power in O(logb) time

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

        long res = 1;

        while(b > 0) {

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

                res = (res * a)%mod;

            }

            a = (a * a)%mod;

            b >>= 1;

        }

        return res;

    }

    // Find nCr

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

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

            return 0;

        }

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

        return ans;

    }

    // Find nPr

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

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

            return 0;

        }

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

        return ans;

    }

    // sort all characters of a string

    public static String sortString(String inputString) {

        char tempArray[] = inputString.toCharArray();

        Arrays.sort(tempArray);

        return new String(tempArray);

    }

    // User defined class for fast I/O

    static class FastReader {

        BufferedReader br;

        StringTokenizer st;

        public FastReader() {

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

        }

        String next() {

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

                try {

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

                }

                catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        boolean hasNext() {

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

                return true;

            }

            String tmp;

            try {

                br.mark(1000);

                tmp = br.readLine();

                if (tmp == null) {

                    return false;

                }

                br.reset();

            } catch (IOException e) {

                return false;

            }

            return true;

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

        float nextFloat() {

            return Float.parseFloat(next());

        }

        boolean nextBoolean() {

            return Boolean.parseBoolean(next());

        }

        String nextLine() {

            String str = "";

            try {

                str = br.readLine();

            }

            catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

        int[] nextArray(int n) {

            int[] a = new int[n];

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

                a[i] = nextInt();

            }

            return a;

        }

    }

}

/**

Dec  Char                           Dec  Char     Dec  Char     Dec  Char

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

  0  NUL (null)                      32  SPACE     64  @         96  `

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

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

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

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

  5  ENQ (enquiry)                   37  %         69  E        101  e

  6  ACK (acknowledge)               38  &         70  F        102  f

  7  BEL (bell)                      39  '         71  G        103  g

  8  BS  (backspace)                 40  (         72  H        104  h

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

 24  CAN (cancel)                    56  8         88  X        120  x

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

 26  SUB (substitute)                58  :         90  Z        122  z

 27  ESC (escape)                    59  ;         91  [        123  {

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

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

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

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

 */

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

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


D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n)  — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n)  — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
OutputCopy3
InputCopy5 4 2
2 4
1 2
2 3
3 4
4 5
OutputCopy3
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33.   The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.

/*

        "Everything in the universe is balanced. Every disappointment

                you face in life will be balanced by something good for you!

                        Keep going, never give up."

                        Just have Patience + 1...

*/

import java.util.*;

import java.lang.*;

import java.io.*;

public class Solution {

    static int MAX = 200005, INF = 1000000007;

    static Map<Integer, List<Integer>> graph = new HashMap<>();

    static int[][] shortestDistance = new int[2][MAX];

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

        out = new PrintWriter(new BufferedOutputStream(System.out));

        sc = new FastReader();

        int test = 1;

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

            solve();

        }

        out.close();

    }

    private static void solve() {

        int n = sc.nextInt();

        int m = sc.nextInt();

        int k = sc.nextInt();

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

            Arrays.fill(shortestDistance[i], INF);

        }

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

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

            int node = sc.nextInt();

            specialNodes.add(node);

        }

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

            graph.put(i, new ArrayList<>());

        }

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

            int u = sc.nextInt();

            int v = sc.nextInt();

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

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

        }

        bfs(1, 0);

        bfs(n, 1);

        specialNodes.sort(Comparator.comparingInt(a -> (shortestDistance[0][a] - shortestDistance[1][a])));

        int maxShortestPath = 0, maxSpecialDistanceFromStart = -INF;

        for (int node : specialNodes) {

            maxShortestPath = Math.max(maxShortestPath, maxSpecialDistanceFromStart + shortestDistance[1][node]);

            maxSpecialDistanceFromStart = Math.max(maxSpecialDistanceFromStart, shortestDistance[0][node]);

        }

        maxShortestPath++; // special edge length

        out.println(Math.min(maxShortestPath, shortestDistance[0][n]));

    }

    private static void bfs(int startNode, int index) {

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

        shortestDistance[index][startNode] = 0;

        q.add(startNode);

        while (!q.isEmpty()) {

            int currNode = q.poll();

            for (int adjacentNode : graph.get(currNode)) {

                if (shortestDistance[index][adjacentNode] > shortestDistance[index][currNode] + 1) {

                    shortestDistance[index][adjacentNode] = shortestDistance[index][currNode] + 1;

                    q.add(adjacentNode);

                }

            }

        }

    }

    public static FastReader sc;

    public static PrintWriter out;

    static class FastReader

    {

        BufferedReader br;

        StringTokenizer str;

        public FastReader()

        {

            br = new BufferedReader(new

                    InputStreamReader(System.in));

        }

        String next()

        {

            while (str == null || !str.hasMoreElements())

            {

                try

                {

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

                }

                catch (IOException  lastMonthOfVacation)

                {

                    lastMonthOfVacation.printStackTrace();

                }

            }

            return str.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 lastMonthOfVacation)

            {

                lastMonthOfVacation.printStackTrace();

            }

            return str;

        }

    }

}


E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can:  choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive;  take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously.  Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this:  In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3
3 2 1
1 2 3
4 5 6
OutputCopy6
InputCopy4 3
1 2 3
4 5 6
7 8 9
10 11 12
OutputCopy0
InputCopy3 4
1 6 3 4
5 10 7 8
9 2 11 12
OutputCopy2
NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.

import java.io.*;

import java.util.*;

public class E{

	static int n,m;

	static int[][] g;

	static int[][] t;

	static void dbg(int[][] cur) {

		for (int[] x: cur) {

			for (int y: x) out.print(y + " ");

			out.println();

		}

	}

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

		// br = new BufferedReader(new FileReader(".in"));

		// out = new PrintWriter(new FileWriter(".out"));

		//new Thread(null, new (), "peepee", 1<<28).start();

		n = readInt();

		m = readInt();

		g = new int[n][m];

		t = new int[n][m];

		int b = 1;

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

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

				t[i][j] = b++;

				g[i][j] = readInt();

			}

		}

		long cost = 0;

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

			long v = solve(i);

			//System.out.println(v);

			cost += v;

		}

		out.println(cost);

		out.close();

	}

	static void dbg(long[] a) {

		for (long x: a) out.print(x + " ");

		out.println();

	}

	static long solve(int col) {

		long[] r = new long[n];

		long[] r2 = new long[n];

		HashMap<Long, List<Integer>>hm = new HashMap<Long, List<Integer>>();

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

			r[i] = g[i][col];

			r2[i] = t[i][col];

			if (!hm.containsKey(r2[i])) {

				hm.put(r2[i], new ArrayList<Integer>());

			}

			hm.get(r2[i]).add(i);

		}

		long ans = 2*n;

		long[] cycles = new long[n]; // I cycled i times.

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

			if (!hm.containsKey(r[i])) continue;

			for (int x: hm.get(r[i])) {

				// X IS FROM R2 (the correct)

				// I IS FROM R1. (ours)

				if (i >= x) cycles[i-x]++;

				else {

					int newR2Pos = x-n;

					//System.out.println("We saw it at r2 pos " + x + " but our r pos is " + i );

					cycles[i-newR2Pos]++;

				}

			}

		}

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

			long tans = i+n-cycles[i];

			ans = Long.min(ans, tans);

		}

		//System.out.println(ans);

		return ans;

	}

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

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

	static StringTokenizer st = new StringTokenizer("");

	static String read() throws IOException{return st.hasMoreTokens() ? st.nextToken():(st = new StringTokenizer(br.readLine())).nextToken();}

	static int readInt() throws IOException{return Integer.parseInt(read());}

	static long readLong() throws IOException{return Long.parseLong(read());}

	static double readDouble() throws IOException{return Double.parseDouble(read());}

}


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.

//Code By KB.

import java.beans.Visibility;

import java.io.*;

import java.lang.annotation.Target;

import java.lang.reflect.Array;

import java.nio.channels.AsynchronousCloseException;

import java.security.KeyStore.Entry;

import java.util.*;

import java.util.logging.*;

import java.io.*;

import java.util.logging.*;

import java.util.regex.*;

import javax.management.ValueExp;

import javax.print.DocFlavor.INPUT_STREAM;

import javax.print.event.PrintJobListener;

import javax.swing.plaf.basic.BasicBorders.SplitPaneBorder;

import javax.swing.text.AbstractDocument.LeafElement;

import javax.xml.validation.Validator;

public class Codeforces {

	public static void main(String[] args) {

		FlashFastReader in = new FlashFastReader(System.in);

		try(PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));)

		{

			new Codeforces().solution(in, out);

		} catch (Exception e) {

			System.out.println(e.getStackTrace());

		}

	}

	public void solution(FlashFastReader in, PrintWriter out)

	{

		try {

			// int t =in.nextInt();

			// while (t-->0) {

			// }

			int n = in.nextInt();

			int m = in.nextInt();

			if (m%n==0) {

				int d = m/n;

				int res = 0 ;

				while (d%2==0) {

					d/=2;

					res++;

				}

				while (d%3==0) {

					d/=3;

					res++;

				}

				if (d==1) {

					out.println(res);

				} else {

					out.println(-1);

				}

			} else {

				out.println("-1");

			}

		} catch (Exception exception) {

			out.println(exception);

		}

	}

	boolean visited [] = new boolean[1001];

    public int[] topKFrequent(int[] nums, int k) {

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

		int f[] = new int[k];

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

			map.put(nums[i], map.getOrDefault(nums[i], 0)+1);

		}

		//descending oder of values of map  ,here map is the frequency map with key -value pairs

        PriorityQueue<int[]> heap = new PriorityQueue<>(map.size(), (a, b) -> ((int[])b)[1] - ((int[])a)[1]);

		for (Map.Entry<Integer , Integer> e : map.entrySet()) {

			heap.add(new int[]{e.getKey() , e.getValue()});

		}

		int j = 0;

		while (k-->0) {

			int c[] = heap.remove();

			f[j++] = c[0];

		}

		return f;

    }

	public int countSquares(int[][] matrix) {

        int dp [][] = new int [matrix.length+1][matrix[0].length+1];

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

			for (int j = 1; j <=matrix[0].length; j++) {

				if (matrix[i][j]==1) {

					if (i>=1&&j>=1) {

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

					}

				}

				x+=dp[i][j];

			}

		}

		return x;

    }

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

	public int totalNQueens(int n) {

        if (n==1) {

			return 1;

		}

		if (n==2||n==3) {

			return 0;

		}

		dfsNqueens( map ,  0  , n );

		return x;

    }

	public void dfsNqueens( HashMap<Integer, Integer>map ,  int col  , int n  ) {

		if (col == n) {

			x++;

			return;

		}

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

			map.put(col, i);

			boolean f = true;

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

				if (map.containsKey(j)) {

					if (map.get(j)==i||Math.abs(col - j)==Math.abs(map.get(j)-i) ) {

						f = false;

					}

				}

			}

			if (f) {

				dfsNqueens(map, col+1, n);

			}

		}

	}

	public int[] minOperations(String boxes) {

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

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

			StringBuilder sb =  new StringBuilder(boxes);

			int x = 0;

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

				if (sb.indexOf("1")<0) {

					break;

				}

				x+=Math.abs(i - sb.indexOf("1"));

				sb.setCharAt(sb.indexOf("1"), '0');

			}

			a[i] = x;

		}

		return a;

    }

	public List<List<Integer>> subsets(int[] nums) {

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

		subsetsGen(0, nums , curr);

		return list;

    }

	public void subsetsGen(int j ,int[] n , List<Integer>curr) {

		list.add(curr);

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

			curr.add(n[i]);

			subsetsGen(j+1, n, curr);

			curr.remove(curr.size()-1);

		}

	}

	public int findCircleNum(int[][] isConnected) {

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

			if (visited[i]!=true) {

				x++;

				dfsFindProvinces( i , isConnected  );

			}

		}

		return x;

    }

	public void dfsFindProvinces( int i ,int [][]isConnected  ) {

		visited[i]=true;

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

			if (isConnected[i][j]==1&&visited[j]!=true) {

				dfsFindProvinces(j, isConnected);

			}

		}

	}

	public int[] canSeePersonsCount(int[] heights) {

		int ans [] = new int[heights.length];

		Stack<Integer> stck = new Stack<>();

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

			while(!stck.isEmpty()&&heights[stck.peek()]<heights[i]) {

				ans[stck.pop()]++;

			}

			if (!stck.isEmpty()) {

				ans[stck.peek()]++;

			}

			stck.push(i);

		}

		return ans;

    }

	public int pathSum(TreeNode root, int targetSum) {

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

        dsfPathSum(root, targetSum , 0 ,path);

		pathSum(root.left, targetSum);

		pathSum(root.right, targetSum);

		for (List<Integer> p : list) {

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

				System.out.print(p.get(i)+" ");

			}

			System.out.println();

		}

        return list.size();

    }

    public void dsfPathSum(TreeNode root , int t , long sum , List<Integer>path ) {

		if (root==null) {

			return;

		}

		sum+=root.val ;

		path.add(root.val);

		if (sum==t) {

			list.add(path);

		}

		dsfPathSum(root.left, t, sum , path);

		dsfPathSum(root.right, t, sum , path);

	}

	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode l = new ListNode();

		int a = 0;

		int b =0;

		l1 = reverseList(l1);

		l2 = reverseList(l2);

		while (l1!=null) {

			a=a*10+l1.val;

			l1=l1.next;

		}

		while (l2!=null) {

			b=b*10+l2.val;

			l2=l2.next;

		}

		a=a+b;

		ListNode head = null;

		while (a!=0) {

			int r = a%10;

			if(l==null) {

				head= new ListNode(r);

				l=head;

			}else {

				l.next = new ListNode(r);

				l= l.next;

				}

			a/=10;

		}

		return head;

    }

	public ListNode reverseList(ListNode head) {

        if(head==null || head.next==null)

            return head;

        ListNode nextNode=head.next;

        ListNode newHead=reverseList(nextNode);

        nextNode.next=head;

        head.next=null;

        return newHead;

    }

	int x=0;

	public int uniquePathsIII(int[][] grid) {

		int zeros = 0;

		int sx=0;

		int sy =0;

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

			for (int j = 0; j < grid[0].length; j++) {

				if (grid[i][j]==0) {

					zeros++;

				} else if (grid[i][j]==1) {

					sx=i;

					sy=j;

				}

			}

		}

		dfsUniquePaths(zeros , sx , sy , grid);

		return x;

    }

	public void dfsUniquePaths(int zeros ,int  i ,int  j , int g[][]) {

		if (i<0||i>=g.length||j>=g[0].length||j<0||g[i][j]<0) {

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

			return;

		}

		if (g[i][j]==2) {

			if(zeros==0)

				x++;

			return;

		}

		g[i][j]=-2;

		zeros--;

		dfsUniquePaths(zeros, i+1, j, g);

		dfsUniquePaths(zeros, i-1, j, g);

		dfsUniquePaths(zeros, i, j+1, g);

		dfsUniquePaths(zeros, i, j-1, g);

		g[i][j]=0;

		zeros++;

	}

	public TreeNode addOneRow(TreeNode root, int val, int depth) {

        if (depth==1) {

			TreeNode t  = new TreeNode(val);

			t.left=root;

			return t;

		}

		dfsAddOneRow(root , 1 , val , depth);

		return root;

    }

	public void dfsAddOneRow(TreeNode root , int currD , int  val , int depth) {

		if (root==null) {

			return ;

		}

		if (currD==depth) {

			TreeNode l = root.left;

			root.left = new TreeNode(val);

			root.left.left = l;

			TreeNode r = root.right;

			root.right = new TreeNode(val);

			root.right.right = r;

		}

		currD++;

		dfsAddOneRow(root.left, currD, val, depth);

		dfsAddOneRow(root.right, currD, val, depth);

	}

    public List<List<Integer>> threeSum(int[] nums) {

		int n = nums.length;

		int sum =0;

		HashSet<List<Integer>> h = new HashSet<List<Integer>>();

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

			sum=nums[i];

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

			}

		}

		return list;

    }

	public int uniquePaths(int m, int n) {

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

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

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

				if(i==0&&j==0) {

					dp[i][j]=1;

				} else if (i==0) {

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

				} else if (j==0) {

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

				} else {

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

				}

			}

		}

		return dp[m-1][n-1];

    }

	public int maxProfit(int[] prices) {

        int p = -1;

		return p ;

    }

	public int trap(int[] height) {

		int n = height.length;

		int left[] = new int [n];

		int right[] = new int [n];

		left[0] = height[0];

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

			left[i] = Math.max(height[i], left[i-1]);

		}

		right[n-1]=height[n-1];

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

			right[i] = Math.max(height[i], right[i+1]);

		}

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

			int s =Math.min(left[i] , right[i])-height[i];

			if (s>0) {

				x+=s;

			}

		}

		return x;

    }

    public int maxProduct(int[] nums) {

        int maxSoFar = Integer.MIN_VALUE;

		int maxTillEnd = 0;

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

			maxTillEnd*=nums[i];

			if (maxSoFar<maxTillEnd) {

				maxSoFar=maxTillEnd;

			}

			if (maxTillEnd<=0) {

				maxTillEnd=1;

			}

		}

		return maxSoFar;

    }

	public int maximumScore(int[] nums, int[] multipliers) {

		int n = multipliers.length;

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

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

			for (int j = 1; j < nums.length; j++) {

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

			}

		}

        return dp[n];

    }

	public int islandPerimeter(int[][] grid) {

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

			for (int j = 0; j < grid[0].length; j++) {

				if(grid[i][j]==1){

					dfsIslandPerimeter(i , j , grid);

				}

			}

		}

		return x;

    }

	public void dfsIslandPerimeter(int i , int j , int[][] grid) {

		if(i<0||i>=grid.length||j<0||j>grid[0].length) {

			x++;

			return;

		}

		if(grid[i][j]==0) {

			x++;

			return;

		}

		if(grid[i][j]==1) {

			return;

		}

		dfsIslandPerimeter(i+1, j, grid);

		dfsIslandPerimeter(i-1, j, grid);

		dfsIslandPerimeter(i, j+1, grid);

		dfsIslandPerimeter(i, j-1, grid);

	}

	public int[] findOriginalArray(int[] changed) {

		int n =changed.length;

		int m = n/2;

        int a[] = new int[m];

		if (n<2) {

			return new int[]{};

		}

		if (n%2!=0) {

			return new int[]{};

		}

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

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

			map.put(changed[i], map.getOrDefault(changed[i] ,0)+1);

		}

		int j =0;

		for (Map.Entry<Integer , Integer> e : map.entrySet()) {

			if (map.containsKey(e.getKey()*2)&&map.get(e.getKey()*2)>=1&&map.get(e.getKey())>=1) {

				map.put(e.getKey(), map.get(e.getKey()) -1);

				if(j==n-1)

					break;

				a[j++] = e.getKey();

			}

		}

		return a;

    }

	public int jump(int[] nums) {

        int n =nums.length;

		int jumps =1;

		int i =0;

		int j =0;

		while (i<n) {

			int max =0;

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

				max = Math.max(max , nums[j]+j);

			}

			jumps++;

			i=max;

		}

		return jumps;

    }

	static void sort(int[] arr) {

        if (arr.length < 2) return;

        int mid = arr.length / 2;

        int[] left_half = new int[mid];

        int[] right_half = new int[arr.length - mid];

        // copying the elements of array into left_half

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

            left_half[i] = arr[i];

        }

        // copying the elements of array into right_half

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

            right_half[i - mid] = arr[i];

        }

        sort(left_half);

        sort(right_half);

        merge(arr, left_half, right_half);

    }

    static void merge(int[] arr, int[] left_half, int[] right_half) {

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

        while (i < left_half.length && j < right_half.length) {

            if (left_half[i] < right_half[j]) {

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

            }

            else {

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

            }

        }

        while (i < left_half.length) {

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

        }

        while (j < right_half.length) {

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

        }

    }

	public int minCostClimbingStairs(int[] cost) {

		int n = cost.length;

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

		dp[1] = cost[0];

		dp[2] = cost[1];

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

			dp[i]=cost[i-1]+Math.min(dp[i-1], dp[i-2]);

		}

		return dp[n];

    }

	TreeNode newAns =null;

    public TreeNode removeLeafNodes(TreeNode root, int target) {

		newAns = root;

        dfsRemoveNode(newAns , target);

		return newAns;

    }

	public void dfsRemoveNode(TreeNode root , int t) {

		if (root==null) {

			return;

		}

		if (root.val==t) {

			if (root.left!=null) {

				root=root.left;

			}else if (root.right!=null){

				root=root.right;

			} else {

				root=null;

			}

		}

		dfsRemoveNode(root.left, t);

		dfsRemoveNode(root.right, t);

	}

	public int maxProfit(int k, int[] prices) {

		int n = prices.length;

		if (n <= 1)

			return 0;

		if (k >=  n/2) {

			return stocks(prices, n);

		}

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

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

			int c= dp[i-1][0] - prices[0];

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

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

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

			}

		}

		return dp[k][n-1];

	}

	public int stocks(int [] prices , int n ) {

		int maxPro = 0;

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

				if (prices[i] > prices[i-1])

					maxPro += prices[i] - prices[i-1];

			}

		return maxPro;

	}

    public List<List<Integer>> combine(int n, int k) {

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

        combinations( n , k  , 1 ,x);

		return list;

    }

	public void combinations(int n , int k ,int startPos , List<Integer> x) {

		if (k==x.size()) {

			list.add(new ArrayList<>(x));

			//x=new ArrayList<>();

			return;

		}

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

			x.add(i);

			combinations(n, k, i+1, x);

			x.remove(x.size()-1);

		}

	}

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

	public List<List<Integer>> permute(int[] a) {

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

        permutations(a , 0 ,a.length ,x );

		return list ;

    }

	public void permutations(int a[] , int startPos , int l , List<Integer>x) {

		if (l==x.size()) {

			list.add(new ArrayList<>(x));

			//x=new ArrayList<>();

		}

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

			if (!x.contains(a[i])) {

				x.add(a[i]);

				permutations(a, i, l, x);

				x.remove(x.size()-1);

			}

		}

	}

	List<String> str = new ArrayList<>();

	public List<String> letterCasePermutation(String s) {

		casePermutations(s , 0 , s.length() , "" );

        return str;

    }

	public void casePermutations(String s ,int i , int l , String curr) {

		if (curr.length()==l) {

			str.add(curr);

			return;

		}

		char b = s.charAt(i);

		curr+=b;

		casePermutations(s, i+1, l, curr);

		curr = new StringBuilder(curr).deleteCharAt(curr.length()-1).toString();

		if (Character.isAlphabetic(b)&&Character.isLowerCase(b)) {

			curr+=Character.toUpperCase(b);

			casePermutations(s, i+1, l, curr);

			curr = new StringBuilder(curr).deleteCharAt(curr.length()-1).toString();

		} else if (Character.isAlphabetic(b)) {

			curr+=Character.toLowerCase(b);

			casePermutations(s, i+1, l, curr);

			curr = new StringBuilder(curr).deleteCharAt(curr.length()-1).toString();

		}

	}

	TreeNode ans= null;

	public TreeNode lcaDeepestLeaves(TreeNode root) {

		dfslcaDeepestLeaves(root , 0 );

        return ans;

    }

	public void dfslcaDeepestLeaves(TreeNode root , int level) {

		if (root==null) {

			return;

		}

		if (depth(root.left)==depth(root.right)) {

			ans= root;

			return;

		} else if (depth(root.left)>depth(root.right)){

			dfslcaDeepestLeaves(root.left, level+1);

		} else {

			dfslcaDeepestLeaves(root.right, level+1);

		}

	}

	public int depth(TreeNode root) {

		if (root==null) {

			return 0;

		}

		return 1+Math.max(depth(root.left), depth(root.right));

	}

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

	public int maxLevelSum(TreeNode root) {

        int maxlevel =0;

		int mx = Integer.MIN_VALUE;

		dfsMaxLevelSum(root , 0);

		for (Map.Entry<Integer,Integer> e : m.entrySet()) {

			if (e.getValue()>mx) {

				mx=e.getValue();

				maxlevel=e.getKey()+1;

			}

		}

		return maxlevel;

    }

	public void dfsMaxLevelSum(TreeNode root , int currLevel) {

		if (root==null) {

			return;

		}

		if (!m.containsKey(currLevel)) {

			m.put(currLevel, root.val);

		} else {

			m.put(currLevel, m.get(currLevel)+root.val);

		}

		dfsMaxLevelSum(root.left, currLevel+1);

		dfsMaxLevelSum(root.right, currLevel+1);

	}

	int teampPerf = 0;

	int teampSpeed = 0;

    public int maxPerformance(int n, int[] speed, int[] efficiency, int k) {

		int [][] map = new int[efficiency.length][2];

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

			map[i][0] = efficiency[i];

			map[i][1] = speed[i];

		}

		Arrays.sort(map , (e1 , e2 )-> (e2[0] - e1[0]));

		PriorityQueue<Integer> pq = new PriorityQueue<>();

		calmax(map  , speed , efficiency , pq , k);

		return teampPerf ;

    }

	public void calmax(int [][]map , int s[] , int e[] , PriorityQueue<Integer>pq , int k) {

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

			if (pq.size()==k) {

				int lowestSpeed =pq.remove();

				teampSpeed-=lowestSpeed;

			}

			pq.add(map[i][1]);

			teampSpeed+=map[i][1];

			teampPerf=Math.max(teampPerf, teampSpeed*map[i][1]);

		}

	}

	int maxRob = 0;

	public int rob(int[] nums) {

		int one = 0;

		int two = 0;

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

			if (i%2==0) {

				one+=nums[i];

			} else {

				two+=nums[i];

			}

		}

		return Math.max(one, two);

    }

	public int numberOfWeakCharacters(int[][] properties) {

		int c =0;

		Arrays.sort(properties, (a, b) -> (b[0] == a[0]) ? (a[1] - b[1]) : b[0] - a[0]);

		PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());

		pq.offer(0);

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

			if (properties[i][1]<pq.peek()) {

				c++;

			}

			pq.offer(properties[i][1]);

		}

		return c;

    }

	public boolean canFinish(int numCourses, int[][] prerequisites) {

        boolean f = true ;

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

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

			if (map.get(prerequisites[i][1])!=null) {

				return false;

			}

				map.put(prerequisites[i][0], prerequisites[i][1]);

		}

		return f;

    }

	int n =0;

	public int dfsB(int i , int j , char [][]b , char [][]res) {

		if (i<0||i>=b.length|j<0||j>=b[0].length||res[i][j]=='.') {

			return 0;

		}

		if (res[i][j]=='X') {

			return 1+dfsB(i+1, j, b, res)+dfsB(i, j+1, b, res);

		}

		return 0;

	}

	 public class ListNode {

	     int val;

	     ListNode next;

	     ListNode() {}

	     ListNode(int val) { this.val = val; }

	     ListNode(int val, ListNode next) { this.val = val; this.next = next; }

	 }

	 public ListNode middleNode(ListNode head) {

        ListNode mid = head;

		ListNode last = head;

		int k =0;

		while (last.next!=null&&last.next.next!=null) {

			k++;

			mid= mid.next;

			last = last.next.next;

		}

		if (getLen(head)%2==0) {

			return mid.next;

		}

		return mid;

    }

	public int getLen(ListNode mid) {

		int l = 0;

		ListNode p = mid;

		while (p!=null) {

			l++;

			p=p.next;

		}

		return l;

	}

	public class TreeNode {

		int val;

		     TreeNode left;

		     TreeNode right;

		     TreeNode() {}

		     TreeNode(int val) { this.val = val; }

		     TreeNode(int val, TreeNode left, TreeNode right) {

		         this.val = val;

		         this.left = left;

		         this.right = right;

		     }

		 }

    public List<List<Integer>> verticalTraversal(TreeNode root) {

        TreeMap<Integer, TreeMap<Integer, PriorityQueue<Integer>>> map = new TreeMap<>();

        dfs(root, 0, 0, map);

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

        for (TreeMap<Integer, PriorityQueue<Integer>> ys : map.values()) {

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

            for (PriorityQueue<Integer> nodes : ys.values()) {

                while (!nodes.isEmpty()) {

                    // list.get(list.size() - 1).add(nodes.poll());

                }

            }

        }

        return list;

    }

    private void dfs(TreeNode root, int x, int y, TreeMap<Integer, TreeMap<Integer, PriorityQueue<Integer>>> map) {

        if (root == null) {

            return;

        }

        if (!map.containsKey(x)) {

            map.put(x, new TreeMap<>());

        }

        if (!map.get(x).containsKey(y)) {

            map.get(x).put(y, new PriorityQueue<>());

        }

        map.get(x).get(y).offer(root.val);

        dfs(root.left, x - 1, y + 1, map);

        dfs(root.right, x + 1, y + 1, map);

    }

	public long pow (int x ,int n ) {

		long y = 1;

		if (n==0) {

			return y;

		}

		while (n>0) {

			if (n%2!=0) {

				y=y*x;

			}

			x*=x;

			n/=2;

		}

		return y;

	}

	public long powrec (int x ,int n ) {

		long y = 1;

		if (n==0) {

			return y;

		}

		y = powrec(x, n/2);

		if (n%2==0) {

			return y*y;

		}

		return y*y*x;

	}

	public int fib(int n) {

		if (n==0||n==11) {

			return n;

		}

		return fib(n-1)+fib(n-2);

	}

	public long gcd(long a , long b)

	{

		if (b%a==0) {

			return a;

		}

		return gcd(b%a,a);

	}

	public int maximumElement(int a[])

	{

		int x = Integer.MIN_VALUE;

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

			 if (a[i]>x) {

				x=a[i];

			 }

		}

		return x;

	}

	public int minimumElement(int a[])

	{

		int x = Integer.MAX_VALUE;

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

			 if (a[i]<x) {

				x=a[i];

			 }

		}

		return x;

	}

	public static boolean[] SieveOfEratosthenes(int num)

	{

		boolean[] isPrime = new boolean[num + 1];

		for (int i = 2; i <= num; i++) isPrime[i] = true;

		// Removing multiples.

		for (int i = 2; i <= num; i++)

		{

			if (isPrime[i])

			{

				for (int j = i * 2; j <= num; j += i)

					isPrime[j] = false; // Eliminate multiples of i.

			}

		}

		return isPrime;

	}

	// GFG arraylist function for referral

	public ArrayList create2DArrayList(int n ,int k)

    {

        // Creating a 2D ArrayList of Integer type

        ArrayList<ArrayList<Integer> > x

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

        // One space allocated for R0

        // Adding 3 to R0 created above x(R0, C0)

        //x.get(0).add(0, 3);

		int xr = 0;

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

			if ((i+k)*(i+1)%4==0) {

				x.add(new ArrayList<Integer>());

				x.get(xr).addAll(Arrays.asList(i , i+1));

			}

			else {

				x.add(new ArrayList<Integer>());

				x.get(xr).addAll(Arrays.asList(i+1 , i));

			}

			xr++;

		}

        // Creating R1 and adding values

        // Note: Another way for adding values in 2D

        // collections

        // x.add(

        //     new ArrayList<Integer>(Arrays.asList(3, 4, 6)));

        // // Adding 366 to x(R1, C0)

        // x.get(1).add(0, 366);

        // // Adding 576 to x(R1, C4)

        // x.get(1).add(4, 576);

        // // Now, adding values to R2

        // x.add(2, new ArrayList<>(Arrays.asList(3, 84)));

        // // Adding values to R3

        // x.add(new ArrayList<Integer>(

        //     Arrays.asList(83, 6684, 776)));

        // // Adding values to R4

        // x.add(new ArrayList<>(Arrays.asList(8)));

        // // Appending values to R4

        // x.get(4).addAll(Arrays.asList(9, 10, 11));

        // // Appending values to R1, but start appending from

        // // C3

        // x.get(1).addAll(3, Arrays.asList(22, 1000));

        // This method will return 2D array

        return x;

    }

}

class FlashFastReader

{

	BufferedReader in;

	StringTokenizer token;

	public FlashFastReader(InputStream ins)

	{

		in=new BufferedReader(new InputStreamReader(ins));

		token=new StringTokenizer("");

	}

	public boolean hasNext()

	{

		while (!token.hasMoreTokens())

		{

			try

			{

				String s = in.readLine();

				if (s == null) return false;

				token = new StringTokenizer(s);

			} catch (IOException e)

			{

				throw new InputMismatchException();

			}

		}

		return true;

	}

	public String next()

	{

		hasNext();

		return token.nextToken();

	}

	public int nextInt()

	{

		return Integer.parseInt(next());

	}

	public int[] nextIntsInputAsArray(int n)

	{

		int[] res = new int[n];

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

			res[i] = nextInt();

		return res;

	}

	public long nextLong() {

		return Long.parseLong(next());

	}

	public long[] nextLongsInputAsArray(int n)

	{

		long [] a = new long[n];

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

			a[i] = nextLong();

		return a;

	}

	public String nextString() {

		return String.valueOf(next());

	}

	public String[] nextStringsInputAsArray(int n)

	{

		String [] a = new String[n];

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

			a[i] = nextString();

		return a;

	}

}


E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6
-100 -200 -300 125 77 -4
OutputCopy9
InputCopy1000000000000 5
-1 0 0 0 0
OutputCopy4999999999996
InputCopy10 4
-3 -6 5 4
OutputCopy-1

//package superherobattle;

import java.util.*;

import java.io.*;

public class superherobattle {

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

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

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

		long h = Long.parseLong(st.nextToken());

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

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

		long[] nums = new long[n];

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

			nums[i] = Long.parseLong(st.nextToken());

		}

		long[] pfxMin = new long[n];

		long min = Integer.MAX_VALUE;

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

			if(i == 0) {

				pfxMin[0] = nums[0];

			}

			else {

				pfxMin[i] = pfxMin[i - 1] + nums[i];

			}

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

		}

		long diff = pfxMin[n - 1];

		if(diff >= 0) {

			if(h + min <= 0) {

				long ans = 0;

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

					ans ++;

					if(h + pfxMin[i] <= 0) {

						break;

					}

				}

				System.out.println(ans);

			}

			else {

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

			}

		}

		else {

			long ans = 0;

			if(h + min > 0) {

				long toMin = h + min;

				long cycles = Math.abs(Math.abs(toMin / diff) + (toMin % diff != 0? 1 : 0));

				ans += cycles * n;

				//System.out.println(cycles);

				h += cycles * diff;

			}

			//System.out.println(h);

			if(h > 0) {

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

					ans ++;

					if(h + pfxMin[i] <= 0) {

						break;

					}

				}

			}

			System.out.println(ans);

		}

	}

}


import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.util.HashMap;

import java.util.Objects;

public class YetAnotherWalkingRobot {

    static BufferedReader br;

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

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

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

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

    }

    static void test() throws Exception {

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

        String s = br.readLine();

        Point p = new Point(0, 0);

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

        map.put(p, 1);

        int[] min = new int[2];

        min[0] = -1000000000;

        min[1] = 1000000000;

        boolean got = false;

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

            p = new Point(p.x, p.y);

            if (s.charAt(i) == 'L') p.x--;

            else if (s.charAt(i) == 'R') p.x++;

            else if (s.charAt(i) == 'U') p.y++;

            else p.y--;

            if (map.containsKey(p)) {

                int start = map.get(p);

                int minDist = min[1] - min[0];

                int dist = (i + 1) - start;

                if (dist < minDist) {

                    min[1] = (i + 1);

                    min[0] = start;

                    got = true;

                }

                map.put(p, i + 2);

            } else map.put(p, i + 2);

        }

        if (got) System.out.println(min[0] + " " + min[1]);

        else System.out.println(-1);

    }

    static class Point {

        public long x, y;

        public Point(long x, long y) {

            this.x = x;

            this.y = y;

        }

        @Override

        public boolean equals(Object o) {

            if (this == o) return true;

            if (o == null || getClass() != o.getClass()) return false;

            Point point = (Point) o;

            return x == point.x && y == point.y;

        }

        @Override

        public int hashCode() {

            return Objects.hash(x, y);

        }

    }

}


import java.io.*;

import java.util.*;

public class ProblemB {

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

		Scanner s = new Scanner();

		StringBuilder sb = new StringBuilder();

		int test = s.readInt();

		while(test-->0){

			int n = s.readInt();

			String ss = s.readLine();

			int x =0,y = 0;

			String pos = x+" "+y;

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

			String ans = "";

			int min = Integer.MAX_VALUE;

			map.put(pos, -1);

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

				if(ss.charAt(i) == 'R')x++;

				else if(ss.charAt(i) == 'U')y++;

				else if(ss.charAt(i) == 'D')y--;

				else x--;

				pos = x+" "+y;

				if(map.containsKey(pos)){

					int dis = i - map.get(pos)+1 ;

					if(dis<min){

						min = dis;

						ans = map.get(pos)+2 +" "+(i+1);

					}

				}

				map.put(pos, i);

			}

			System.out.println(min==Integer.MAX_VALUE?-1:ans);

		}

		System.out.println(sb);

	}

	static class Pair{

		int x,y;

		public Pair(int x,int y){

			this.x = x;

			this.y = y;

		}

	}

	static class Scanner{

		BufferedReader br;

		StringTokenizer st;

		public Scanner(){

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

		}

	    public String read()

	    {

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

	            try {	st = new StringTokenizer(br.readLine()); }

	            catch (Exception e) {	e.printStackTrace(); }

	         }

	         return st.nextToken();

	     }

	     public int  readInt() { return Integer.parseInt(read()); }

	     public long readLong() { return Long.parseLong(read()); }

	     public double readDouble(){return Double.parseDouble(read());}

	     public String readLine() throws IOException{ return br.readLine(); }

	}

}


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.util.InputMismatchException;

import java.io.IOException;

import java.io.Writer;

import java.io.OutputStreamWriter;

import java.io.InputStream;

import java.util.*;

import java.util.ArrayList;

public class Main{

    public static void main(String[] args){

        Scanner in = new Scanner(System.in);

        int t;

        // t = in.nextInt();

        t = 1;

        while(t>0){

            int n,m;

            n = in.nextInt();

            m = in.nextInt();

            if(n==m){

                System.out.println(0);

                t--;

                continue;

            }

            HashMap<Integer,Integer> mp1 = new HashMap<>();

            HashMap<Integer,Integer> mp2 = new HashMap<>();

            double x2 = Math.sqrt(n);

            int val1 = (int)x2;

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

                while(n%i==0){

                    n /= i;

                    if(mp1.containsKey(i)){

                        int x = mp1.get(i);

                        mp1.put(i,++x);

                    }

                    else{

                        mp1.put(i,1);

                    }

                }

            }

            if(n!=1){

                if(mp1.containsKey(n)){

                    int x = mp1.get(n);

                    mp1.put(n,++x);

                }

                else{

                    mp1.put(n,1);

                }

            }

            x2 = Math.sqrt(m);

            int val2 = (int)x2;

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

                while(m%i==0){

                    m /= i;

                    if(mp2.containsKey(i)){

                        int x = mp2.get(i);

                        mp2.put(i,++x);

                    }

                    else{

                        mp2.put(i,1);

                    }

                }

            }

            if(m!=1){

                if(mp2.containsKey(m)){

                    int x = mp2.get(m);

                    mp2.put(m,++x);

                }

                else{

                    mp2.put(m,1);

                }

            }

            Boolean flag = false;

            for (Integer key: mp1.keySet()) {

                int value = mp1.get(key);

                if(mp2.containsKey(key)==false){

                    System.out.println(-1);

                    flag = true;

                    break;

                }

            }

            if(flag==false){

                for (Integer key: mp2.keySet()) {

                int value = mp2.get(key);

                if(mp1.containsKey(key)==false && key!=2 && key!=3){

                    System.out.println(-1);

                    flag = true;

                    break;

                }

            }

            }

            if(flag==false){

                val1 = 0;

                val2 = 0;

                if(mp1.containsKey(2)){

                    val1 = mp1.get(2);

                }

                if(mp2.containsKey(2)){

                    int x = mp2.get(2);

                    val1 = x - val1;

                }

                if(mp1.containsKey(3)){

                    val2 = mp1.get(3);

                }

                if(mp2.containsKey(3)){

                    int x = mp2.get(3);

                    val2 = x - val2;

                }

                if(mp1.containsKey(2)==true && mp2.containsKey(2)==false){

                    System.out.println(-1);

                }

                else if(mp1.containsKey(3)==true && mp2.containsKey(3)==false){

                    System.out.println(-1);

                }

                else if(val1<0 || val2<0){

                    System.out.println(-1);

                }

                else{

                    val1 += val2;

                    System.out.println(val1);

                }

            }

            t--;

        }

    }

}