C. Sequencetime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math; so he asks for your help.The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.InputThe first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.OutputOutput one integer — minimum number of steps required to achieve the goal.ExamplesInputCopy53 2 -1 2 11OutputCopy4InputCopy52 1 1 1 1OutputCopy1

import java.io.*;

import java.math.BigDecimal;

import java.math.BigInteger;

import java.math.RoundingMode;

import java.util.*;

/**

 * @author Tran Anh Tai

 * @template for CP codes

 * What a trick prob!

 */

public class ProbC {

    public static void main(String[] args) {

        InputStream inputStream = System.in;

        OutputStream outputStream = System.out;

        InputReader in = new InputReader(inputStream);

        PrintWriter out = new PrintWriter(outputStream);

        Task solver = new Task();

        solver.solve(in, out);

        out.close();

    }

    // main solver

    static class Task{

        static int MOD = 1000000007;

        public void solve(InputReader in, PrintWriter out) {

            int n = in.nextInt();

            long a[] = new long[n];

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

                a[i] = in.nextInt();

            }

            long b[] = a.clone();

            Arrays.sort(b);

            long[][] dp = new long[2][n];

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

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

                    dp[(i & 1)][j] = dp[(i + 1) & 1][j] + Math.abs(a[i - 1]- b[j]);

                    if (j > 0){

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

                    }

                }

            }

            out.println(dp[n & 1][n - 1]);

        }

    }

    // fast input reader class;

    static class InputReader {

        BufferedReader br;

        StringTokenizer st;

        public InputReader(InputStream stream) {

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

        }

        public String nextToken() {

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

                String line = null;

                try {

                    line = br.readLine();

                } catch (IOException e) {

                    throw new RuntimeException(e);

                }

                if (line == null) {

                    return null;

                }

                st = new StringTokenizer(line);

            }

            return st.nextToken();

        }

        public int nextInt() {

            return Integer.parseInt(nextToken());

        }

        public long nextLong(){

            return Long.parseLong(nextToken());

        }

    }

}


D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6
1 4
4 2
5 3
6 3
2 3

3

4

4

OutputCopy

? 5 6

? 3 1

? 1 2

! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:

import java.util.*;

import java.io.*;

public class Main {

  static StringBuilder sb;

  static dsu dsu;

  static long fact[];

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

  static ArrayList<HashSet<Integer>> graph; // set for o(1) removal

  static HashSet<Integer> leaves;

  static void solve() {

     int n =i();

     graph = new ArrayList();

     leaves = new HashSet();

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

         graph.add(new HashSet());

     }

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

         int u = i()-1;

         int v = i()-1;

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

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

     }

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

         int s = graph.get(i).size();

         if(s==1) leaves.add(i);

     }

     while(leaves.size()>1){

         int u = leaves.iterator().next();

         leaves.remove(u);

         int v = leaves.iterator().next();

         leaves.remove(v);

         int w = query(u,v);

         if(w==v||w==u){

             System.out.println("! "+(w+1));

             System.out.flush();

             return;

         }

         delete(u,-1,w);

         delete(v,-1,w);

         if(graph.get(w).size()<=1) leaves.add(w);

     }

     int ans = leaves.iterator().next();

     System.out.println("! "+(ans+1));

     System.out.flush();

  }

  static int query(int u,int v){

      u++;

      v++;

      System.out.println("? "+u+" "+v);

      System.out.flush();

      int lca = i()-1;

      return lca;

  }

  static void delete(int u,int p,int lca){

      leaves.remove(u);

      for(int e : graph.get(u)){

          if(e==p) continue;

          if(e==lca){

              graph.get(lca).remove(u);

          }else delete(e,u,lca);

      }

    //   graph.get(u).clear();

  }

  public static void main(String[] args) {

    sb = new StringBuilder();

    int test = 1;

    while (test-- > 0) {

      solve();

    }

    System.out.println(sb);

  }

  /*

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

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

   */

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

  static long ncr(int n, int r) {

    if (r > n)

      return (long) 0;

    long res = fact[n] % mod;

    // System.out.println(res);

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

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

    // System.out.println(res);

    return res;

  }

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

  {

    if (y == 0)

      return 1;

    long res = 1;

    while (y > 0) {

      if (y % 2 == 1) {

        res = (res * x) % mod;

        y--;

      }

      x = (x * x) % mod;

      y = y / 2;

    }

    return res;

  }

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

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

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

  static class dsu {

    int parent[];

    dsu(int n) {

      parent = new int[n];

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

        parent[i] = -1;

    }

    int find(int a) {

      if (parent[a] < 0)

        return a;

      else {

        int x = find(parent[a]);

        parent[a] = x;

        return x;

      }

    }

    void merge(int a, int b) {

      a = find(a);

      b = find(b);

      if (a == b)

        return;

      parent[b] = a;

    }

  }

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

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

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

    long num = n;

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

      if (n % i == 0) {

        int nt = 0;

        while (n % i == 0) {

          n = n / i;

          nt++;

        }

        h.put(i, nt);

      }

    }

    if (n != 1)

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

    return h;

  }

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

  static class Pair implements Comparable<Pair> {

    int x;

    long y;

    Pair(int x, long y) {

      this.x = x;

      this.y = y;

    }

    public int compareTo(Pair o) {

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

    }

  }

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

  static class InputReader {

    private InputStream stream;

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

    private int curChar;

    private int numChars;

    private SpaceCharFilter filter;

    public InputReader(InputStream stream) {

      this.stream = stream;

    }

    public int read() {

      if (numChars == -1)

        throw new InputMismatchException();

      if (curChar >= numChars) {

        curChar = 0;

        try {

          numChars = stream.read(buf);

        } catch (IOException e) {

          throw new InputMismatchException();

        }

        if (numChars <= 0)

          return -1;

      }

      return buf[curChar++];

    }

    public int Int() {

      int c = read();

      while (isSpaceChar(c))

        c = read();

      int sgn = 1;

      if (c == '-') {

        sgn = -1;

        c = read();

      }

      int res = 0;

      do {

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

          throw new InputMismatchException();

        res *= 10;

        res += c - '0';

        c = read();

      } while (!isSpaceChar(c));

      return res * sgn;

    }

    public String String() {

      int c = read();

      while (isSpaceChar(c))

        c = read();

      StringBuilder res = new StringBuilder();

      do {

        res.appendCodePoint(c);

        c = read();

      } while (!isSpaceChar(c));

      return res.toString();

    }

    public boolean isSpaceChar(int c) {

      if (filter != null)

        return filter.isSpaceChar(c);

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

    }

    public String next() {

      return String();

    }

    public interface SpaceCharFilter {

      public boolean isSpaceChar(int ch);

    }

  }

  static class OutputWriter {

    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {

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

    }

    public OutputWriter(Writer writer) {

      this.writer = new PrintWriter(writer);

    }

    public void print(Object... objects) {

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

        if (i != 0)

          writer.print(' ');

        writer.print(objects[i]);

      }

    }

    public void printLine(Object... objects) {

      print(objects);

      writer.println();

    }

    public void close() {

      writer.close();

    }

    public void flush() {

      writer.flush();

    }

  }

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

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

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

    int n = a2.length;

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

    for (long i : a2)

      l.add(i);

    Collections.sort(l);

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

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

    return a2;

  }

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

    int n = a2.length;

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

    for (char i : a2)

      l.add(i);

    Collections.sort(l);

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

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

    return a2;

  }

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

    long res = 1;

    while (y > 0) {

      if (y % 2 != 0) {

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

        y--;

      }

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

      y = y / 2;

    }

    return res;

  }

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

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

    if (x == 0)

      return y;

    else

      return gcd(y % x, x);

  }

  // ******LOWEST COMMON MULTIPLE

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

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

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

  }

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

  public static int i() {

    return in.Int();

  }

  public static long l() {

    String s = in.String();

    return Long.parseLong(s);

  }

  public static String s() {

    return in.String();

  }

  public static int[] readArrayi(int n) {

    int A[] = new int[n];

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

      A[i] = i();

    }

    return A;

  }

  public static long[] readArray(long n) {

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

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

      A[i] = l();

    }

    return A;

  }

}


B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3
5
1 3
1 2
3 3
5 5
4 3
2
1 0
0 1
1
4 3
OutputCopyYES
RUUURRRRUU
NO
YES
RRRRUUU
NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.Collections;

import java.util.StringTokenizer;

public class CollectingPackages {

    static PrintWriter pw;

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

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

        pw = new PrintWriter(System.out);

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

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

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

            ArrayList<Point> points = new ArrayList<>();

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

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

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

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

                points.add(new Point(x, y));

            }

            Collections.sort(points);

            if (!test(points)) pw.println("NO");

        }

        pw.close();

    }

    static boolean test(ArrayList<Point> points) {

        Point pos = new Point(0, 0);

        StringBuilder sb = new StringBuilder();

        for (Point p : points) {

            if (p.x >= pos.x && p.y >= pos.y) {

                sb.append(diff(pos, p));

                pos = p;

            } else return false;

        }

        pw.println("YES");

        pw.println(sb);

        return true;

    }

    static StringBuilder diff(Point p1, Point p2) {

        StringBuilder res = new StringBuilder();

        res.append("R".repeat(Math.max(0, p2.x - p1.x)));

        res.append("U".repeat(Math.max(0, p2.y - p1.y)));

        return res;

    }

    static class Point implements Comparable<Point> {

        public int x, y;

        public Point(int x, int y) {

            this.x = x;

            this.y = y;

        }

        @Override

        public int compareTo(Point o) {

            int xComp = Integer.compare(x, o.x);

            if (xComp != 0) return xComp;

            else return Integer.compare(y, o.y);

        }

    }

}


E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
OutputCopyYES
YES
NO
YES
NO
NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines).  Possible paths for the queries with "YES" answers are:   11-st query: 11 – 33 – 22  22-nd query: 11 – 22 – 33  44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33

// package TreeQueries;

import java.util.*;

import java.io.*;

public class addEdge {

    static class FastReader {

        BufferedReader br;

        StringTokenizer st;

        public FastReader() {

            br = new BufferedReader(

                    new InputStreamReader(System.in));

        }

        String next() {

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

                try {

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

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

        String nextLine() {

            String str = "";

            try {

                str = br.readLine();

            } catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

    }

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

        FastReader sc = new FastReader();

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

        int t = 1;

        // t = sc.nextInt();

        while (t-- != 0) {

            int n = sc.nextInt();

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

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

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

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

                int u = sc.nextInt();

                int v = sc.nextInt();

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

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

            }

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

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

            int parent[][] = new int[n + 1][limit + 1];

            dfs(1, 0, 0, adj, level, parent);

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

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

                    int x = parent[j][i - 1];

                    parent[j][i] = parent[x][i - 1];

                }

            }

            int q = sc.nextInt();

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

                int k = 5;

                int qur[] = new int[k];

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

                    qur[j] = sc.nextInt();

                }

                int withoutedge = getDist(qur[2], qur[3], parent, level);

                int d2 = getDist(qur[2], qur[0], parent, level) + 1 + getDist(qur[1], qur[3], parent, level);

                int d3 = getDist(qur[3], qur[0], parent, level) + 1 + getDist(qur[1], qur[2], parent, level);

                int withedge = Math.min(d2, d3);

                int ans = Integer.MAX_VALUE;

                if (withedge % 2 == qur[4] % 2) {

                    ans = withedge;

                }

                if (withoutedge % 2 == qur[4] % 2) {

                    ans = Math.min(ans, withoutedge);

                }

                if (ans <= qur[4]) {

                    w.write("YES\n");

                } else {

                    w.write("NO\n");

                }

            }

            w.flush();

        }

        w.close();

    }

    private static int getDist(int a, int b, int[][] parent, int[] level) {

        if (level[a] > level[b]) {

            int temp = a;

            a = b;

            b = temp;

        }

        int diff = level[b] - level[a];

        int ans = 0;

        while (diff > 0) {

            int log = (int) (Math.log(diff) / Math.log(2));

            b = parent[b][log];

            diff -= (1 << log);

            ans += (1 << log);

        }

        if(a==b)return ans;

        for(int i=parent[0].length-1;i>=0;i--){

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

                a = parent[a][i];

                b = parent[b][i];

                ans += 2*(1 << (i));

            }

        }

        return ans+2;

    }

    private static void dfs(int i, int p, int l, ArrayList<ArrayList<Integer>> adj, int[] level, int[][] parent) {

        parent[i][0] = p;

        level[i] = l;

        for (int nbr : adj.get(i)) {

            if (nbr == p)

                continue;

            dfs(nbr, i, l + 1, adj, level, parent);

        }

    }

}


C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab.  During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab.  During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab.  During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba.  During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows.  During the first move, remove the third character s3=s3= d, ss becomes bca.  During the second move, remove the second character s2=s2= c, ss becomes ba.  And during the third move, remove the first character s1=s1= b, ss becomes a.

import java.util.*;

import java.io.*;

public class Main {

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

    //Code here

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

    PrintWriter wr = new PrintWriter(System.out);

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

    String s = br.readLine();

    int count = 0;

    for(char ch = 'z';ch>='a';ch--){

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

            if(s.length()==1) break;

            if(s.charAt(i)!=ch) continue;

            if(i==0){

                if(s.charAt(i+1)==ch-1){

                    count++;

                    s = s.substring(0,i) + s.substring(i+1);

                }

            }else if(i==s.length()-1){

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

                    count++;

                    s = s.substring(0,i) + s.substring(i+1);

                }

            }else{

                if(s.charAt(i+1)==ch-1||s.charAt(i-1)==ch-1){

                    count++;

                    s = s.substring(0,i) + s.substring(i+1);

                    i-=2;

                }

            }

        }

    }

    wr.println(count);

    wr.close();

  }

}


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.lang.*;

import java.io.*;

public class Main

{

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

    static final FastReader sc = new FastReader();

    //I invented a new word!Plagiarism!

    //Did you hear about the mathematician who’s afraid of negative numbers?He’ll stop at nothing to avoid them

    //What do Alexander the Great and Winnie the Pooh have in common? Same middle name.

    //I finally decided to sell my vacuum cleaner. All it was doing was gathering dust!

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

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

    //char[] a = s.toCharArray();

    // char s[]=sc.next().toCharArray();

    public static boolean sorted(int a[])

    {

        int n=a.length,i;

        int b[]=new int[n];

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

        b[i]=a[i];

        Arrays.sort(b);

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

        {

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

            return false;

        }

        return true;

    }

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

	{

	        int n=sc.nextInt();

	        int a[]=new int[n];

	        int b[]=new int[n];

	        int i; long pos=0;

	        long ans=0;

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

	        a[i]=sc.nextInt();

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

	        b[i]=sc.nextInt();

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

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

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

	        {

	            arr.add((long)b[i]-(long)a[i]);

	            if(a[i]-b[i]<=0)

	            neg.add((long)a[i]-(long)b[i]);

	            else

	            pos++;

	        }

	        ans=(pos*(pos-1))/2;

	        Collections.sort(arr);

	        for(long it:neg)

	        {

	           ans+=lower_bound(arr,0,arr.size()-1,it);

	        }

	        System.out.println(ans);

	}

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

    {

        if (high >= low) {

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

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

                return mid;

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

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

            else

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

        }

        return -1;

    }

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

    {

        if (high >= low) {

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

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

                return mid;

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

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

            else

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

        }

        return -1;

    }

	public static int lis(int[] arr) {

	int n = arr.length;

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

	al.add(arr[0]);

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

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

		if(arr[i]>=x) {

			al.add(arr[i]);

		}else {

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

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

		}

	}

	return al.size();

}

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

{

    //Collections.sort(ar);

    int s=lo;

    int e=hi;

    while (s !=e)

    {

        int mid = s+e>>1;

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

        {

            s=mid+1;

        }

        else

        {

            e=mid;

        }

    }

    if(s==ar.size())

    {

        return -1;

    }

    return s;

}

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

{

    Collections.sort(ar);

    int s=lo;

    int e=hi;

    while (s !=e)

    {

        int mid = s+e>>1;

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

        {

            s=mid+1;

        }

        else

        {

            e=mid;

        }

    }

    if(s==ar.size())

    {

        return -1;

    }

    return s;

}

static boolean isPrime(long N)

    {

        if (N<=1)  return false;

        if (N<=3)  return true;

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

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

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

                return false;

        return true;

    }

    static int countBits(long a)

    {

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

    }

    static long fact(long N)

    {

        long mod=1000000007;

        long n=2;

        if(N<=1)return 1;

        else

        {

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

        }

        return n;

    }

    private static boolean isInteger(String s) {

        try {

            Integer.parseInt(s);

        } catch (NumberFormatException e) {

            return false;

        } catch (NullPointerException e) {

            return false;

        }

        return true;

    }

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

        if (b == 0)

            return a;

        return gcd(b, a % b);

    }

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

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

    }

    private static boolean isPalindrome(String str) {

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

        while (i < j)

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

                return false;

        return true;

    }

    private static String reverseString(String str) {

        StringBuilder sb = new StringBuilder(str);

        return sb.reverse().toString();

    }

	static class FastReader {

        BufferedReader br;

        StringTokenizer st;

        public FastReader()

        {

            br = new BufferedReader(

                new InputStreamReader(System.in));

        }

        String next()

        {

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

                try {

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

                }

                catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

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

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

        double nextDouble()

        {

            return Double.parseDouble(next());

        }

        String nextLine()

        {

            String str = "";

            try {

                str = br.readLine();

            }

            catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

    }

}


C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
OutputCopy1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10

import java.util.*;

import java.io.*;

public class Practice {
	static boolean multipleTC = true;
	FastReader in;
	PrintWriter out;

	final static int mod = 1000000007;
	final static int mod2 = 998244353;
	final double E = 2.7182818284590452354;
	final double PI = 3.14159265358979323846;
	int MAX = 100005;

	public static void main(String[] args) throws Exception {
		new Practice().run();
	}

	void run() throws Exception {
		in = new FastReader();
		out = new PrintWriter(System.out);
		int T = (multipleTC) ? ni() : 1;
		pre();
		for (int t = 1; t <= T; t++)
			solve(t);
		out.flush();
		out.close();
	}

	void pre() throws Exception {
	}

	// All the best
	void solve(int TC) throws Exception {
		int n = ni(), arr[] = readArr(n);
		int max = 2 * n;
		boolean used[] = new boolean[max + 1];
		int res[] = new int[max];
		boolean possible = true;
		for (int i = 0, j = 0; i < n; i++, j += 2) {
			if (arr[i] >= max || used[arr[i]]) {
				possible = false;
				break;
			} else {
				res[j] = arr[i];
				used[arr[i]] = true;
			}
		}
		if (possible) {
			for (int i = 0, j = 1; i < n; i++, j += 2) {
				boolean found = false;
				for (int k = arr[i] + 1; k <= max; k++) {
					if (!used[k]) {
						res[j] = k;
						found = true;
						used[k] = true;
						break;
					}
				}
				if (!found) {
					possible = false;
					break;
				}
			}
			if (possible) {
				StringBuilder ans = new StringBuilder();
				for (int i : res) {
					ans.append(i + " ");
				}
				pn(ans);
			}else {
				pn("-1");
			}

		} else {
			pn("-1");
		}
	}

	int[] readArr(int n) throws Exception {
		int arr[] = new int[n];
		for (int i = 0; i < n; i++) {
			arr[i] = ni();
		}
		return arr;
	}

	void sort(int arr[]) {
		ArrayList<Integer> list = new ArrayList<>();
		for (int i = 0; i < arr.length; i++)
			list.add(arr[i]);
		Collections.sort(list);
		for (int i = 0; i < arr.length; i++)
			arr[i] = list.get(i);
	}

	public long max(long... arr) {
		long max = arr[0];
		for (long itr : arr)
			max = Math.max(max, itr);
		return max;
	}

	public int max(int... arr) {
		int max = arr[0];
		for (int itr : arr)
			max = Math.max(max, itr);
		return max;
	}

	public long min(long... arr) {
		long min = arr[0];
		for (long itr : arr)
			min = Math.min(min, itr);
		return min;
	}

	public int min(int... arr) {
		int min = arr[0];
		for (int itr : arr)
			min = Math.min(min, itr);
		return min;
	}

	public long sum(long... arr) {
		long sum = 0;
		for (long itr : arr)
			sum += itr;
		return sum;
	}

	public long sum(int... arr) {
		long sum = 0;
		for (int itr : arr)
			sum += itr;
		return sum;
	}

	String bin(long n) {
		return Long.toBinaryString(n);
	}

	String bin(int n) {
		return Integer.toBinaryString(n);
	}

	static int bitCount(int x) {
		return x == 0 ? 0 : (1 + bitCount(x & (x - 1)));
	}

	static void dbg(Object... o) {
		System.err.println(Arrays.deepToString(o));
	}

	int bit(long n) {
		return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
	}

	int abs(int a) {
		return (a < 0) ? -a : a;
	}

	long abs(long a) {
		return (a < 0) ? -a : a;
	}

	void p(Object o) {
		out.print(o);
	}

	void pn(Object o) {
		out.println(o);
	}

	void pni(Object o) {
		out.println(o);
		out.flush();
	}

	String n() throws Exception {
		return in.next();
	}

	String nln() throws Exception {
		return in.nextLine();
	}

	int ni() throws Exception {
		return Integer.parseInt(in.next());
	}

	long nl() throws Exception {
		return Long.parseLong(in.next());
	}

	double nd() throws Exception {
		return Double.parseDouble(in.next());
	}

	class FastReader {
		BufferedReader br;
		StringTokenizer st;

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

		public FastReader(String s) throws Exception {
			br = new BufferedReader(new FileReader(s));
		}

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

		String nextLine() throws Exception {
			String str = "";
			try {
				str = br.readLine();
			} catch (IOException e) {
				throw new Exception(e.toString());
			}
			return str;
		}
	}
}


A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets:  the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different),  the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows:  Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution:   Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100)  — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000)  — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000)  — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
OutputCopy1 8 5
8 4 5
5 1 7
6 2 1
NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.

// Created on: 10:12:32 PM | 14-Mar-2022

import java.util.*;

import java.io.*;

import java.math.*;

import java.lang.*;

public class Main {

	static InputStream is;

	static PrintWriter out;

	static String INPUT = "";

	static void solve() {

		int caseNo = 1;

		for (int T = sc.nextInt(); T > 0; T--, caseNo++) {

			solveIt(caseNo);

		}

	}

	// Solution

	static void solveIt(int t) {

		int n = sc.nextInt();

		int a[] = sc.readIntArray(n);

		int b[] = sc.readIntArray(n);

		sort(a);

		sort(b);

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

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

		}

		System.out.println();

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

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

		}

		System.out.println();

	}

	static void revArray(int a[], int i, int j) {

		while (i <= j) {

			int temp = a[i];

			a[i] = a[j];

			a[j] = temp;

			i++;

			j--;

		}

	}

	static boolean isSorted(int a[], int s, int e, boolean strict) {

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

			if (strict && a[i - 1] >= a[i])

				return false;

			if (!strict && a[i - 1] > a[i])

				return false;

		}

		return true;

	}

	static class DSU {

		int rank[];

		int parent[];

		DSU(int n) {

			rank = new int[n + 1];

			parent = new int[n + 1];

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

				parent[i] = i;

			}

		}

		int findParent(int node) {

			if (parent[node] == node)

				return node;

			return parent[node] = findParent(parent[node]);

		}

		boolean union(int x, int y) {

			int px = findParent(x);

			int py = findParent(y);

			if (px == py)

				return false;

			if (rank[px] < rank[py]) {

				parent[px] = py;

			} else if (rank[px] > rank[py]) {

				parent[py] = px;

			} else {

				parent[px] = py;

				rank[py]++;

			}

			return true;

		}

	}

	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 boolean[] seiveOfEratosthenes(int n) {

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

		Arrays.fill(isPrime, true);

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

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

				isPrime[j] = false;

			}

		}

		return isPrime;

	}

	public static int[] seiveOnlyPrimes(int n) {

		if (n <= 32) {

			int[] primes = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 };

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

				if (n < primes[i]) {

					return Arrays.copyOf(primes, i);

				}

			}

			return primes;

		}

		int u = n + 32;

		double lu = Math.log(u);

		int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)];

		ret[0] = 2;

		int pos = 1;

		int[] isp = new int[(n + 1) / 32 / 2 + 1];

		int sup = (n + 1) / 32 / 2 + 1;

		int[] tprimes = { 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 };

		for (int tp : tprimes) {

			ret[pos++] = tp;

			int[] ptn = new int[tp];

			for (int i = (tp - 3) / 2; i < tp << 5; i += tp)

				ptn[i >> 5] |= 1 << (i & 31);

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

				for (int j = i; j < sup; j += tp)

					isp[j] |= ptn[i];

			}

		}

		int[] magic = { 0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17,

				9, 6, 16, 5, 15, 14 };

		int h = n / 2;

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

			for (int j = ~isp[i]; j != 0; j &= j - 1) {

				int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27];

				int p = 2 * pp + 3;

				if (p > n)

					break;

				ret[pos++] = p;

				for (int q = pp; q <= h; q += p)

					isp[q >> 5] |= 1 << (q & 31);

			}

		}

		return Arrays.copyOf(ret, pos);

	}

	static int gcd(int a, int b) {

		if (b == 0)

			return a;

		return gcd(b, a % b);

	}

	static boolean isPrime(long n) {

		if (n < 2)

			return false;

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

			if (n % i == 0)

				return false;

		}

		return true;

	}

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

		long S = System.currentTimeMillis();

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

		out = new PrintWriter(System.out);

		solve();

		out.flush();

		long G = System.currentTimeMillis();

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

	}

	static class sc {

		private static boolean endOfFile() {

			if (bufferLength == -1)

				return true;

			int lptr = ptrbuf;

			while (lptr < bufferLength)

				if (!isThisTheSpaceCharacter(inputBufffferBigBoi[lptr++]))

					return false;

			try {

				is.mark(1000);

				while (true) {

					int b = is.read();

					if (b == -1) {

						is.reset();

						return true;

					} else if (!isThisTheSpaceCharacter(b)) {

						is.reset();

						return false;

					}

				}

			} catch (IOException e) {

				return true;

			}

		}

		private static byte[] inputBufffferBigBoi = new byte[1024];

		static int bufferLength = 0, ptrbuf = 0;

		private static int justReadTheByte() {

			if (bufferLength == -1)

				throw new InputMismatchException();

			if (ptrbuf >= bufferLength) {

				ptrbuf = 0;

				try {

					bufferLength = is.read(inputBufffferBigBoi);

				} catch (IOException e) {

					throw new InputMismatchException();

				}

				if (bufferLength <= 0)

					return -1;

			}

			return inputBufffferBigBoi[ptrbuf++];

		}

		private static boolean isThisTheSpaceCharacter(int c) {

			return !(c >= 33 && c <= 126);

		}

		private static int skipItBishhhhhhh() {

			int b;

			while ((b = justReadTheByte()) != -1 && isThisTheSpaceCharacter(b))

				;

			return b;

		}

		private static double nextDouble() {

			return Double.parseDouble(next());

		}

		private static char nextChar() {

			return (char) skipItBishhhhhhh();

		}

		private static String next() {

			int b = skipItBishhhhhhh();

			StringBuilder sb = new StringBuilder();

			while (!(isThisTheSpaceCharacter(b))) {

				sb.appendCodePoint(b);

				b = justReadTheByte();

			}

			return sb.toString();

		}

		private static char[] readCharArray(int n) {

			char[] buf = new char[n];

			int b = skipItBishhhhhhh(), p = 0;

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

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

				b = justReadTheByte();

			}

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

		}

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

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

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

				map[i] = readCharArray(m);

			return map;

		}

		private static int[] readIntArray(int n) {

			int[] a = new int[n];

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

				a[i] = nextInt();

			return a;

		}

		private static long[] readLongArray(int n) {

			long[] a = new long[n];

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

				a[i] = nextLong();

			return a;

		}

		private static int nextInt() {

			int num = 0, b;

			boolean minus = false;

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

				;

			if (b == '-') {

				minus = true;

				b = justReadTheByte();

			}

			while (true) {

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

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

				} else {

					return minus ? -num : num;

				}

				b = justReadTheByte();

			}

		}

		private static long nextLong() {

			long num = 0;

			int b;

			boolean minus = false;

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

				;

			if (b == '-') {

				minus = true;

				b = justReadTheByte();

			}

			while (true) {

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

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

				} else {

					return minus ? -num : num;

				}

				b = justReadTheByte();

			}

		}

		private static void tr(Object... o) {

			if (INPUT.length() != 0)

				System.out.println(Arrays.deepToString(o));

		}

	}

}


E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23
16 17 14 20 20 11 22
OutputCopy3
NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good.

import java.io.*;

import java.util.StringTokenizer;

/**

 * * @author zhengnaishan

 * * @date 2023/2/13 9:21

 */

public class CF1324 {

    public static void main(String[] args) {

        Kattio io = new Kattio();

        int n = io.nextInt();

        int h = io.nextInt();

        int l = io.nextInt();

        int r = io.nextInt();

        int[] a = new int[n];

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

            a[i] = io.nextInt();

        }

        int ans = 0;

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

        long sum = 0;

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

            sum += a[i - 1];

            for (int j = i; j >= 0; j--) {

                long v = (sum - j) % h;

                s[j] = s[j] + (v >= l && v <= r ? 1 : 0);

                if (j > 0) {

                    s[j] = Math.max(s[j - 1] + (v >= l && v <= r ? 1 : 0), s[j]);

                }

                ans = Math.max(ans, s[j]);

            }

        }

        io.println(ans);

        io.flush();

    }

    public static class Kattio extends PrintWriter {

        private BufferedReader r;

        private StringTokenizer st;

        // 标准 IO

        public Kattio() {

            this(System.in, System.out);

        }

        public Kattio(InputStream i, OutputStream o) {

            super(o);

            r = new BufferedReader(new InputStreamReader(i));

        }

        // 文件 IO

        public Kattio(String intput, String output) throws IOException {

            super(output);

            r = new BufferedReader(new FileReader(intput));

        }

        // 在没有其他输入时返回 null

        public String next() {

            try {

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

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

                return st.nextToken();

            } catch (Exception e) {

            }

            return null;

        }

        public int nextInt() {

            return Integer.parseInt(next());

        }

        public double nextDouble() {

            return Double.parseDouble(next());

        }

        public long nextLong() {

            return Long.parseLong(next());

        }

    }

}


F. Three Paths on a Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.The simple path is the path that visits each vertex at most once.InputThe first line contains one integer number nn (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree. Next n−1n−1 lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.OutputIn the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠ca≠,b≠c,a≠c.If there are several answers, you can print any.ExampleInputCopy8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
OutputCopy5
1 8 6
NoteThe picture corresponding to the first example (and another one correct answer):If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer.

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.Comparator;

import java.util.Deque;

import java.util.HashMap;

import java.util.HashSet;

import java.util.LinkedList;

import java.util.Queue;

import java.util.Random;

import java.util.Scanner;

import java.util.StringTokenizer;

import java.util.Vector;

public class Main {

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

    /* ======================DSU===================== */

    static class dsu {

        static int parent[], n;// min[],value[];

        static long size[];

        dsu(int n) {

            parent = new int[n + 1];

            size = new long[n + 1];

            // min=new int[n+1];

            // value=new int[n+1];

            Main.dsu.n = n;

            makeSet();

        }

        static void makeSet() {

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

                parent[i] = i;

                size[i] = 1;

                // min[i]=i;

            }

        }

        static int find(int a) {

            if (parent[a] == a)

                return a;

            else {

                return parent[a] = find(parent[a]);// Path Compression

            }

        }

        static void union(int a, int b) {

            int setA = find(a);

            int setB = find(b);

            if (setA == setB)

                return;

            if (size[setA] >= size[setB]) {

                parent[setB] = setA;

                size[setA] += size[setB];

            } else {

                parent[setA] = setB;

                size[setB] += size[setA];

            }

        }

    }

    /* ======================================================== */

    static class Pair<X extends Number, Y extends Number> implements Comparator<Pair> {

        X x;

        Y y;

        // Constructor

        public Pair(X x, Y y) {

            this.x = x;

            this.y = y;

        }

        public Pair() {

        }

        @Override

        public int compare(Main.Pair o1, Main.Pair o2) {

            return ((int) (o1.y.intValue() - o2.y.intValue()));// Ascending Order based on 'y'

        }

    }

    /* ===============================Tries================================= */

    static class TrieNode {

        private HashMap<Character, TrieNode> children = new HashMap<>();

        public int size;

        boolean endOfWord;

        public void putChildIfAbsent(char ch) {

            children.putIfAbsent(ch, new TrieNode());

        }

        public TrieNode getChild(char ch) {

            return children.get(ch);

        }

    }

    static private TrieNode root;

    public static void insert(String str) {

        TrieNode curr = root;

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

            curr.putChildIfAbsent(ch);

            curr = curr.getChild(ch);

            curr.size++;

        }

        // mark the current nodes endOfWord as true

        curr.endOfWord = true;

    }

    public static int search(String word) {

        TrieNode curr = root;

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

            curr = curr.getChild(ch);

            if (curr == null) {

                return 0;

            }

        }

        // size contains words starting with prefix- word

        return curr.size;

    }

    public boolean delete(TrieNode current, String word, int index) {

        if (index == word.length()) {

            // when end of word is reached only delete if currrent.endOfWord is true.

            if (!current.endOfWord) {

                return false;

            }

            current.endOfWord = false;

            // if current has no other mapping then return true

            return current.children.size() == 0;

        }

        char ch = word.charAt(index);

        TrieNode node = current.children.get(ch);

        if (node == null) {

            return false;

        }

        boolean shouldDeleteCurrentNode = delete(node, word, index + 1);

        // if true is returned then delete the mapping of character and trienode

        // reference from map.

        if (shouldDeleteCurrentNode) {

            current.children.remove(ch);

            // return true if no mappings are left in the map.

            return current.children.size() == 0;

        }

        return false;

    }

    /* ================================================================= */

    static boolean isPrime(long n) {

        if (n <= 1)

            return false;

        if (n <= 3)

            return true;

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

            return false;

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

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

                return false;

        return true;

    }

    static Pair<Integer, Integer> lowerBound(long[] a, long x) { // x is the target, returns lowerBound. If not found

                                                                 // return -1

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

        while (l + 1 < r) {

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

            if (a[m] == x) {

                return new Pair<>(m, 1);

            }

            if (a[m] >= x)

                r = m;

            else

                l = m;

        }

        return new Pair<>(r, 0);

    }

    static Pair<Integer, Integer> upperBound(long[] a, long x) {// x is the target, returns upperBound. If not found

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

        while (l + 1 < r) {

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

            if (a[m] == x) {

                return new Pair<>(m, 1);

            }

            if (a[m] <= x)

                l = m;

            else

                r = m;

        }

        return new Pair<>(l + 1, 0);

    }

    static long gcd(long a, long b) {

        if (a == 0)

            return b;

        return gcd(b % a, a);

    }

    static long lcm(long a, long b) {

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

    }

    static long power(long x, long y) {

        long res = 1;

        while (y > 0) {

            if (y % 2 == 1)

                res = (res * x);

            y >>= 1;

            x = (x * x);

        }

        return res;

    }

    public double binPow(double x, int n) {// binary exponentiation with negative power as well

        if (n == 0)

            return 1.0;

        double binPow = binPow(x, n / 2);

        if (n % 2 == 0) {

            return binPow * binPow;

        } else {

            return n > 0 ? (binPow * binPow * x) : (binPow * binPow / x);

        }

    }

    static long ceil(long x, long y) {

        return (x % y == 0 ? x / y : (x / y + 1));

    }

    /*

     * ===========Modular Operations==================

     */

    static long modPower(long x, long y, long p) {

        long res = 1;

        x = x % p;

        while (y > 0) {

            if (y % 2 == 1)

                res = (res * x) % p;

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

            x = (x * x) % p;

        }

        return res;

    }

    static long modInverse(long n, long p) {

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

    }

    static long modAdd(long a, long b) {

        return ((a + b + mod) % mod);

    }

    static long modMul(long a, long b) {

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

    }

    static long[] fac = new long[200000 + 5];

    static long[] invFac = new long[200000 + 5];

    static long nCrModPFermat(int n, int r) {

        if (r == 0)

            return 1;

        // return (fac[n] * modInverse(fac[r], mod) % mod * modInverse(fac[n - r], mod)

        // % mod) % mod;

        return (fac[n] * invFac[r] % mod * invFac[n - r] % mod) % mod;

    }

    /*

     * ===============================================

     */

    static void ruffleSort(long[] a) {

        int n = a.length;

        Random r = new Random();

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

            int oi = r.nextInt(n);

            long temp = a[i];

            a[i] = a[oi];

            a[oi] = temp;

        }

        Arrays.sort(a);

    }

    static void ruffleSort(int[] a) {

        int n = a.length;

        Random r = new Random();

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

            int oi = r.nextInt(n);

            int temp = a[i];

            a[i] = a[oi];

            a[oi] = temp;

        }

        Arrays.sort(a);

    }

    static boolean isVowel(char ch) {

        return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u';

    }

    static String binString32(int n) {

        StringBuilder str = new StringBuilder("");

        String bin = Integer.toBinaryString(n);

        if (bin.length() != 32) {

            for (int k = 0; k < 32 - bin.length(); k++) {

                str.append("0");

            }

            str.append(bin);

        }

        return str.toString();

    }

    static class sparseTable {

        public static int st[][];

        public static int log = 4;

        static int func(int a, int b) {// make func as per question(here min range query)

            return (int) gcd(a, b);

        }

        void makeTable(int n, int a[]) {

            st = new int[n][log];

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

                st[i][0] = a[i];

            }

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

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

                    st[i][j] = func(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);

                }

            }

        }

        static int query(int l, int r) {

            int length = r - l + 1;

            int k = 0;

            while ((1 << (k + 1)) <= length) {

                k++;

            }

            return func(st[l][k], st[r - (1 << k) + 1][k]);

        }

        static void printTable(int n) {

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

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

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

                }

                System.out.println();

            }

        }

    }

    /*

     * ====================================Main=================================

     */

    // static int st[], a[];

    // static void buildTree(int treeIndex, int lo, int hi) {

    // if (hi == lo) {

    // st[treeIndex] = a[lo];

    // return;

    // }

    // int mid = (lo + hi) / 2;

    // buildTree(treeIndex * 2 + 1, lo, mid);

    // buildTree(treeIndex * 2 + 2, mid + 1, hi);

    // st[treeIndex] = merge(st[treeIndex * 2 + 1], st[treeIndex * 2 + 2]);

    // }

    // static void update(int treeIndex, int lo, int hi, int arrIndex, int val) {

    // if (hi == lo) {

    // st[treeIndex] = val;

    // a[arrIndex] = val;

    // return;

    // }

    // int mid = (hi + lo) / 2;

    // if (mid < arrIndex) {

    // update(treeIndex * 2 + 2, mid + 1, hi, arrIndex, val);

    // } else {

    // update(treeIndex * 2 + 1, lo, mid, arrIndex, val);

    // }

    // st[treeIndex] = merge(st[treeIndex * 2 + 1], st[treeIndex * 2 + 2]);

    // }

    // static int query(int treeIndex, int lo, int hi, int l, int r) {

    // if (l <= lo && r >= hi) {

    // return st[treeIndex];

    // }

    // if (l > hi || r < lo) {

    // return 0;

    // }

    // int mid = (hi + lo) / 2;

    // return query(treeIndex * 2 + 1, lo, mid, l, Math.min(mid, r));

    // }

    // static int merge(int a, int b) {

    // return a + b;

    // }

    public static long findKthPositive(long[] A, long k) {

        int l = 0, r = A.length, m;

        while (l < r) {

            m = (l + r) / 2;

            if (A[m] - 1 - m < k)

                l = m + 1;

            else

                r = m;

        }

        return l + k;

    }

    static int[] z_function(char ar[]) {

        int[] z = new int[ar.length];

        z[0] = ar.length;

        int l = 0;

        int r = 0;

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

            if (r < i) {

                l = i;

                r = i;

                while (r < ar.length && ar[r - l] == ar[r])

                    r++;

                z[i] = r - l;

                r--;

            } else {

                int k = i - l;

                if (z[k] < r - i + 1) {

                    z[i] = z[k];

                } else {

                    l = i;

                    while (r < ar.length && ar[r - l] == ar[r])

                        r++;

                    z[i] = r - l;

                    r--;

                }

            }

        }

        return z;

    }

    static void mergeSort(int a[]) {

        int n = a.length;

        if (n >= 2) {

            int mid = n / 2;

            int left[] = new int[mid];

            int right[] = new int[n - mid];

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

                left[i] = a[i];

            }

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

                right[i - mid] = a[i];

            }

            mergeSort(left);

            mergeSort(right);

            mergeSortedArray(left, right, a);

        }

    }

    static void mergeSortedArray(int left[], int right[], int a[]) {

        int i = 0, j = 0, k = 0, n = left.length, m = right.length;

        while (i != n && j != m) {

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

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

            } else {

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

            }

        }

        while (i != n) {

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

        }

        while (j != m) {

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

        }

    }

    // BINARY SEARCH

    // count of set bits in a particular position

    // suffix max array/ suffix sum array/ prefix

    static class FastReader {

        BufferedReader br;

        StringTokenizer st;

        public FastReader() {

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

        }

        String next() {

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

                try {

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

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

        String nextLine() {

            String str = "";

            try {

                str = br.readLine();

            } catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

        int[] intArr(int n) {

            int res[] = new int[n];

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

                res[i] = nextInt();

            return res;

        }

        long[] longArr(int n) {

            long res[] = new long[n];

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

                res[i] = nextLong();

            return res;

        }

    }

    static FastReader f = new FastReader();

    static BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));

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

    static HashSet<Integer> set = new HashSet<>();

    static int maxLevel = 0, farthestNode = -1;

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

        int t = 1;

        // t = f.nextInt();

        int tc = 1;

        // fac[0] = 1;

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

        // fac[i] = fac[i - 1] * i % mod;

        // invFac[i] = modInverse(fac[i], mod);

        // }

        while (t-- != 0) {

            int n = f.nextInt();

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

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

            }

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

                int u = f.nextInt();

                int v = f.nextInt();

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

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

            }

            dfs(1, -1, 0);

            int endPt1 = farthestNode;

            dfs(farthestNode, -1, 0);

            int endPt2 = farthestNode;

            // w.write(endPt1 + " " + endPt2 + "\n");

            Vector<Integer> stack = new Vector<Integer>();

            nodesInTheDia(endPt1, endPt2, n, stack);

            // w.write(set+"\n");

            int max = 0, maxNodeOutsideDiameter = -1;

            for (int node : set) {

                // int level[] = new int[n + 1];

                // int vis[] = new int[n + 1];

                // vis[node] = 1;

                // level[node] = 0;

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

                // q.add(node);

                // int flag = 0;

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

                //     int cur = q.poll();

                //     for (int child : g.get(cur)) {

                //         if (vis[child] == 0 && !set.contains(child)) {

                //             vis[child] = 1;

                //             level[child] = level[cur] + 1;

                //             q.add(child);

                //             flag = 1;

                //         }

                //     }

                // }

                // if (flag == 1) {

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

                //         if (level[i] > max) {

                //             max = level[i];

                //             maxNodeOutsideDiameter = i;

                //         }

                //     }

                // }

                Pair<Integer,Integer> p=maxDepthNode(node,0,0);

                if(p.y>=max) {

                    max = p.y;

                    maxNodeOutsideDiameter = p.x;

                }

                // w.write(p.y+" "+p.x+" "+node+"\n");

            }

            if(maxNodeOutsideDiameter==-1 || maxNodeOutsideDiameter==endPt1 || maxNodeOutsideDiameter==endPt2) {

                for(int i:set){

                    if(i!=endPt1 && i!=endPt2){

                        maxNodeOutsideDiameter=i;

                        break;

                    }

                }

            }

            w.write((set.size() - 1 + max) + "\n");

            w.write(endPt1 + " " + endPt2 + " " + maxNodeOutsideDiameter + "\n");

        }

        w.flush();

    }

    static Pair<Integer,Integer> maxDepthNode(int node,int parent,int depth){

        // if(g.get(node).size()==1){

        //     return new Pair<>(node,depth);

        // }

        Pair<Integer,Integer> max=new Pair<>(node,depth);

        for(int child:g.get(node)){

            if(child!=parent && !set.contains(child)){

                Pair<Integer,Integer> p=maxDepthNode(child,node,depth+1);

                if(p.y>max.y){

                    max=p;

                }

            }

        }

        return max;

    }

    static void dfs(int node, int parent, int level) {

        // System.out.println(node);

        if (level >= maxLevel) {

            maxLevel = level;

            farthestNode = node;

        }

        for (int i : g.get(node)) {

            if (i != parent) {

                dfs(i, node, level + 1);

            }

        }

    }

    static void printPath(Vector<Integer> stack) {

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

            set.add(stack.get(i));

        }

    }

    static void DFS(boolean vis[], int x, int y, Vector<Integer> stack) {

        stack.add(x);

        if (x == y) {

            printPath(stack);

            return;

        }

        vis[x] = true;

        if (g.get(x).size() > 0) {

            for (int j = 0; j < g.get(x).size(); j++) {

                if (vis[g.get(x).get(j)] == false) {

                    DFS(vis, g.get(x).get(j), y, stack);

                }

            }

        }

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

    }

    static void nodesInTheDia(int x, int y, int n, Vector<Integer> stack) {

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

        DFS(vis, x, y, stack);

    }

}

/*

 */


C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2
OutputCopy1 2
InputCopy6
OutputCopy2 3
InputCopy4
OutputCopy1 4
InputCopy1
OutputCopy1 1

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

public class Codeforces {
     public static void main(String[] args) {
        FastReader fastReader = new FastReader();
        PrintWriter out = new PrintWriter(System.out);
        int tt = 1;
         while(tt-->  0){
             long x =fastReader.nextLong();
             ArrayList<Long> left = new ArrayList<>();
             long ans1 = 1, ans2 = x;
             for(long i = 1; i *i <= x ; i++){
                 if(x%i == 0 && lcm(i,(x/i)) == x){
                     if(max(ans1,ans2) > max(i,(x/i))){
                         ans1= i;
                         ans2 = (x/i);
                     }

                 }
             }

             /*
             Collections.sort(left);
             for(int i = 0 ;i  < left.size() ; i++){
                 if(left.get(i) >= max(ans1,ans2)) break;
                 for(int j= i; j < left.size(); j++){
                    if(left.get(i) >= max(ans1,ans2)) break;
                     if(lcm(left.get(i),left.get(j)) == x && max(left.get(i),left.get(j)) < max(ans1,ans2)){
                         ans1 = left.get(i);
                         ans2 = left.get(j);
                     }
                 }
             }
             out.println(left.size());
             out.println(sqrt(x));

              */
             out.println(ans1 + " " + ans2);

         }

         out.close();
     }

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

    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return nonPrimes;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    static class FastReader {

        BufferedReader br;
        StringTokenizer st;

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

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

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

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

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

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

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

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


import java.util.*;

public class Main{

	public static void main(String []args){

		Scanner sc = new Scanner(System.in);

		long x = sc.nextLong();

		long ans = 1;

		for(long i=1; i<=Math.sqrt(x); i++){

			if(x%i==0&&gcd(i,x/i)==1){

				ans = i;

			}

		}

		System.out.println(ans+ " "+ (x/ans));

	}

	static long gcd(long a, long b){

		if(a%b==0) return b;

		return gcd(b, a%b);

	}

}


A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3
010011
0
1111000
OutputCopy2
0
0
NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).

import java.util.*;

public class OneRemove {

	public static void main(String [] args) {

		Scanner sc=new Scanner(System.in);

		int t=sc.nextInt();

		while(t-->0)

		{

			String s=sc.next();

			int one=0;

			int zero=0;

			int tone=0;

			int temp=0;

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

			{

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

				{

					tone++;

				}

			}

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

			{

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

				{

					one++;

					temp++;

				}

				if(temp==tone)

				{

					break;

				}

				if(one>0 && s.charAt(i)-'0'==0)

				{

					zero++;

				}

			}

			System.out.println(zero);

		}

	}

}