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

		}

	}

}


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

        }

    }

}


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

import java.io.OutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.PrintWriter;

import java.util.Arrays;

import java.io.IOException;

import java.util.TreeSet;

import java.util.ArrayList;

import java.util.Comparator;

import java.util.Collections;

import java.io.InputStream;

/**

 * Built using CHelper plug-in

 * Actual solution is at the top

 *

 * @author Indrajit Sinha

 */

public class Main {

	public static void main(String[] args) {

		InputStream inputStream = System.in;

		OutputStream outputStream = System.out;

		InputReader in = new InputReader(inputStream);

		PrintWriter out = new PrintWriter(outputStream);

		EMessengerSimulator solver = new EMessengerSimulator();

		solver.solve(1, in, out);

		out.close();

	}

	static class EMessengerSimulator {

		int n;

		PrintWriter out;

		InputReader in;

		final Comparator<Query> com = new Comparator<Query>() {

			public int compare(Query x, Query y) {

				int xx = Integer.compare(x.r, y.r);

				if (xx == 0)

					return Integer.compare(x.l, y.l);

				return xx;

			}

		};

		public void solve(int testNumber, InputReader in, PrintWriter out) {

			int t, i, j, tt, k;

			this.out = out;

			this.in = in;

			n = in.nextInt();

			int m = in.nextInt();

			int a[] = new int[m];

			int[] mn, mx;

			mn = new int[n];

			mx = new int[n];

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

				mn[i] = i;

				mx[i] = i;

			}

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

				a[i] = in.nextInt() - 1;

				mn[a[i]] = 0;

			}

			ArrayList<Integer> ar[] = new ArrayList[n];

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

				ar[i] = new ArrayList<>();

			}

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

				ar[a[i]].add(i);

			}

			TreeSet<Integer> ts = new TreeSet<>();

			SegmenTree sg = new SegmenTree();

			sg.build(n);

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

				if (ts.contains(a[i]))

					continue;

				mx[a[i]] = Math.max(mx[a[i]], a[i] + sg.query(a[i] + 1, n));

				ts.add(a[i]);

				sg.updateTreeNode(a[i], 1);

			}

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

				if (ar[i].size() == 0) {

					mx[i] = Math.max(mx[i], i + sg.query(i + 1, n));

				}

			}

			ArrayList<Query> queries = new ArrayList<>();

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

				if (i == 98) {

					int ou = 0;

				}

				for (j = 1; j < ar[i].size(); j++) {

					int l = ar[i].get(j - 1) + 1;

					int r = ar[i].get(j) - 1;

					if (l <= r) {

						queries.add(new Query(l, r, i));

					}

					if (j == ar[i].size() - 1) {

						l = ar[i].get(j) + 1;

						r = m - 1;

						if (l <= r)

							queries.add(new Query(l, r, i));

					}

				}

				if (ar[i].size() == 1) {

					int l = ar[i].get(0) + 1;

					int r = m - 1;

					if (l <= r)

						queries.add(new Query(l, r, i));

				}

			}

			Collections.sort(queries, com);

			int bit[] = new int[m + 1];

			int last_visit[] = new int[n + 5];

			Arrays.fill(last_visit, -1);

			int query_counter = 0, q = queries.size();

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

				if (last_visit[a[i]] != -1)

					update(last_visit[a[i]] + 1, -1, bit, m);

				last_visit[a[i]] = i;

				update(i + 1, 1, bit, m);

				while (query_counter < q && queries.get(query_counter).r == i) {

					int an = query(queries.get(query_counter).r + 1, bit, m) - query(queries.get(query_counter).l, bit, m);

					int idx = queries.get(query_counter).idx;

					mx[idx] = Math.max(mx[idx], an);

					query_counter++;

				}

			}

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

				pn((mn[i] + 1) + " " + (mx[i] + 1));

			}

		}

		void update(int idx, int val, int bit[], int n) {

			for (; idx <= n; idx += idx & -idx)

				bit[idx] += val;

		}

		int query(int idx, int bit[], int n) {

			int sum = 0;

			for (; idx > 0; idx -= idx & -idx)

				sum += bit[idx];

			return sum;

		}

		void pn(String zx) {

			out.println(zx);

		}

		class Query {

			int l;

			int r;

			int idx;

			Query(int a, int b, int c) {

				l = a;

				r = b;

				idx = c;

			}

		}

		class SegmenTree {

			int n;

			int[] tree;

			void build(int x) {

				n = x;

				tree = new int[2 * n + 1];

			}

			void updateTreeNode(int p, int value) {

				tree[p + n] = value;

				p = p + n;

				for (int i = p; i > 1; i >>= 1)

					tree[i >> 1] = tree[i] + tree[i ^ 1];

			}

			int query(int l, int r) {

				int res = 0;

				for (l += n, r += n; l < r;

				     l >>= 1, r >>= 1) {

					if ((l & 1) > 0)

						res += tree[l++];

					if ((r & 1) > 0)

						res += tree[--r];

				}

				return res;

			}

		}

	}

	static class InputReader {

		private InputStream stream;

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

		private int curChar;

		private int numChars;

		public InputReader(InputStream stream) {

			this.stream = stream;

		}

		public int read() {

			if (numChars == -1) {

				throw new UnknownError();

			}

			if (curChar >= numChars) {

				curChar = 0;

				try {

					numChars = stream.read(buf);

				} catch (IOException e) {

					throw new UnknownError();

				}

				if (numChars <= 0) {

					return -1;

				}

			}

			return buf[curChar++];

		}

		public int nextInt() {

			return Integer.parseInt(next());

		}

		public String next() {

			int c = read();

			while (isSpaceChar(c)) {

				c = read();

			}

			StringBuffer res = new StringBuffer();

			do {

				res.appendCodePoint(c);

				c = read();

			} while (!isSpaceChar(c));

			return res.toString();

		}

		private boolean isSpaceChar(int c) {

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

		}

	}

}


D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3
4 9
5 10
42 9999999967
OutputCopy6
1
9999999966
NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00.

import java.io.*;

import java.util.*;

public class D{

	static long gcd(long a, long b) {

		if (a == 0) return b;

		return gcd(b%a, a);

	}

	static long bf(long a, long m) {

		long cnt = 0;

		long gcd = gcd(a,m);

		for (int i = 0; i < m; i++) cnt += gcd(a+i,m)==gcd ? 1:0;

		return cnt;

	}

	static long pp(long a, long m) {

		long g = gcd(a,m);

		a/=g;

		m/=g;

		long ans = m;

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

			if (m % i == 0) {

				while(m%i==0) m/=i;

				ans -= ans/i;

			}

		}

		if (m > 1) ans -= ans/m;

		return ans;

	}

	static List<Long> p;

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

		boolean[] sieve = new boolean[(int)1e6+20];

		p = new ArrayList<Long>();

		for (int i = 2; i *i <= sieve.length; i++) {

			if (!sieve[i]) {

				for (int j = i*i; j < sieve.length; j+=i) sieve[j] = false;

			}

		}

		for (int i = 2; i < sieve.length; i++) if (!sieve[i]) p.add((long)i);

//		long a = (long)(Math.random()*1e3+1);

//		long b = a + (long)(Math.random()*1e2+12);

//		for (int i = 1; i < 10; i++) {

//			long ta = a*i;

//			long tb = b*i;

//			out.println(bf(ta,tb) + " " + pp(ta,tb));

//		}

		readInput();

		out.close();

	}

	static void readInput() throws IOException{

		read();

		int t= RI();

		while(t-->0) {

			read();

			long a = RL();

			long m = RL();

			out.println(pp(a,m));

		}

	}

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

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

	static StringTokenizer st;

	static void read() throws IOException{st = new StringTokenizer(br.readLine());}

	static int RI() throws IOException{return Integer.parseInt(st.nextToken());}

	static long RL() throws IOException{return Long.parseLong(st.nextToken());}

	static double RD() throws IOException{return Double.parseDouble(st.nextToken());}

}


import java.util.*;

public class Solution

{

    public static void main(String[] args){

        Scanner sc=new Scanner(System.in);

        long h=sc.nextLong();

        int n=sc.nextInt();

        long[] ar=new long[n];

        long base=h;

        int an=0;

        int pr=0;

        boolean ok=false;

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

            ar[i]=sc.nextLong();

            base+=ar[i];

            an++;

            if(base<=0 && ok==false){ok=true;pr=an;}

        }

        if(base>=h){

            if(ok)System.out.println(pr);

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

        }

        else{

           long b=h;

           long max=0;

           long ans=0;long extra=0;

           long min=0;

            ok=true;

           long overall=0;

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

               ans++;

               b+=ar[i];

               min+=ar[i];

               overall+=ar[i];

               if(Math.abs(min)>max && min<0){

                   max=Math.abs(min);

                   extra=i+1;

               }

               if(b<=0 && ok){ok=false;break;}

           }

           if(!ok)System.out.println(ans);

           else{

               long rem=b-max;

               overall=Math.abs(overall);

               if(rem<=0){

                    while(true){

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

                    if(b<=0)break;

                    b+=ar[i];

                    ans++;

                    if(b<=0)break;

                }

                if(b<=0)break;

              }

               }

               else{

                  long div=rem/overall;

                  rem-=div*overall;

                  div=div*(long)n;

                  ans+=div;

                  rem+=max;

                   while(true){

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

                    if(rem<=0)break;

                    rem+=ar[i];

                    ans++;

                    if(rem<=0)break;

                }

                if(rem<=0)break;

              }

               }

               System.out.println(ans);

           }

        }

    }

}


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

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.*;

public class StringModification {

    static class Pair {

        int f;

        int s; //

        Pair() {

        }

        Pair(int f, int s) {

            this.f = f;

            this.s = s;

        }

    }

    static class Fast {

        BufferedReader br;

        StringTokenizer st;

        public Fast() {

            br = new BufferedReader(

                    new InputStreamReader(System.in));

        }

        String next() {

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

                try {

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

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

        int[] readArray(int n) {

            int a[] = new int[n];

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

                a[i] = nextInt();

            return a;

        }

        long[] readArray1(int n) {

            long a[] = new long[n];

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

                a[i] = nextLong();

            return a;

        }

        String nextLine() {

            String str = "";

            try {

                str = br.readLine().trim();

            } catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

    }

    /*  static long noOfDivisor(long a)

      {

          long count=0;

          long t=a;

          for(long i=1;i<=(int)Math.sqrt(a);i++)

          {

              if(a%i==0)

                  count+=2;

          }

          if(a==((long)Math.sqrt(a)*(long)Math.sqrt(a)))

          {

              count--;

          }

              return count;

      }*/

    static boolean isPrime(long a) {

        for (long i = 2; i <= (long) Math.sqrt(a); i++) {

            if (a % i == 0)

                return false;

        }

        return true;

    }

    static void primeFact(int n) {

        int temp = n;

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

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

            if (temp % i == 0) {

                int c = 0;

                while (temp % i == 0) {

                    c++;

                    temp /= i;

                }

                h.put(i, c);

            }

        }

        if (temp != 1)

            h.put(temp, 1);

    }

    static void reverseArray(int a[]) {

        int n = a.length;

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

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

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

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

        }

    }

    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 int min(int a, int b) {

        return a < b ? a : b;

    }

    static int max(int a, int b) {

        return a < b ? a : b;

    }

    static long maxSum(int arr[], int n, int k) {

        long res = 0;

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

            res += arr[i];

        long curr_sum = res;

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

            curr_sum += arr[i] - arr[i - k];

            res = Math.max(res, curr_sum);

        }

        return res;

    }

    static boolean check(int n,int k,char s[],StringBuffer max[])

    {

        StringBuffer sa=new StringBuffer();

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

            sa.append(s[i]);

        if(((n-k)&1)==0)

        {

            for(int i=k-2;i>=0;i--)

                sa.append(s[i]);

        }

        else //ans==3

        {

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

                sa.append(s[i]);

        }

        if(sa.compareTo(max[0])<0) {

            max[0] = sa;

            return true;

        }

return false;

    }

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

        Fast sc = new Fast();

        PrintWriter out = new PrintWriter(System.out);

        int t1 = sc.nextInt();

        while (t1-- > 0) {

            int n = sc.nextInt();

            String s1 = sc.next();

            char s[] = s1.toCharArray();

            StringBuffer max[]=new StringBuffer[1];

            max[0]=new StringBuffer(s1);

            int ans1=1;

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

            {

                    if(check(n,k,s,max))

                    {

                        ans1=k;

                    }

            }

            out.println(max[0]);

              out.println(ans1);

        }

        out.close();

    }

}

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

            Fast sc = new Fast();

            PrintWriter out = new PrintWriter(System.out);

            int t1 = sc.nextInt();

            while (t1-- > 0) {

                int n=sc.nextInt();

               String s1=sc.next();

               char s[]=s1.toCharArray();

               TreeMap<Integer, TreeSet<Integer>> tm=new TreeMap<>();

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

               {

                   char ch=s[i];

                   if(tm.get(ch-97)==null)

                   {

                       TreeSet<Integer> ts1=new TreeSet<>();

                       ts1.add(i);

                       tm.put(ch-97,ts1);

                   }

                   else

                   {

                       TreeSet ts1=tm.get(ch-97);

                       ts1.add(i); tm.put(ch-97,ts1);

                   }

               }

               TreeSet<Integer> ts1=null;

               for(Map.Entry<Integer,TreeSet<Integer>> en:tm.entrySet())

               {

                   ts1=en.getValue();

                   break;

               }

               if(ts1.size()==1)

               {

                   int ans=ts1.first()+1;

                   String sa="";

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

                       sa+=s[i];

                   if(((n-ans)&1)==0)

                   {

                       for(int i=ans-2;i>=0;i--)

                           sa+=s[i];

                   }

                   else //ans==3

                   {

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

                           sa+=s[i];

                   }

                   out.println(sa);

                   out.println(ans);

               }

            else

               {

              //     out.println(-1);

                   int ans=-1;

                   int comp=Integer.MAX_VALUE;

                   for(int ne:ts1)

                   {

                       if(ne!=0)

                       {

                         if(comp>s[ne-1])

                         {

                             comp=s[ne-1];

                             ans=ne+1;

                         }

                       }

                   }

                   String sa="";

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

                       sa+=s[i];

                   if(((n-ans)&1)==0)

                   {

                       for(int i=ans-2;i>=0;i--)

                           sa+=s[i];

                   }

                   else //ans==3

                   {

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

                           sa+=s[i];

                   }

                   if(sa.equals(s1))

                   {

                       out.println(sa);out.println(1);

                   }

                   else

                   {

                       out.println(sa);out.println(ans);

                   }

               }

            }

            out.close();

        }

    }

*/


D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1≤n≤100000,1≤m≤109,1≤k≤81≤n≤100000,1≤m≤109,1≤k≤8) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1≤Li≤Ri≤m1≤Li≤Ri≤m) — the parameters of the ii spell.OutputPrint a single integer — the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third.

//package com.example.practice.codeforces;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringTokenizer;
//D. Happy New Year
public class Solution {
    public static void main (String [] args) throws IOException {
        // Use BufferedReader rather than RandomAccessFile; it's much faster
        final BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        // input file name goes above
        //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("inflate.out")));

        StringTokenizer st = new StringTokenizer(input.readLine());
        int n = Integer.parseInt(st.nextToken()), m = Integer.parseInt(st.nextToken()), k = Integer.parseInt(st.nextToken());
        int[][] ns = new int[n][2];
        for(int i=0;i<n;++i){
            st = new StringTokenizer(input.readLine());
            ns[i][0] = Integer.parseInt(st.nextToken());
            ns[i][1] = Integer.parseInt(st.nextToken());
        }
        System.out.println(calc(n, m, k, ns));
        //out.close();       // close the output file
    }

    private static int calc(final int n, final int m, final int k, int[][] ns) {
        HashMap<Integer, Node> map = new HashMap<>();
        int p = 0, pre = 0, finished = 0;
        for (int[] kk : ns){
            if (!map.containsKey(kk[0])){
                map.put(kk[0], new Node(kk[0]));
            }
            map.get(kk[0]).st.add(p);
            if (!map.containsKey(kk[1]+1)){
                map.put(kk[1]+1, new Node(kk[1]+1));
            }
            map.get(kk[1]+1).en.add(p++);
        }
        Node[] nds = new Node[map.size()];
        p = 0;
        for (Node nd : map.values()){
            nds[p++] = nd;
        }
        Arrays.sort(nds);
        final int ks = 1<<k;
        int[][] dp = new int[nds.length][ks];
        int[] mask = new int[n], bitCount = new int[ks];
        for (int i=1;i<ks;++i){
            if((i&1) == 1)bitCount[i]=bitCount[i-1]+1;
            else bitCount[i]=bitCount[i>>1];
        }
        for (int i=0;i<dp.length-1;++i){
            pre -= finished;
            int d = 1, added = 0;
            for (int a : nds[i].st){
                while((d&pre) != 0) {
                    d = d << 1;
                }
                mask[a] = d;
                added += d;
                pre += d;
            }
            finished = 0;
            for (int a : nds[i+1].en){
                finished += mask[a];
            }
            for (int j=0;j<ks;++j) {
                if ((j & pre) == j) {
                    int t = 0;
                    if ((bitCount[j] & 1) == 1) {
                        t += nds[i + 1].start - nds[i].start;
                    }
                    if (i > 0) {
                        t += dp[i - 1][j - (j & added)];
                    }
                    dp[i][j - (j & finished)] = Math.max(dp[i][j - (j & finished)], t);
                }
            }
        }
        return dp[dp.length-2][0];
    }

    static class Node implements Comparable<Node>{
        int start;
        ArrayList<Integer> st;
        ArrayList<Integer> en;
        public Node(int a){
            start = a;
            st = new ArrayList<>(4);
            en = new ArrayList<>(4);
        }
        @Override
        public int compareTo(Node nd){
            return this.start - nd.start;
        }
    }
}


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

import java.util.*;

public class Main

{

	public static void main(String[] args) {

		Scanner sc=new Scanner(System.in);

		int t=sc.nextInt();

		while(t--!=0){

		    int a=sc.nextInt();

		    int b=sc.nextInt();

		    int ans=0;

		    boolean p=true;

		    if(a==b){

		        p=false;

		        System.out.println(0);

		    }

		    else if(a>b){

		        int d=a-b;

		        ans++;

		        if(d%2!=0){

		            ans+=1;

		        }

		    }

		    else{

		        int d=b-a;

		        ans++;

		        if(d%2!=1){

		            ans++;

		        }

		    }

		    if(p==true){

		        System.out.println(ans);

		    }

		}

	}

}


E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j  — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres  — the maximum possible strength of the club.ExamplesInputCopy4 1 2
1 16 10 3
18
19
13
15
OutputCopy44
InputCopy6 2 3
78 93 9 17 13 78
80 97
30 52
26 17
56 68
60 36
84 55
OutputCopy377
InputCopy3 2 1
500 498 564
100002 3
422332 2
232323 1
OutputCopy422899
NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class teambuilding {

    static class Node implements Comparable<Node>{
        int ind;
        int v;
        Node(int ind, int v){
            this.ind = ind;
            this.v = v;
        }
        public int compareTo(Node s){
            if(v != s.v) return s.v - v;
            return ind - s.ind;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken()), p = Integer.parseInt(st.nextToken()), k = Integer.parseInt(st.nextToken());
        Node[] ar = new Node[n];
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < n; i++) ar[i] = new Node(i, Integer.parseInt(st.nextToken()));
        long[][] vs = new long[n][p];
        for (int i = 0; i < n; i++) {
            st = new StringTokenizer(br.readLine());
            for (int j = 0; j < p; j++) {
                vs[i][j] = Long.parseLong(st.nextToken());
            }
        }
        Arrays.sort(ar);
        long[][] dp = new long[(1 << p)][n];
        for (int i = 0; i < (1 << p); i++) for (int j = 0; j < n; j++) dp[i][j] = -1;
        dp[0][0] = ar[0].v;
        for (int i = 0; i < p; i++) dp[(1 << i)][0] = vs[ar[0].ind][i];
        for (int i = 1; i < n; i++) {
            for (int j = 0; j < (1 << p); j++) {
                if(dp[j][i - 1] == -1) continue;
                int onecount = Integer.bitCount(j);
//                System.out.println(j + " " + onecount);
                if(k - (i - onecount + 1) >= 0){
                    dp[j][i] = Math.max(dp[j][i - 1] + ar[i].v, dp[j][i]);
                } else {
                    dp[j][i] = Math.max(dp[j][i], dp[j][i - 1]);
                }
                for (int l = 0; l < p; l++) {
                    //i is the current one to choose, j is the bitmask, l is the position
                    if((j >> l) % 2 == 1) continue;
                    dp[(j | (1 << l))][i] = Math.max(dp[j][i - 1] + vs[ar[i].ind][l], dp[(j | (1 << l))][i]);
                }
            }
        }
        System.out.println(dp[(1 << p) - 1][n - 1]);
    }
}


D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5
4 8 2 6 2
4 5 4 1 3
OutputCopy7
InputCopy4
1 3 2 4
1 3 2 4
OutputCopy0

import java.util.*;

import java.io.*;

import java.math.BigInteger;

public class CODE {

    public static class pair implements Comparable<pair> {

        int x;

        int y;

        public pair(int par1, int par2) {

            x = par1;

            y = par2;

        }

        @Override

        public int compareTo(pair p) {

            return x - p.x;

        }

        @Override

        public String toString() {

            return +x + " " + y;

        }

    }

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

    public static long facn(long n, long x) {

        long ans = 1;

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

            ans *= n;

            ans %= mod;

            n--;

        }

        long k = 1;

        long t = x;

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

            k *= x;

            k %= mod;

            x--;

        }

//      BigInteger b = BigInteger.valueOf((k)).modInverse(BigInteger.valueOf((mod)));

        long b = modPow(k, mod - 2, mod);

        return ((b % mod) * ans) % mod;

    }

    public static long modInverse(long a, long m) {

        a = a % m;

        for (int x = 1; x < m; x++)

            if ((a * x) % m == 1)

                return x;

        return 1;

    }

    static long modPow(long a, long e, long mod) { // O(log e)

        a %= mod;

        long res = 1;

        while (e > 0) {

            if ((e & 1) == 1)

                res = (res * a) % mod;

            a = (a * a) % mod;

            e >>= 1;

        }

        return res % mod;

    }

    public static void bb(Serializable s) {

        System.out.println(55);

    }

    public static int dfs(int u) {

        vis[u] = true;

        rank[u] = rnk;

        int ans = 1;

        for (int v : adj[u])

            if (!vis[v])

                ans += dfs(v);

        return ans;

    }

    public static void dfsD(int u) {

        dist[u] = dst;

        for (int v : adj[u])

            if (dist[v] == -1)

                dfsD(v);

    }

    static ArrayList<Integer>[] adj, adj2;

    static int n, m, k, rnk, dst;

    static boolean[] vis;

    static int[] dist, rank;

    public static String rev(String str) {

        StringBuilder sb = new StringBuilder();

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

            sb.append(str.charAt(i));

        // System.out.println(sb);

        return sb.toString();

    }

    static PriorityQueue<pair> pq;

    static int p;

    static int[][] Matrix;

    static long[][] memo;

    static pair[] Arr;

//  public static long dp(int idx, int mask) {

//      int k=idx-Integer.bitCount(mask);

//      if (k==0&&Integer.bitCount(mask)==p)

//          return 0;

//      long ans = 0;

//      if (memo[mask][idx] != -1)

//          return memo[mask][idx];

//      if (kk > 0)

//          ans = Math.max(ans, Arr[k+p-kk - pp].y + dp(kk - 1, pp, mask));

//      if (pp > 0)

//          for (int i = 0; i < p; i++)

//              if ((mask & (1 << i)) == 0)

//                  ans = Math.max(Matrix[Arr[k+p-kk - pp].x][i] + dp(kk, pp - 1, mask | 1 << i), ans);

//

//      return memo[mask][pp][kk] = ans;

//  }

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

        try {

            System.setIn(new FileInputStream("input.txt"));

            System.setOut(new PrintStream(new FileOutputStream("output.txt")));

        } catch (Exception e) {

            System.err.println("Error");

        }

        Scanner sc = new Scanner(System.in);

        PrintWriter pw = new PrintWriter(System.out);

        int n = sc.nextInt();

        Long[]Arr = new Long[n];

        for (int i = 0; i < n; i++)Arr[i] = sc.nextLong();

        for (int i = 0; i < n; i++)Arr[i] -= sc.nextLong();

        Arrays.sort(Arr);

        long sum = 0;

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

            int lo = 0;

            int hi = n - 1;

            int mid = n;

            int ans = n;

            while (hi >= lo) {

                mid = (lo + hi) / 2;

                if (Arr[i] + Arr[mid] > 0) {

                    ans = mid;

                    hi = mid - 1;

                } else {

                    lo = mid + 1;

                }

            }

            sum += n - ans;

        }

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

            if (Arr[i] > 0)sum--;

        }

        pw.println(sum / 2);

        pw.close();

    }

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

            PrintWriter pw = new PrintWriter(System.out);

            int t=sc.nextInt();

            while(t-->0) {

                int n=sc.nextInt();

                int[]Arr=new int [n];

                for(int i=0;i<n;i++)Arr[i]=sc.nextInt();

                for(int i=0;i<n;i++)Arr[i]-=sc.nextInt();

                Arrays.sort(Arr);

                int sum=0;

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

                {

                    int lo=0;

                    int hi=n-1;

                    int mid=n+1;

                    int ans=n+1;

                    while(hi>=lo) {

                        mid=(lo+hi)/2;

                    }

                }

                }

            pw.close();*/

    public static class trie {

        trie[] arr;

        int isLeaf;

        int freq;

        public trie() {

            super();

            this.arr = new trie[26];

            this.isLeaf = 0;

            this.freq = 0;

        }

        public void add(String str) {

            add(str, 0);

        }

        private void add(String str, int idx) {

            if (idx == str.length()) {

                isLeaf++;

                return;

            }

            int x = str.charAt(idx) - 'a';

            if (arr[x] == null)

                arr[x] = new trie();

            arr[x].freq++;

            arr[x].add(str, idx + 1);

        }

        public int numOfPref(String str) {

            return numOfPref(str, 0);

        }

        private int numOfPref(String str, int idx) {

            if (idx == str.length())

                return freq;

            int x = str.charAt(idx) - 'a';

            if (arr[x] == null)

                return 0;

            return arr[x].numOfPref(str, idx + 1);

        }

        public int numofStr(String str) {

            return numOfStr(str, 0);

        }

        private int numOfStr(String str, int idx) {

            if (idx == str.length())

                return isLeaf;

            int x = str.charAt(idx) - 'a';

            if (arr[x] == null)

                return 0;

            return arr[x].numOfStr(str, idx + 1);

        }

        public boolean contains(String str) {

            return numofStr(str) != 0;

        }

        public boolean containsPref(String str) {

            return numOfPref(str) != 0;

        }

    }

    public static class Scanner {

        StringTokenizer st;

        BufferedReader br;

        public Scanner(InputStream s) {

            br = new BufferedReader(new InputStreamReader(s));

        }

        public String next() throws IOException {

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

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

            return st.nextToken();

        }

        public int nextInt() throws IOException {

            return Integer.parseInt(next());

        }

        public long nextLong() throws IOException {

            return Long.parseLong(next());

        }

        public String nextLine() throws IOException {

            return br.readLine();

        }

        public double nextDouble() throws IOException {

            String x = next();

            StringBuilder sb = new StringBuilder("0");

            double res = 0, f = 1;

            boolean dec = false, neg = false;

            int start = 0;

            if (x.charAt(0) == '-') {

                neg = true;

                start++;

            }

            for (int i = start; i < x.length(); i++)

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

                    res = Long.parseLong(sb.toString());

                    sb = new StringBuilder("0");

                    dec = true;

                } else {

                    sb.append(x.charAt(i));

                    if (dec)

                        f *= 10;

                }

            res += Long.parseLong(sb.toString()) / f;

            return res * (neg ? -1 : 1);

        }

        public boolean ready() throws IOException, IOException {

            return br.ready();

        }

    }

}


import java.util.*;
import  static java.lang.System.out;

public class Main {
    static Scanner sc;

    public static void main(String[] args) {
        sc = new Scanner(System.in);

//        int t = sc.nextInt();
//        for(int __ = 0; __ < t; __++){
            var n = sc.nextLong();
            var m = sc.nextLong();
            if(m % n != 0) out.println(-1);
            else{
                m /= n;
                int c = 0;
                while((m & 1) == 0) {
                    m >>= 1;
                    c++;
                }
                while( m % 3 == 0) {
                    m /= 3;
                    c++;
                }
                if(m != 1) out.println(-1);
               else out.println(c);
            }

        //}

        sc.close();
    }

    public static int[] intar(int n){
        var f = new int[n];
        for(int i = 0; i < n; i++) f [i] = sc.nextInt();
        return f;
    }

    public static void outintar(int[] a, String d){
        out.print(a[0]);
        for(int i = 1; i < a.length; i++)
        {
            out.print(" ");
            out.print(a[i]);
        }
        out.println();
    }
}