C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3
2 4
1 1
1 1
1 2
2 1
2 2

3 4
1 1 1
1 1
1 2
2 2
2 3

4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
OutputCopy2
1
12
NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11.

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.util.Random;
import java.util.HashMap;
import java.util.Collections;
import java.util.ArrayList;
import java.io.InputStream;

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

    static class CInstantNoodles {
        long[] random;

        public void solve(int testNumber, ScanReader in, PrintWriter out) {
            int t = in.scanInt();

            random = new long[500005];

            for (int i = 0; i < random.length; i++) random[i] = new Random().nextInt(1000000000) + 234792734l;

            while (t-- > 0) {
                int n = in.scanInt();
                int m = in.scanInt();
                long cost[] = new long[n + 1];
                for (int i = 1; i <= n; i++) cost[i] = in.scanLong();

                ArrayList<Integer> arrayList[] = new ArrayList[n + 1];
                for (int i = 1; i <= n; i++) arrayList[i] = new ArrayList<>();

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

                for (int i = 0; i < m; i++) {
                    int a = in.scanInt();
                    int b = in.scanInt();
                    arrayList[b].add(a);
                }

                for (int i = 1; i <= n; i++) {
                    if (arrayList[i].size() == 0) continue;
                    Collections.sort(arrayList[i]);
                    long hash = findHash(arrayList[i]);
                    hashMap.put(hash, cost[i] + hashMap.getOrDefault(hash, 0l));
                }

                long gcd = 0;
                for (long kkk : hashMap.values()) {
                    gcd = CodeX.GCD(gcd, kkk);
                }

                out.println(gcd);

            }

        }

        long findHash(ArrayList<Integer> arrayList) {
            int p = 0;
            long res = 0;
            for (int k : arrayList) {
                res = (res + ((k * random[p++]) % 792950153)) % 792950153;
            }
            return res;
        }

    }

    static class CodeX {
        public static long GCD(long A, long B) {
            if (B == 0)
                return A;
            else
                return GCD(B, A % B);
        }

    }

    static class ScanReader {
        private byte[] buf = new byte[4 * 1024];
        private int INDEX;
        private BufferedInputStream in;
        private int TOTAL;

        public ScanReader(InputStream inputStream) {
            in = new BufferedInputStream(inputStream);
        }

        private int scan() {
            if (INDEX >= TOTAL) {
                INDEX = 0;
                try {
                    TOTAL = in.read(buf);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (TOTAL <= 0) return -1;
            }
            return buf[INDEX++];
        }

        public int scanInt() {
            int I = 0;
            int n = scan();
            while (isWhiteSpace(n)) n = scan();
            int neg = 1;
            if (n == '-') {
                neg = -1;
                n = scan();
            }
            while (!isWhiteSpace(n)) {
                if (n >= '0' && n <= '9') {
                    I *= 10;
                    I += n - '0';
                    n = scan();
                }
            }
            return neg * I;
        }

        private boolean isWhiteSpace(int n) {
            if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
            else return false;
        }

        public long scanLong() {
            long I = 0;
            int n = scan();
            while (isWhiteSpace(n)) n = scan();
            int neg = 1;
            if (n == '-') {
                neg = -1;
                n = scan();
            }
            while (!isWhiteSpace(n)) {
                if (n >= '0' && n <= '9') {
                    I *= 10;
                    I += n - '0';
                    n = scan();
                }
            }
            return neg * I;
        }

    }
}


F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values:  his departure station ajaj;  his arrival station bjbj;  minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4
1 2
3 2
3 4
2
1 2 5
1 3 3
OutputCopy5 3 5
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
OutputCopy5 3 1 2 1
InputCopy6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
OutputCopy-1

// package c1296;

//
// Codeforces Round #617 (Div. 3) 2020-02-04 06:35
// F. Berland Beauty
// https://codeforces.com/contest/1296/problem/F
// time limit per test 3 seconds; memory limit per test 256 megabytes
// public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*'
//
// There are n railway stations in Berland. They are connected to each other by n-1 railway
// sections. The railway network is connected, i.e. can be represented as an undirected tree.
//
// You have a map of that network, so for each railway section you know which stations it connects.
//
// Each of the n-1 sections has some integer value of the . However, these values are not marked on
// the map and you don't know them. All these values are from 1 to 10^6 inclusive.
//
// You asked m passengers some questions: the j-th one told you three values:
//  * his departure station a_j;
//  * his arrival station b_j;
//  * minimum scenery beauty along the path from a_j to b_j (the train is moving along the shortest
//    path from a_j to b_j).
//
// You are planning to update the map and set some value f_i on each railway section -- the . The
// passengers' answers should be consistent with these values.
//
// Print any valid set of values f_1, f_2, ..., f_{n-1}, which the passengers' answer is consistent
// with or report that it doesn't exist.
//
// Input
//
// The first line contains a single integer n (2 <= n <= 5000) -- the number of railway stations in
// Berland.
//
// The next n-1 lines contain descriptions of the railway sections: the i-th section description is
// two integers x_i and y_i (1 <= x_i, y_i <= n, x_i != y_i), where x_i and y_i are the indices of
// the stations which are connected by the i-th railway section. All the railway sections are
// bidirected. Each station can be reached from any other station by the railway.
//
// The next line contains a single integer m (1 <= m <= 5000) -- the number of passengers which were
// asked questions. Then m lines follow, the j-th line contains three integers a_j, b_j and g_j (1
// <= a_j, b_j <= n; a_j != b_j; 1 <= g_j <= 10^6) -- the departure station, the arrival station and
// the minimum scenery beauty along his path.
//
// Output
//
// If there is no answer then print a single integer -1.
//
// Otherwise, print n-1 integers f_1, f_2, ..., f_{n-1} (1 <= f_i <= 10^6), where f_i is some valid
// scenery beauty along the i-th railway section.
//
// If there are multiple answers, you can print any of them.
//
// Example
/*
input:
4
1 2
3 2
3 4
2
1 2 5
1 3 3
output:
5 3 5

input:
6
1 2
1 6
3 1
1 5
4 1
4
6 1 3
3 4 1
6 5 2
1 2 5
output:
5 3 1 2 1

input:
6
1 2
1 6
3 1
1 5
4 1
4
6 1 1
3 4 3
6 5 3
1 2 4
output:
-1
*/
//

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;

public class C1296F {
  static final int MOD = 998244353;
  static final Random RAND = new Random();

  static int[] solve(int[][] edges, int[][] paths) {
    int n = edges.length + 1;
    int m = paths.length;

    List<int[]>[] adjs = new ArrayList[n+1];
    for (int i = 0; i < n+1; i++) {
      adjs[i] = new ArrayList<>();
    }
    for (int i = 0; i < n-1; i++) {
      int u = edges[i][0];
      int v = edges[i][1];
      adjs[u].add(new int[] {v, i});
      adjs[v].add(new int[] {u, i});
    }

    int[][] parent = new int[n+1][2];
    int[] depth = new int[n+1];
    int r = 1;

    Queue<Integer> q = new LinkedList<>();
    q.add(r);
    while (!q.isEmpty()) {
      int v = q.poll();
      for (int[] e : adjs[v]) {
        int w = e[0];
        if (w == parent[v][0]) {
          continue;
        }
        parent[w][0] = v;
        parent[w][1] = e[1];
        depth[w] = depth[v] + 1;
        q.add(w);
      }
    }
    if (test) System.out.format("  parent: %s\n", Arrays.deepToString(parent));

    int maxw = 0;
    for (int pid = 0; pid < m; pid++) {
      maxw = Math.max(maxw, paths[pid][2]);
    }

    // Evaluate all paths in descending weight order
    Arrays.sort(paths, (x,y)->y[2]-x[2]);

    int[] ans = new int[n-1];
    for (int pid = 0; pid < m; pid++) {
      int a = paths[pid][0];
      int b = paths[pid][1];
      int w = paths[pid][2];
      List<Integer> eids = getPathEdgesList(a, b, parent, depth);
      if (test) System.out.format("  pid:%d a:%d b:%d w:%d eids:%s\n", pid, a, b, w, eids.toString());
      // All the involved edges has minimal weight w
      boolean ok = false;
      for (int eid : eids) {
        myAssert(ans[eid] == 0 || ans[eid] >= w);
        if (ans[eid] == 0) {
          if (test) System.out.format("  assign %d %d\n", eid, w);
          ans[eid] = w;
          ok = true;
        } else if (ans[eid] == w) {
          ok = true;
        } else {
          // this edge won't satisfy w
        }
      }
      if (!ok) {
        // no edge in the path can support w
        return null;
      }
    }
    for (int i = 0; i < n-1; i++) {
      if (ans[i] == 0) {
        ans[i] = maxw;
      }
    }
    return ans;
  }

  // Time limit exceeded on test 268
  // 5000
  // 1 2
  // 2 3
  // 3 4
  // ...
  // test 264 5000 2261 ms  2262 ms
  // test 266 5000 2713 ms  2355 ms
  static int[] solveA(int[][] edges, int[][] paths) {
    int n = edges.length + 1;
    int m = paths.length;

    List<int[]>[] adjs = new ArrayList[n+1];
    for (int i = 0; i < n+1; i++) {
      adjs[i] = new ArrayList<>();
    }
    for (int i = 0; i < n-1; i++) {
      int u = edges[i][0];
      int v = edges[i][1];
      adjs[u].add(new int[] {v, i});
      adjs[v].add(new int[] {u, i});
    }

    int[][] parent = new int[n+1][2];
    int[] depth = new int[n+1];
    int r = 1;

    Queue<Integer> q = new LinkedList<>();
    q.add(r);
    while (!q.isEmpty()) {
      int v = q.poll();
      for (int[] e : adjs[v]) {
        int w = e[0];
        if (w == parent[v][0]) {
          continue;
        }
        parent[w][0] = v;
        parent[w][1] = e[1];
        depth[w] = depth[v] + 1;
        q.add(w);
      }
    }
    if (test) System.out.format("  parent: %s\n", Arrays.deepToString(parent));

    // pida[eid] is the path ids that contains edge eid
    Set<Integer>[] pida = new HashSet[n-1];
    for (int eid = 0; eid < n-1; eid++) {
      // Sort paths for the edge in ascending order of weight (smallest path first)
      // *** Note that if we sort, ensure the comparison is NOT 0 for different eid regardless ***
      // pida[eid] = new TreeSet<>((x, y)->paths[x][2] - paths[y][2]);
      pida[eid] = new HashSet<>();
    }

    TreeMap<Integer, Set<Integer>> wpids = new TreeMap<>();

    int maxw = 0;
    for (int pid = 0; pid < m; pid++) {
      int a = paths[pid][0];
      int b = paths[pid][1];
      int w = paths[pid][2];
      maxw = Math.max(maxw, w);
      List<Integer> eids = getPathEdgesList(a, b, parent, depth);
      if (test) System.out.format("  pid:%d a:%d b:%d w:%d eids:%s\n", pid, a, b, w, eids.toString());
      for (int eid : eids) {
        pida[eid].add(pid);
      }
      wpids.computeIfAbsent(w, x -> new HashSet<>()).add(pid);
    }

    for (int eid = 0; eid < n-1; eid++) {
      if (!pida[eid].isEmpty()) {
        if (test) {
          List<Integer> pids = new ArrayList<>(pida[eid]);
          System.out.format("  eid:%d pids:%s\n", eid, pids.toString());
        }
      }
    }
    for (Map.Entry<Integer, Set<Integer>> e : wpids.entrySet()) {
      int w = e.getKey();
      Set<Integer> pids = e.getValue();
      if (test) System.out.format("  w:%d pids:%s\n", w, pids.toString());
    }

    boolean[] edone = new boolean[n-1];
    boolean[] pdone = new boolean[m];

    int[] ans = new int[n-1];
    Arrays.fill(ans, maxw);

    Set<Integer> eids = new HashSet<>();
    for (int eid = 0; eid < n-1; eid++) {
      if (edone[eid] || pida[eid].isEmpty()) {
        continue;
      }
      eids.add(eid);
    }

    for (Map.Entry<Integer, Set<Integer>> e : wpids.entrySet()) {
      int w = e.getKey();
      Set<Integer> pids = e.getValue();
      if (test) System.out.format("  w:%d pids:%s\n", w, pids.toString());
      while (!pids.isEmpty()) {
        int eid = -1;
        for (int v : eids) {
          boolean ok = true;
          for (int pid : pida[v]) {
            myAssert(!pdone[pid]);
            if (paths[pid][2] != w) {
              ok = false;
              break;
            }
          }
          if (ok) {
            eid = v;
            break;
          }
        }
        if (eid < 0) {
          if (test) System.out.format("  no edge for %d found\n", w);
          return null;
        }
        if (test) System.out.format("  found edge %d for %d found\n", eid, w);
        Set<Integer> epids = pida[eid];

        if (test) System.out.format("    epids %s\n", epids.toString());

        ans[eid] = w;
        edone[eid] = true;
        // remove eid from all the paths that contain it
        for (int pid : epids) {
          pdone[pid] = true;
        }
        for (int v : eids) {
          if (v != eid) {
            pida[v].removeAll(epids);
            if (test) System.out.format("    v:%d %s\n", v, pida[v].toString());
          }
        }
        eids.remove(eid);
        pids.removeAll(epids);
      }
    }
    return ans;
  }

  static Set<Integer> getPathEdgesSet(int a, int b, int[][] parent, int[] depth) {
    if (depth[a] < depth[b]) {
      return getPathEdgesSet(b, a, parent, depth);
    }
    myAssert(depth[a] >= depth[b]);
    //        root
    //        /
    //       p
    //      / \
    //     *   b
    //    /
    //   a

    Set<Integer> edges = new HashSet<>();
    int x = a;
    for (int i = 0; i < depth[a] - depth[b]; i++) {
      edges.add(parent[x][1]);
      x = parent[x][0];
    }
    int y = b;
    while (x != y) {
      edges.add(parent[x][1]);
      x = parent[x][0];
      edges.add(parent[y][1]);
      y = parent[y][0];
    }
    return edges;
  }

  // Get list of edge ids on the path from a to b.
  // For efficiency, the order is not guarantee.
  static List<Integer> getPathEdgesList(int a, int b, int[][] parent, int[] depth) {
    if (depth[a] < depth[b]) {
      return getPathEdgesList(b, a, parent, depth);
    }
    myAssert(depth[a] >= depth[b]);
    //        root
    //        /
    //       p
    //      / \
    //     *   b
    //    /
    //   a

    List<Integer> edges = new ArrayList<>();
    int x = a;
    for (int i = 0; i < depth[a] - depth[b]; i++) {
      edges.add(parent[x][1]);
      x = parent[x][0];
    }
    int y = b;
    while (x != y) {
      edges.add(parent[x][1]);
      x = parent[x][0];
      edges.add(parent[y][1]);
      y = parent[y][0];
    }
    return edges;
  }

  static String trace(int[][] a) {
    return Arrays.deepToString(a).replace(" ", "").replace('[', '{').replace(']', '}');
  }

  static String trace(int[] a) {
    return Arrays.toString(a).replace(" ", "").replace('[', '{').replace(']', '}');
  }

  static void test(int[] exp, int[][] railways, int[][] paths) {
    System.out.format("edges:%s\n", trace(railways));
    System.out.format("paths:%s\n", trace(paths));
    int[] ans = solve(railways, paths);
    boolean ok = true;
    if (ans == null) {
      ok = exp == null;
      System.out.format("  => %s %s\n", trace(ans), ok ? "":"Expected " + trace(exp));
    } else if (exp == null) {
      System.out.format("  => %s Expected -1\n", trace(ans));
      ok = false;
    } else {
      for (int i = 0; i < ans.length; i++) {
        if (ans[i] != exp[i]) {
          ok = false;
          break;
        }
      }
      System.out.format("  => %s %s\n", trace(ans), ok ? "":"Expected " + trace(exp));
    }
    myAssert(ok);
  }

  static boolean test = false;
  static void doTest() {
    if (!test) {
      return;
    }
    long t0 = System.currentTimeMillis();
    test(new int[] {5,3,1,2,5}, new int[][] {{1,2},{1,6},{3,1},{1,5},{4,1}},
        new int[][] {{6,1,3},{3,4,1},{6,5,2},{1,2,5},{1,4,5}});

    test(new int[] {1}, new int[][] {{2,1}}, new int[][] {{1,2,1},{2,1,1}});
    test(null, new int[][] {{1,2},{3,1},{4,2}}, new int[][] {{2,4,1},{4,1,2}});
    test(new int[] {5,3,5}, new int[][] {{1,2},{3,2},{3,4}}, new int[][] {{1,2,5},{1,3,3}});
    test(new int[] {5,3,1,2,1}, new int[][] {{1,2},{1,6},{3,1},{1,5},{4,1}},
        new int[][] {{6,1,3},{3,4,1},{6,5,2},{1,2,5}});
    test(new int[] {3, 3}, new int[][] {{2,1},{3,1}}, new int[][] {{3,2,3}});
    test(new int[] {2, 4}, new int[][] {{1,2},{1,3}}, new int[][] {{3,2,2},{1,3,4}});

    test(null, new int[][] {{1,2},{1,6},{3,1},{1,5},{4,1}},
        new int[][] {{6,1,1},{3,4,3},{6,5,3},{1,2,4}});

    System.out.format("%d msec\n", System.currentTimeMillis() - t0);
    System.exit(0);
  }

  public static void main(String[] args) {
    doTest();
    MyScanner in = new MyScanner();
    int n = in.nextInt();
    int[][] railways = new int[n-1][2];
    for (int i = 0; i < n-1; i++) {
      railways[i][0] = in.nextInt();
      railways[i][1] = in.nextInt();
    }
    int m = in.nextInt();
    int[][] questions = new int[m][3];
    for (int i = 0; i < m; i++) {
      questions[i][0] = in.nextInt();
      questions[i][1] = in.nextInt();
      questions[i][2] = in.nextInt();
    }
    int[] ans = solve(railways, questions);
    output(ans);
  }

  static void output(int[] a) {
    if (a == null) {
      System.out.println("-1");
      return;
    }
    StringBuilder sb = new StringBuilder();
    for (int v : a) {
      sb.append(v);
      sb.append(' ');
      if (sb.length() > 4000) {
        System.out.print(sb.toString());
        sb.setLength(0);
      }
    }
    System.out.println(sb.toString());
  }

  static void myAssert(boolean cond) {
    if (!cond) {
      throw new RuntimeException("Unexpected");
    }
  }

  static class MyScanner {
    BufferedReader br;
    StringTokenizer st;

    public MyScanner() {
      try {
        final String USERDIR = System.getProperty("user.dir");
        String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", "");
        cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname;
        final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in");
        br = new BufferedReader(new InputStreamReader(fin.exists()
            ? new FileInputStream(fin) : System.in));
      } catch (Exception e) {
        br = new BufferedReader(new InputStreamReader(System.in));
      }
    }

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

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

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


E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be placed arbitrarily  — be inside each other, coincide and so on. Segments can degenerate into points, that is li=rili=ri is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example:  if n=3n=3 and there are segments [3,6][3,6], [100,100][100,100], [5,8][5,8] then their union is 22 segments: [3,8][3,8] and [100,100][100,100];  if n=5n=5 and there are segments [1,2][1,2], [2,3][2,3], [4,5][4,5], [4,6][4,6], [6,6][6,6] then their union is 22 segments: [1,3][1,3] and [4,6][4,6]. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given nn so that the number of segments in the union of the rest n−1n−1 segments is maximum possible.For example, if n=4n=4 and there are segments [1,4][1,4], [2,3][2,3], [3,6][3,6], [5,7][5,7], then:  erasing the first segment will lead to [2,3][2,3], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union;  erasing the second segment will lead to [1,4][1,4], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union;  erasing the third segment will lead to [1,4][1,4], [2,3][2,3], [5,7][5,7] remaining, which have 22 segments in their union;  erasing the fourth segment will lead to [1,4][1,4], [2,3][2,3], [3,6][3,6] remaining, which have 11 segment in their union. Thus, you are required to erase the third segment to get answer 22.Write a program that will find the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n−1n−1 segments.InputThe first line contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first of each test case contains a single integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of segments in the given set. Then nn lines follow, each contains a description of a segment — a pair of integers lili, riri (−109≤li≤ri≤109−109≤li≤ri≤109), where lili and riri are the coordinates of the left and right borders of the ii-th segment, respectively.The segments are given in an arbitrary order.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.OutputPrint tt integers — the answers to the tt given test cases in the order of input. The answer is the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.ExampleInputCopy3
4
1 4
2 3
3 6
5 7
3
5 5
5 5
5 5
6
3 3
1 1
5 5
1 5
2 2
4 4
OutputCopy2
1
5

import java.util.*;

import java.lang.*;

import java.io.*;

public class Main

{

	PrintWriter out = new PrintWriter(System.out);

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

    StringTokenizer tok = new StringTokenizer("");

    String next() throws IOException {

        if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); }

        return tok.nextToken();

    }

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

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

    long mod=1000000007;

    void solve() throws IOException {

        for (int tc=ni();tc>0;tc--) {

            int n=ni();

            int[][]A=new int[n][3];

            for (int i=0;i<n;i++) { A[i][0]=ni(); A[i][1]=ni(); A[i][2]=i;}

            Arrays.sort(A,(a,b)->Integer.compare(a[0],b[0]));

            int[]C=new int[n];

            HashSet<Integer>H=new HashSet();

            PriorityQueue<Pair>Q=new PriorityQueue<Pair>((a,b)->a.v-b.v);

            int max=0;

            int seg=-1;

            int ans=1;

            boolean end=false;

            boolean overlap=false;

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

                int nextstart=A[i][0];

                while (Q.size()>0 && Q.peek().v<nextstart) {

                    Pair toremove=Q.poll();

                    H.remove(toremove.id);

                    end=true;

                }

                if (end && H.size()==1 ) {

                    for (int v:H) {

                        C[v]++;

                        if (C[v]>max) { max=C[v]; seg=v; }

                    }

                }

                if (end && H.size()==0) { ans++; end=false; }

                if (H.size()>0) overlap=true;

                H.add(A[i][2]);

                Q.add(new Pair(A[i][1],A[i][2]));

            }

            if (!overlap) ans--;

            //out.println(ans+" "+max);

            out.println(ans+max);

        }

        out.flush();

    }

    class Pair {

        int v,id;

        Pair(int a,int b) { v=a; id=b; }

        int getval() { return v; }

    }

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

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

    long mp(long a,long p) { long r=1; while(p>0) { if ((p&1)==1) r=(r*a)%mod; p>>=1; a=(a*a)%mod; } return r; }

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

        new Main().solve();

    }

}


E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9
abacbecfd
OutputCopy2
1 1 2 1 2 1 2 1 2
InputCopy8
aaabbcbb
OutputCopy2
1 2 1 2 1 2 1 1
InputCopy7
abcdedc
OutputCopy3
1 1 1 1 1 2 3
InputCopy5
abcde
OutputCopy1
1 1 1 1 1

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.StringTokenizer;

public class StringColoring {

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

        new StringColoring().solve();

    }

    public void solve() throws IOException{

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

        PrintWriter out = new PrintWriter(System.out);

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

        char[] seq = f.readLine().toCharArray();

        int[] values = new int[n];

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

            values[i] = seq[i] - 'a';

        }

        seq = null;

        int[] color = new int[n];

        int[][] maxByColor = new int[n][26];

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

            color[i] = maxByColor[i][values[i]] + 1;

            if (i != n - 1) {

                for (int j = 0; j < values[i]; j++) {

                    maxByColor[i + 1][j] = Math.max(maxByColor[i][j], color[i]);

                }

                for (int j = values[i]; j < 26; j++) {

                    maxByColor[i + 1][j] = maxByColor[i][j];

                }

            }

        }

        int max = 0;

        for (int i = 0; i < n; i++) max = Math.max(max, color[i]);

        out.println(max);

        out.print(color[0]);

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

            out.print(" ");

            out.print(color[i]);

        }

        out.println();

        out.close();

    }

}


/*

        "Everything in the universe is balanced. Every disappointment

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

                        Keep going, never give up."

                        Just have Patience + 1...

*/

import java.util.*;

import java.lang.*;

import java.io.*;

public class Solution {

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

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

        sc = new FastReader();

        int test = 1;

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

            solve();

        }

        out.close();

    }

    private static void solve() {

        int n = sc.nextInt();

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

        int[] maxColorNeeded = new int[26];

        int[] dp = new int[n];

        Arrays.fill(dp, 1); // at least one color needed to color

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

            int index = s[i] - 'a';

            for (int j = 25; j > index; j--) { // swap is required for these chars, since we want to sort

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

            }

            maxColorNeeded[index] = Math.max(maxColorNeeded[index], dp[i]);

        }

        int maxColorRequired = 0;

        for (int colorsNeeded : maxColorNeeded) {

            maxColorRequired = Math.max(maxColorRequired, colorsNeeded);

        }

        out.println(maxColorRequired);

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

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

        }

        out.println();

    }

    public static FastReader sc;

    public static PrintWriter out;

    static class FastReader

    {

        BufferedReader br;

        StringTokenizer str;

        public FastReader()

        {

            br = new BufferedReader(new

                    InputStreamReader(System.in));

        }

        String next()

        {

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

            {

                try

                {

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

                }

                catch (IOException  end)

                {

                    end.printStackTrace();

                }

            }

            return str.nextToken();

        }

        int nextInt()

        {

            return Integer.parseInt(next());

        }

        long nextLong()

        {

            return Long.parseLong(next());

        }

        double nextDouble()

        {

            return Double.parseDouble(next());

        }

        String nextLine()

        {

            String str = "";

            try

            {

                str = br.readLine();

            }

            catch (IOException end)

            {

                end.printStackTrace();

            }

            return str;

        }

    }

}


D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3
1 2 3
OutputCopy2
InputCopy2
1 5
OutputCopy4
NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5.

//package Codeforces.GFG;

import java.util.*;

public class F {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        int n = in.nextInt();

        int[] ar = new int[n];

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

            ar[i] = in.nextInt();

        }

        Arrays.sort(ar);

        System.out.println(cal(30, 0, n - 1, ar));

    }

    static int cal(int index, int from, int to, int[] data) {

        if (index < 0) {

            return 0;

        }

        if (from > to) {

            return 0;

        }

        int re = -1;

        int st = from;

        int ed = to;

        while (st <= ed) {

            int mid = (st + ed) / 2;

            if ((data[mid] & (1 << index)) != 0) {

                re = mid;

                ed = mid - 1;

            } else {

                st = mid + 1;

            }

        }

        if (re != -1 && re != from) {

            int a = (1 << index) + cal(index - 1, from, re - 1, data);

            int b = (1 << index) + cal(index - 1, re, to, data);

            return Integer.min(a, b);

        } else {

            return cal(index - 1, from, to, data);

        }

    }

}


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

import java.util.ArrayList;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int t = sc.nextInt();

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

            int n = sc.nextInt();

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

            int sum = 0;

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

                arrayList.add(sc.nextInt() % 2);

                sum += arrayList.get(j);

            }

            if (sum == arrayList.size() || sum == 0) {

                System.out.println("YES");

            } else {

                System.out.println("NO");

            }

        }

    }

}


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.

import java.util.*;

public class cC {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		int t = sc.nextInt();

		while(t-->0) {

			int n = sc.nextInt();

			int neck[] = new int[n];

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

			int brac[] = new int[n];

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

			Arrays.sort(neck);

			Arrays.sort(brac);

			for(int i=0;i<n;i++)System.out.print(neck[i]+" ");

			System.out.println();

			for(int i=0;i<n;i++)System.out.print(brac[i]+" ");

			System.out.println();

		}

	}

}


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

import java.util.*;

import javax.print.DocFlavor.INPUT_STREAM;

import java.io.*;

import java.math.*;

import java.sql.Array;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.SQLIntegrityConstraintViolationException;

public class Main {

	 private static class MyScanner {

	        private static final int BUF_SIZE = 2048;

	        BufferedReader br;

	        private MyScanner() {

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

	        }

	        private boolean isSpace(char c) {

	            return c == '\n' || c == '\r' || c == ' ';

	        }

	        String next() {

	            try {

	                StringBuilder sb = new StringBuilder();

	                int r;

	                while ((r = br.read()) != -1 && isSpace((char)r));

	                if (r == -1) {

	                    return null;

	                }

	                sb.append((char) r);

	                while ((r = br.read()) != -1 && !isSpace((char)r)) {

	                    sb.append((char)r);

	                }

	                return sb.toString();

	            } catch (IOException e) {

	                e.printStackTrace();

	            }

	            return null;

	        }

	        int nextInt() {

	            return Integer.parseInt(next());

	        }

	        long nextLong() {

	            return Long.parseLong(next());

	        }

	        double nextDouble() {

	            return Double.parseDouble(next());

	        }

	    }

	  static class Reader{

			BufferedReader br;

			StringTokenizer st;

			public Reader() {

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

			}

			String next()

		    {

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

		        {

		            try

		            {

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

		            }

		            catch (IOException  e)

		            {

		                e.printStackTrace();

		            }

		        }

		        return st.nextToken();

		    }

		    int nextInt()

		    {

		        return Integer.parseInt(next());

		    }

		    long nextLong()

		    {

		        return Long.parseLong(next());

		    }

		    double nextDouble()

		    {

		        return Double.parseDouble(next());

		    }

		    String nextLine()

		    {

		        String str = "";

		        try

		        {

		            str = br.readLine();

		        }

		        catch (IOException e)

		        {

		            e.printStackTrace();

		        }

		        return str;

		    }

		}

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

	static void sort(long[] arr ) {

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

		 for(long e:arr) al.add(e);

		 Collections.sort(al);

		 for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);

	 }

	static void sort(int[] arr ) {

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

		 for(int e:arr) al.add(e);

		 Collections.sort(al);

		 for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);

	 }

	static void sort(char[] arr) {

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

		for(char cc:arr) al.add(cc);

		Collections.sort(al);

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

	}

	static long mod_mul(  long... a) {

		long ans = a[0]%mod;

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

			ans = (ans * (a[i]%mod))%mod;

		}

		return ans;

	}

	static long mod_sum( long... a) {

		long ans = 0;

		for(long e:a) {

			ans = (ans + e)%mod;

		}

		return ans;

	}

	 static long gcd(long a, long b)

	  {

	     if (b == 0)

	        return a;

	     return gcd(b, a % b);

	  }

	 static void print(long[] arr) {

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

		 for(long e:arr) System.out.print(e+" ");

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

	 }

	 static void print(int[] arr) {

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

		 for(long e:arr) System.out.print(e+" ");

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

	 }

	 static boolean[] prime(int num) {

			boolean[] bool = new boolean[num];

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

		         bool[i] = true;

		      }

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

		         if(bool[i] == true) {

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

		               bool[j] = false;

		            }

		         }

		      }

		      if(num >= 0) {

		    	  bool[0] = false;

		    	  bool[1] = false;

		      }

		      return bool;

		}

	 static long modInverse(long a, long m)

	    {

	        long g = gcd(a, m);

	          return   power(a, m - 2);

	    }

	   static long lcm(long a , long b) {

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

	   }

	   static int lcm(int a , int b) {

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

	   }

	 static long power(long x, long y){

		 if(y<0) return 0;

		 long m = mod;

	        if (y == 0) return 1; long p = power(x, y / 2) % m; p = (int)((p * (long)p) % m);

	        if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); }

     static class Combinations{

	    	 private long[] z;  // factorial

	    	 private long[] z1; // inverse factorial

	    	 private long[] z2; // incerse number

	    	 private long mod;

	    	  public Combinations(long N , long mod) {

	    		  this.mod = mod;

				z = new long[(int)N+1];

				z1 = new long[(int)N+1];

				z[0] = 1;

				for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod;

			     z2 = new long[(int)N+1];

				z2[0] = z2[1] = 1;

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

			        z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod;

			    z1[0] = z1[1] = 1;

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

			        z1[i] = (z2[i] * z1[i - 1]) % mod;

			}

	    	  long fac(long n) {

	    		  return z[(int)n];

	    	  }

	    	  long invrsNum(long n) {

	    		  return z2[(int)n];

	    	  }

	    	  long invrsFac(long n) {

	    		  return z1[(int)n];

	    	  }

	    	  long ncr(long N, long R)

	    	  {		if(R<0 || R>N ) return 0;

	    		    long ans = ((z[(int)N] * z1[(int)R])

	    		              % mod * z1[(int)(N - R)])

	    		             % mod;

	    		    return ans;

	    		}

	      }

	      static class DisjointUnionSets {

			    int[] rank, parent;

			    int n;

			    public DisjointUnionSets(int n)

			    {

			        rank = new int[n];

			        parent = new int[n];

			        this.n = n;

			        makeSet();

			    }

			    void makeSet()

			    {

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

			            parent[i] = i;

			        }

			    }

			    int find(int x)

			    {

			        if (parent[x] != x) {

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

			        }

			        return parent[x];

			    }

			    void union(int x, int y)

			    {

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

			        if (xRoot == yRoot)

			            return;

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

			            parent[xRoot] = yRoot;

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

			            parent[yRoot] = xRoot;

			        else

			        {

			            parent[yRoot] = xRoot;

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

			        }

			    }

			}

	      static int max(int... a ) {

	    	  int max = a[0];

	    	  for(int e:a) max = Math.max(max, e);

	    	  return max;

	      }

	      static long max(long... a ) {

	    	  long max = a[0];

	    	  for(long e:a) max = Math.max(max, e);

	    	  return max;

	      }

	      static int min(int... a ) {

	    	  int min = a[0];

	    	  for(int e:a) min = Math.min(e, min);

	    	  return min;

	      }

	      static long min(long... a ) {

	    	  long min = a[0];

	    	  for(long e:a) min = Math.min(e, min);

	    	  return min;

	      }

	      static int[] KMP(String str) {

	    	  int n = str.length();

	    	  int[] kmp = new int[n];

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

	    		  int j = kmp[i-1];

	    		  while(j>0 && str.charAt(i) != str.charAt(j)) {

	    			  j = kmp[j-1];

	    		  }

	    		  if(str.charAt(i) == str.charAt(j)) j++;

	    		  kmp[i] = j;

	    	  }

	    	  return kmp;

	      }

/************************************************ Query **************************************************************************************/

/***************************************** 		Sparse Table	********************************************************/

	      static class SparseTable{

	    		private long[][] st;

	    		SparseTable(long[] arr){

	    			int n = arr.length;

	    			st = new long[n][25];

	    			log = new int[n+2];

	    			build_log(n+1);

	    			build(arr);

	    		}

	    		private void build(long[] arr) {

	    			int n = arr.length;

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

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

	    					int r = i + (1<<j)-1;

	    					if(r>=n) break;

	    					if(j == 0 ) st[i][j] = arr[i];

	    					else st[i][j] = Math.max(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] );

	    				}

	    			}

	    		}

	    		public long gcd(long a  ,long b) {

	    			if(a == 0) return b;

	    			return gcd(b%a , a);

	    		}

	    		public long query(int l ,int r) {

	    			int w = r-l+1;

	    			int power = log[w];

	    			return Math.max(st[l][power],st[r - (1<<power) + 1][power]);

	    		}

	    		private int[] log;

	    		void build_log(int n) {

	    			log[1] = 0;

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

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

	    			}

	    		}

	    	}

/********************************************************	Segement Tree	*****************************************************/

	 	 static class SegmentTree{

			 long[] tree;

			 long[] arr;

			 int n;

			 SegmentTree(long[] arr){

				 this.n = arr.length;

				 tree = new long[4*n+1];

				 this.arr = arr;

				 buildTree(0, n-1, 1);

			 }

			  void buildTree(int s ,int e  ,int index ) {

					if(s == e) {

						tree[index] = arr[s];

						return;

					}

					int mid = (s+e)/2;

					buildTree( s,  mid, 2*index);

					buildTree( mid+1, e, 2*index+1);

					tree[index] = gcd(tree[2*index] , tree[2*index+1]);

				}

			 long query(int si ,int ei) {

				 return query(0 ,n-1 , si ,ei , 1   );

			 }

			 private long query( int ss ,int se ,int qs , int qe,int index) {

					if(ss>=qs && se<=qe) return tree[index];

					if(qe<ss || se<qs) return (long)(0);

					int mid = (ss + se)/2;

					long left = query( ss , mid , qs ,qe , 2*index);

					long right= query(mid + 1 , se , qs ,qe , 2*index+1);

					return gcd(left, right);

				}

			 public void update(int index , int val) {

				 arr[index] = val;

//				 for(long e:arr) System.out.print(e+" ");

				 update(index , 0 , n-1 , 1);

			 }

			 private void update(int id ,int si , int ei , int index) {

				 if(id < si || id>ei) return;

				 if(si == ei ) {

					 tree[index] = arr[id];

					 return;

				 }

				 if(si > ei) return;

				 int mid = (ei + si)/2;

					update( id,  si, mid , 2*index);

					update( id , mid+1, ei , 2*index+1);

					tree[index] = Math.min(tree[2*index] ,tree[2*index+1]);

			 }

		 }

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

//	      static MyScanner sc = new MyScanner(); // only in case of less memory

	      static Reader sc = new Reader();

	      static int TC;

	 static StringBuilder sb = new StringBuilder();

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

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

		 int tc = 1;

//		 tc = sc.nextInt();

		 TC = 0;

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

			 TC++;

//			 sb.append("Case #" + i + ": "  );	// During KickStart && HackerCup

			 TEST_CASE();

		 }

		 System.out.print(sb);

	 }

	 static void TEST_CASE() throws IOException {

		 long h = sc.nextLong();

		 int n = sc.nextInt();

		 long[] arr = new long[n];

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

			 arr[i] = sc.nextLong();

		 long[] pre = new long[n];

		 pre[0] = arr[0];

		 if(arr[0]+h<=0) {

			 sb.append("1\n");

			 return;

		 }

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

			 pre[i] = arr[i] + pre[i-1];

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

				 sb.append(i+1).append("\n");

				 return;

			 }

		 }

		 if(pre[n-1]>=0) {

			 sb.append("-1\n");

			 return;

		 }

//		 System.out.println(pre[n-1]);

		 long ans = Long.MAX_VALUE;

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

			 long nh = h+pre[i];

			 long r = nh/(-pre[n-1]);

			 if(nh%(-pre[n-1])!=0) r++;

//			 System.out.println(nh +" - "+(r*n+i+1));

			 ans = min(ans , r*n+i+1);

		 }

		 sb.append(ans+"\n");

	 }

	}

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

/**

 */


A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — 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≤30001≤n≤3000)  — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit).

import java.util.Scanner;

import java.util.Arrays;

import java.util.HashSet;

import java.util.Iterator;

import java.util.HashMap;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Random;

import java.util.LinkedList;

import java.util.TreeSet;

import java.util.PriorityQueue;

import java.util.Deque;

public class Solution{

    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);

        int test_cases = sc.nextInt();

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

            //scan the input

            int n = sc.nextInt();

            String s = sc.next();

            String ans = "";

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

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

                    ans+=s.charAt(i);

                }

                if(ans.length()==2){

                    break;

                }

            }

            if(ans.length()!=2){

                System.out.println(-1);

            }

            else{

                System.out.println(ans);

            }

        }

        sc.close();

    }

    public static boolean check_sorted(long a[]){

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

            if(a[i]<=a[i+1]){

                return true;

            }

        }

        return false;

    }

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

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

            s[i] = sc.next();

        }

    }

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

        int temp = a[s_index];

        a[s_index] = a[e_index];

        a[e_index] = temp;

    }

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

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

            a[i] = sc.nextLong();

        }

    }

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

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

            a[i] = sc.nextInt();

        }

    }

    public static void print_array(int a[]){

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

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

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

                return;

            }

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

        }

    }

    public static long sum_array(long a[]){

        long sum = 0;

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

            sum+=a[i];

        }

        return sum;

    }

    public static boolean perfect_square(double num){

        boolean isSq = false;

        double b = Math.sqrt(num);

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

        if(c==0){

            isSq=true;

        }

        return isSq;

    }

    public static boolean ispalindrome(String s){

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

        while(i<=j){

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

                return false;

            }

            i++;

            j--;

        }

        return true;

    }

    public static boolean ispowerOftwo(int n){

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

            return true;

        }

        else{

            return false;

        }

    }

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

        int gcd = 1;

        if(x%y==0){

            return y;

        }

        else if(y%x==0){

            return x;

        }

        else{

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

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

                    gcd = i;

                }

            }

            return gcd;

        }

    }

    public static long calculate_factorial(long x){

        long ans = 1;

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

            ans*=i;

        }

        return ans;

    }

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

        int temp = a[index_a];

        a[index_a] = b[index_b];

        b[index_b] = temp;

    }

    public static int find_maximum(int a[]){

        int max = Integer.MIN_VALUE;

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

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

        }

        return max;

    }

    public static int find_minimum(int a[]){

        int min = Integer.MAX_VALUE;

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

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

        }

        return min;

    }

    public static void ruffleSort(int[] a) {

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

        Random random = new Random();

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

            int oi=random.nextInt(n);

            int temp=a[oi];

            a[oi]=a[i];

            a[i]=temp;

        }

        Arrays.sort(a);

    }

    public static int sum_of_digits(int n){

        int s =0;

        while(n!=0){

            s+=n%10;

            n/=10;

        }

        return s;

    }

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

        if (array.length <= 1) {

            return array;

        }

        int midpoint = array.length / 2;

        int[] left = new int[midpoint];

        int[] right;

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

            right = new int[midpoint];

        } else {

            right = new int[midpoint + 1];

        }

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

            left[i] = array[i];

        }

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

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

        }

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

        left = mergeSort(left);

        right = mergeSort(right);

        result = merge(left, right);

        return result;

    }

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

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

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

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

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

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

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

                } else {

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

                }

            } else if (leftPointer < left.length) {

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

            } else {

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

            }

        }

        return result;

    }

}


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

import java.util.HashSet;

import java.util.Scanner;

import java.util.Set;

import java.util.stream.Collectors;

import java.util.stream.IntStream;

public class Main {

  static final int ALPHABET_SIZE = 26;

  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    int T = sc.nextInt();

    for (int tc = 0; tc < T; ++tc) {

      String s = sc.next();

      System.out.println(solve(s));

    }

    sc.close();

  }

  static String solve(String s) {

    @SuppressWarnings("unchecked")

    Set<Integer>[] adjSets = new Set[ALPHABET_SIZE];

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

      adjSets[i] = new HashSet<>();

    }

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

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

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

      adjSets[index1].add(index2);

      adjSets[index2].add(index1);

    }

    StringBuilder layout =

        new StringBuilder(

            IntStream.range(0, adjSets.length)

                .filter(i -> adjSets[i].isEmpty())

                .mapToObj(i -> String.valueOf((char) (i + 'a')))

                .collect(Collectors.joining()));

    boolean[] visited = new boolean[adjSets.length];

    int[] begins = IntStream.range(0, adjSets.length).filter(i -> adjSets[i].size() == 1).toArray();

    for (int begin : begins) {

      if (!visited[begin]) {

        visited[begin] = true;

        layout.append((char) (begin + 'a'));

        int current = begin;

        while (!adjSets[current].isEmpty()) {

          int next = adjSets[current].iterator().next();

          adjSets[next].remove(current);

          current = next;

          if (visited[current]) {

            return "NO";

          }

          visited[current] = true;

          layout.append((char) (current + 'a'));

        }

      }

    }

    return (layout.length() == ALPHABET_SIZE) ? String.format("YES\n%s", layout) : "NO";

  }

}


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

import java.io.*;

import java.util.*;

public class CF1305B extends PrintWriter {

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

	Scanner sc = new Scanner(System.in);

	public static void main(String[] $) {

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

	}

	void main() {

		byte[] cc = sc.next().getBytes();

		int n = cc.length;

		int[] ii = new int[n];

		int k = 0;

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

			while (i < n && cc[i] != '(')

				i++;

			while (j >= 0 && cc[j] != ')')

				j--;

			if (i < j) {

				ii[k] = i;

				ii[n - 1 - k] = j;

				k++;

			}

		}

		if (k == 0) {

			println(0);

			return;

		}

		println(1);

		println(k * 2);

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

			print(ii[h] + 1 + " ");

		for (int h = n - k; h < n; h++)

			print(ii[h] + 1 + " ");

		println();

	}

}


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

import java.lang.*;

public class Y

{

	public int[][][] abc;

	public int[][] up;

    public static void main(String[] args)

    {

        Y ob=new Y();

		Scanner sc=new Scanner(System.in);

		int N=sc.nextInt();

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

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

		{

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

		}

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

		{

			int U=sc.nextInt();

			int V=sc.nextInt();

			U=U-1;

			V=V-1;

			AA.get(U).add(V);

			AA.get(V).add(U);

		}

		ob.solve(AA);

    }

	void solve(ArrayList<ArrayList<Integer>> AA)

	{

		abc=new int[AA.size()][3][2];

		int d=fill(AA,0,-1);

		up=new int[AA.size()][2];

		up[0][0]=0;

		up[0][1]=0;

		int u=upfill(AA,0,-1);

		show(AA);

	}

	void show(ArrayList<ArrayList<Integer>> AA)

	{

		int m=0;

		int a=0;

		int b=0;

		int c=0;

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

		{

			/*

			System.out.println();

			System.out.println("curr -> "+i);

			System.out.println("up.D -> "+up[i][0]+" , up.P -> "+up[i][1]);

			System.out.println("D0.D -> "+abc[i][0][0]+" , D0.P -> "+abc[i][0][1]);

			System.out.println("D1.D -> "+abc[i][1][0]+" , D1.P -> "+abc[i][1][1]);

			System.out.println("D2.D -> "+abc[i][2][0]+" , D2.P -> "+abc[i][2][1]);

			*/

			int upp=up[i][1];

			int d0p=abc[i][0][1];

			int d1p=abc[i][1][1];

			int d2p=abc[i][2][1];

			if(m<(abc[i][0][0]+abc[i][1][0]+up[i][0]) && (upp!=d0p && d0p!=d1p && d1p!=upp))

			{

				m=(abc[i][0][0]+abc[i][1][0]+up[i][0]);

				a=abc[i][0][1];

				b=abc[i][1][1];

				c=up[i][1];

			}

			if(m<(abc[i][0][0]+abc[i][1][0]+abc[i][2][0]) && (d2p!=d0p && d0p!=d1p && d1p!=d2p))

			{

				m=(abc[i][0][0]+abc[i][1][0]+abc[i][2][0]);

				a=abc[i][0][1];

				b=abc[i][1][1];

				c=abc[i][2][1];

			}

		}

		System.out.println(m);

		System.out.println((a+1)+" "+(b+1)+" "+(c+1));

	}

	int fill(ArrayList<ArrayList<Integer>> AA,int curr,int parent)

	{

		abc[curr][0][0]=abc[curr][1][0]=abc[curr][2][0]=0;

		abc[curr][0][1]=abc[curr][1][1]=abc[curr][2][1]=curr;

		if(AA.get(curr).size()==1 && AA.get(curr).get(0)==parent)

		{

			return 0;

		}

		PriorityQueue<Point> pq=new PriorityQueue<Point>(new PC());

		for(int i=0;i<AA.get(curr).size();i++)

		{

			int now=AA.get(curr).get(i);

			if(now==parent)

			{

				continue;

			}

			fill(AA,now,curr);

			if(pq.size()<3)

			{

				pq.add(new Point(abc[now][0][0],abc[now][0][1]));

			}

			else if(pq.size()==3 && pq.peek().D<abc[now][0][0])

			{

				pq.poll();

				pq.add(new Point(abc[now][0][0],abc[now][0][1]));

			}

		}

		int j=0;

		while(0<pq.size())

		{

			j=pq.size();

			j=j-1;

			Point P=pq.poll();

			abc[curr][j][0]=P.D+1;

			abc[curr][j][1]=P.P;

		}

		return abc[curr][0][0];

	}

	int upfill(ArrayList<ArrayList<Integer>> AA,int curr,int parent)

	{

		int[][] DD=new int[3][2];

		DD[0][0]=up[curr][0];

		DD[0][1]=up[curr][1];

		DD[1][0]=abc[curr][0][0];

		DD[1][1]=abc[curr][0][1];

		DD[2][0]=abc[curr][1][0];

		DD[2][1]=abc[curr][1][1];

		for(int i=0;i<AA.get(curr).size();i++)

		{

			int next=AA.get(curr).get(i);

			if(next==parent)

			{

				continue;

			}

			int MD=DD[0][0];

			int MP=DD[0][1];

			if(abc[next][0][1]!=DD[1][1] && MD<DD[1][0])

			{

				MD=DD[1][0];

				MP=DD[1][1];

			}

			if(abc[next][0][1]!=DD[2][1] && MD<DD[2][0])

			{

				MD=DD[2][0];

				MP=DD[2][1];

			}

			up[next][0]=MD+1;

			up[next][1]=MP;

			upfill(AA,next,curr);

		}

		return DD[0][0];

	}

	public class Point

	{

		int D;

		int P;

		Point(int d,int p)

		{

			D=d;

			P=p;

		}

	}

	public class PC implements Comparator<Point>

	{

		public int compare(Point P1,Point P2)

		{

			return P1.D-P2.D;

		}

	}

}


C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.

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

public class Practice {

	static boolean multipleTC = false;
	final static int mod = 1000000007;
	final static int mod2 = 998244353;
	final double E = 2.7182818284590452354;
	final double PI = 3.14159265358979323846;
	int MAX = 10000005;

	void pre() throws Exception {
	}

	// All the best
	void solve(int TC) throws Exception {
		int n = ni(), arr[] = readArr(n);
		long max = 0;
		int res[] = new int[n];
		for (int i = 0; i < n; i++) {
			int cur[] = calc(arr, n, i);
			long sum = sum(cur);
			if (max < sum) {
				res = cur;
				max = sum;
			}
		}
		StringBuilder ans = new StringBuilder();
		for (int i = 0; i < n; i++) {
			ans.append(res[i] + " ");
		}
		pn(ans);
	}

	private int[] calc(int[] arr, int n, int peek) {
		int res[] = new int[n];
		res[peek] = arr[peek];
		for (int i = peek - 1; i >= 0; i--) {
			if (arr[i] > res[i + 1]) {
				res[i] = res[i + 1];
			} else {
				res[i] = arr[i];
			}
		}
		for (int i = peek + 1; i < n; i++) {
			if (arr[i] > res[i - 1]) {
				res[i] = res[i - 1];
			} else {
				res[i] = arr[i];
			}
		}
		return res;
	}

	int cur;

	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[], int left, int right) {
		ArrayList<Integer> list = new ArrayList<>();
		for (int i = left; i <= right; i++)
			list.add(arr[i]);
		Collections.sort(list);
		for (int i = left; i <= right; i++)
			arr[i] = list.get(i - left);
	}

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

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

	FastReader in;
	PrintWriter out;

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

	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. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5
3 7 9 7 8
5 2 5 7 5
OutputCopy6
InputCopy5
1 2 3 4 5
1 1 1 1 1
OutputCopy0
NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.

import java.io.BufferedOutputStream;

import java.io.Closeable;

import java.io.DataInputStream;

import java.io.Flushable;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.AbstractMap;

import java.util.Arrays;

import java.util.Comparator;

import java.util.InputMismatchException;

import java.util.Map;

import java.util.TreeMap;

/**

 * Built using CHelper plug-in

 * Actual solution is at the top

 */

public class Main {

	static class TaskAdapter implements Runnable {

		@Override

		public void run() {

			long startTime = System.currentTimeMillis();

			InputStream inputStream = System.in;

			OutputStream outputStream = System.out;

			FastReader in = new FastReader(inputStream);

			Output out = new Output(outputStream);

			ARecommendations solver = new ARecommendations();

			solver.solve(1, in, out);

			out.close();

			System.err.println(System.currentTimeMillis()-startTime+"ms");

		}

	}

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

		Thread thread = new Thread(null, new TaskAdapter(), "", 1<<28);

		thread.start();

		thread.join();

	}

	static class ARecommendations {

		public ARecommendations() {

		}

		public void solve(int kase, InputReader in, Output pw) {

			int n = in.nextInt();

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

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

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

					arr[i][j] = in.nextInt();

				}

			}

			Arrays.sort(arr, Comparator.comparingInt(o -> o[0]));

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

			long ans = 0, sum = 0, cnt = 0;

			int i = 0, cur = -1;

			while(i<n||!tm.isEmpty()) {

				if(tm.isEmpty()) {

					cur = arr[i][0];

				}

				for(; i<n&&arr[i][0]==cur; i++) {

					Utilities.add(tm, arr[i][1]);

					sum += arr[i][1];

				}

				sum -= tm.lastKey();

				Utilities.remove(tm, tm.lastKey());

				ans += sum;

				cur++;

			}

			;

			pw.println(ans);

		}

	}

	static class Utilities {

		public static <K, V> V getOrDefault(Map<? extends K, ? extends V> map, K key, V value) {

			V ret = map.get(key);

			if(ret==null) {

				return value;

			}

			return ret;

		}

		public static <T> void add(Map<? super T, Integer> map, T key) {

			map.put(key, getOrDefault(map, key, 0)+1);

		}

		public static <T> void remove(Map<? super T, Integer> map, T key) {

			int cnt = getOrDefault(map, key, 1)-1;

			if(cnt>0) {

				map.put(key, cnt);

			}else {

				map.remove(key);

			}

		}

	}

	static class Output implements Closeable, Flushable {

		public StringBuilder sb;

		public OutputStream os;

		public int BUFFER_SIZE;

		public String lineSeparator;

		public Output(OutputStream os) {

			this(os, 1<<16);

		}

		public Output(OutputStream os, int bs) {

			BUFFER_SIZE = bs;

			sb = new StringBuilder(BUFFER_SIZE);

			this.os = new BufferedOutputStream(os, 1<<17);

			lineSeparator = System.lineSeparator();

		}

		public void println(long l) {

			println(String.valueOf(l));

		}

		public void println(String s) {

			sb.append(s);

			println();

		}

		public void println() {

			sb.append(lineSeparator);

		}

		private void flushToBuffer() {

			try {

				os.write(sb.toString().getBytes());

			}catch(IOException e) {

				e.printStackTrace();

			}

			sb = new StringBuilder(BUFFER_SIZE);

		}

		public void flush() {

			try {

				flushToBuffer();

				os.flush();

			}catch(IOException e) {

				e.printStackTrace();

			}

		}

		public void close() {

			flush();

			try {

				os.close();

			}catch(IOException e) {

				e.printStackTrace();

			}

		}

	}

	static class FastReader implements InputReader {

		final private int BUFFER_SIZE = 1<<16;

		private DataInputStream din;

		private byte[] buffer;

		private int bufferPointer;

		private int bytesRead;

		public FastReader(InputStream is) {

			din = new DataInputStream(is);

			buffer = new byte[BUFFER_SIZE];

			bufferPointer = bytesRead = 0;

		}

		public int nextInt() {

			int ret = 0;

			byte c = skipToDigit();

			boolean neg = (c=='-');

			if(neg) {

				c = read();

			}

			do {

				ret = ret*10+c-'0';

			} while((c = read())>='0'&&c<='9');

			if(neg) {

				return -ret;

			}

			return ret;

		}

		private boolean isDigit(byte b) {

			return b>='0'&&b<='9';

		}

		private byte skipToDigit() {

			byte ret;

			while(!isDigit(ret = read())&&ret!='-') ;

			return ret;

		}

		private void fillBuffer() {

			try {

				bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);

			}catch(IOException e) {

				e.printStackTrace();

				throw new InputMismatchException();

			}

			if(bytesRead==-1) {

				buffer[0] = -1;

			}

		}

		private byte read() {

			if(bytesRead==-1) {

				throw new InputMismatchException();

			}else if(bufferPointer==bytesRead) {

				fillBuffer();

			}

			return buffer[bufferPointer++];

		}

	}

	static interface InputReader {

		int nextInt();

	}

}