C. Au Pont Rougetime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK just opened its second HQ in St. Petersburg! Side of its office building has a huge string ss written on its side. This part of the office is supposed to be split into mm meeting rooms in such way that meeting room walls are strictly between letters on the building. Obviously, meeting rooms should not be of size 0, but can be as small as one letter wide. Each meeting room will be named after the substring of ss written on its side.For each possible arrangement of mm meeting rooms we ordered a test meeting room label for the meeting room with lexicographically minimal name. When delivered, those labels got sorted backward lexicographically.What is printed on kkth label of the delivery?InputIn the first line, you are given three integer numbers n,m,kn,m,k — length of string ss, number of planned meeting rooms to split ss into and number of the interesting label (2≤n≤1000;1≤m≤1000;1≤k≤10182≤n≤1000;1≤m≤1000;1≤k≤1018).Second input line has string ss, consisting of nn lowercase english letters.For given n,m,kn,m,k there are at least kk ways to split ss into mm substrings.OutputOutput single string – name of meeting room printed on kk-th label of the delivery.ExamplesInputCopy4 2 1
abac
OutputCopyaba
InputCopy19 5 1821
aupontrougevkoffice
OutputCopyau
NoteIn the first example; delivery consists of the labels "aba"; "ab"; "a".In the second example; delivery consists of 30603060 labels. The first label is "aupontrougevkof" and the last one is "a".

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Collectors;

public class C1310C_2 {
    public static void main(String[] args) {
        var scanner = new BufferedScanner();
        var writer = new PrintWriter(new BufferedOutputStream(System.out));

        var n = scanner.nextInt();
        var m = scanner.nextInt();
        var k = scanner.nextLong();
        var s = scanner.next().toCharArray();
//        var n = 1000;
//        var m = 800;
//        var k = (long) 1e18;
//        var sb = new StringBuilder();
//        for (int i = 0; i < n; i++) {
//            sb.append((char) (Math.random() * 3 + 'a'));
//        }
//        var s = sb.toString().toCharArray();
        var t = System.nanoTime();
        writer.println(solve(n, m, k, s));
//        System.out.println((System.nanoTime() - t) / 1e9);

        scanner.close();
        writer.flush();
        writer.close();
    }

    static final long K_MAX = (long) 1e18;

    private static String solve(int n, int m, long k, char[] s) {
        var lcp = lcp(n, s);
        var subs = subs(n, s, lcp);
        var low = 0;
        var high = subs.size() - 1;
        var found = -1;
        while (low <= high && found < 0) {
            var mid = (low + high) >>> 1;
            var gte = countGte(n, s, m, subs.get(mid), lcp);
            var countFrom = gte[1] + 1;
            var countTo = gte[1] + gte[0];
//            System.out.println(subs.get(mid) + " " + Arrays.toString(gte));
            if (countFrom <= k && k <= countTo) {
                found = mid;
            } else if (countTo < k) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }

        }
        return new String(s, subs.get(found).from, subs.get(found).len);
    }

    static int compare(int from1, int len1, int from2, int len2, int[][] lcp, char[] s) {
        var common = lcp[from1][from2];
        if (common >= len1 || common >= len2) {
            return Integer.compare(len1, len2); // 谁长谁大
        } else {
            return Character.compare(s[from1 + common], s[from2 + common]);
        }
    }

    private static long[] countGte(int n, char[] s, int m, Sub minS, int[][] lcp) {
        int minSLen = minS.len;
        var dp0 = new long[m + 1][n + 1];
        var dp1 = new long[m + 1][n + 1];
        dp0[0][0] = 0; // 长度为0划分为0个部分，其中至少一个等于minS的划分数为0。
        dp1[0][0] = 1; // 长度为0划分为0个部分，其中所有都大于minS的划分数为1。
        for (int parts = 1; parts <= m; parts++) {
            var change = new HashMap<Integer, List<Integer>>();
            var dp0Acc = new long[]{0, 0}; // [0]:small sum; [1]:large count
            var dp1Acc = new long[]{0, 0}; // [0]:small sum; [1]:large count
            for (int len = parts; len <= n; len++) {
                int start = len - 1;
                // 前面开始的子串，到这一步可能有几个变化：一直是minS前缀（长度可能是0）的，变大于、等于、小于minS了。
                // 先把当前这个加进去
                if (compare(start, len - start, minS.from, minS.len, lcp, s) > 0) {
                    // 第1位就大于minS的，无论怎么延长都会一直大于minS，所以后面的len+x(x>=0)都会用到
                    add(dp0Acc, dp0[parts - 1][start]);
                    add(dp1Acc, dp1[parts - 1][start]);
                } else {
                    var common = min(lcp[start][minS.from], minS.len);
                    var changePos = common == minSLen ? start + common - 1
                                                      : start + common;
                    change.compute(changePos, (k, v) -> {
                        if (v == null) {
                            v = new ArrayList<>();
                        }
                        v.add(start);
                        return v;
                    });
                }
                var equalStarts = new ArrayList<Integer>();
                for (Integer startToChange : change.getOrDefault(start, List.of())) {
                    int compare = compare(startToChange, len - startToChange, minS.from, minS.len, lcp, s);
                    if (compare == 0) {
                        add(dp0Acc, dp0[parts - 1][startToChange], dp1[parts - 1][startToChange]);
                        equalStarts.add(startToChange);
                    } else if (compare > 0) {
                        add(dp0Acc, dp0[parts - 1][startToChange]);
                        add(dp1Acc, dp1[parts - 1][startToChange]);
                    }
                }
                dp0[parts][len] = translate(dp0Acc);
                dp1[parts][len] = translate(dp1Acc);
                for (Integer equalStart : equalStarts) {
                    // 相等只在当前len有用
                    minus(dp0Acc, dp0[parts - 1][equalStart], dp1[parts - 1][equalStart]);
                    // len+1就可能变大或者变小
                    change.compute(start + 1, (k, v) -> {
                        if (v == null) {
                            v = new ArrayList<>();
                        }
                        v.add(equalStart);
                        return v;
                    });
                }
            }
        }
        return new long[]{dp0[m][n], dp1[m][n]};
    }

    private static int min(int... a) {
        var ans = Integer.MAX_VALUE;
        for (int x : a) {
            ans = Math.min(ans, x);
        }
        return ans;
    }

    private static long translate(long[] acc) {
        return acc[0] > K_MAX || acc[1] > 0 ? K_MAX + 1 : acc[0];
    }

    private static void minus(long[] acc, long... a) {
        for (long x : a) {
            if (x > K_MAX) {
                acc[1]--;
            } else {
                acc[0] -= x;
            }
        }
    }

    static void add(long[] sum, long... a) {
        for (long x : a) {
            if (x > K_MAX) {
                sum[1]++;
            } else {
                sum[0] += x;
            }
        }
    }

    private static List<Sub> subs(int n, char[] s, int[][] lcp) {
        var t = System.nanoTime();
        var tmp = new ArrayList<Sub>();
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                tmp.add(new Sub(i, j, s, lcp));
            }
        }
//        System.out.println("sub collect: " + (System.nanoTime() - t) / 1e9);
        t = System.nanoTime();
        var ans = tmp.stream().distinct().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
//        System.out.println("sub distinct and sort: " + (System.nanoTime() - t) / 1e9);
        return ans;
    }

    static class Sub implements Comparable<Sub> {
        final int from;
        final int to;
        final int len;
        final char[] s;
        final int[][] lcp;
        int hash;

        Sub(int from, int to, char[] s, int[][] lcp) {
            this.from = from;
            this.to = to;
            this.s = s;
            this.lcp = lcp;
            len = to - from + 1;
        }

        @Override
        public int compareTo(Sub o) {
            return compare(from, len, o.from, o.len, lcp, s);
        }

        @Override
        public String toString() {
            return "Sub{" +
                    "from=" + from +
                    ", to=" + to +
                    ", len=" + len +
                    ", s=" + Arrays.toString(s) +
                    ", sub=" + new String(s, from, len) +
                    '}';
        }

        @Override
        public int hashCode() {
            int h = hash;
            if (h == 0 && len > 0) {
                for (int i = from; i <= to; i++) {
                    h = 31 * h + (s[i] & 0xff);
                }
                hash = h;
            }
            return h;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            } else if (this == obj) {
                return true;
            } else if (getClass() != obj.getClass()) {
                return false;
            }
            Sub o = (Sub) obj;
            if (len == o.len) {
                for (int i = 0; i < len; i++) {
                    if (s[from + i] != s[o.from + i]) {
                        return false;
                    }
                }
                return true;
            } else {
                return false;
            }
        }
    }

    private static int[][] lcp(int n, char[] s) {
        var ans = new int[n + 1][n + 1];
        for (int i = n - 1; i >= 0; i--) {
            for (int j = n - 1; j >= 0; j--) {
                if (s[i] == s[j]) {
                    ans[i][j] = ans[i + 1][j + 1] + 1;
                } else {
                    ans[i][j] = 0;
                }
            }
        }
        return ans;
    }

    public static class BufferedScanner {
        BufferedReader br;
        StringTokenizer st;

        public BufferedScanner(Reader reader) {
            br = new BufferedReader(reader);
        }

        public BufferedScanner() {
            this(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;
        }

        void close() {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    static long gcd(long a, long b) {
        if (a < b) {
            return gcd(b, a);
        }
        while (b > 0) {
            long tmp = b;
            b = a % b;
            a = tmp;
        }
        return a;
    }

    static long inverse(long a, long m) {
        long[] ans = extgcd(a, m);
        return ans[0] == 1 ? (ans[1] + m) % m : -1;
    }

    private static long[] extgcd(long a, long m) {
        if (m == 0) {
            return new long[]{a, 1, 0};
        } else {
            long[] ans = extgcd(m, a % m);
            long tmp = ans[1];
            ans[1] = ans[2];
            ans[2] = tmp;
            ans[2] -= ans[1] * (a / m);
            return ans;
        }
    }

    private static List<Integer> primes(double upperBound) {
        var limit = (int) Math.sqrt(upperBound);
        var isComposite = new boolean[limit + 1];
        var primes = new ArrayList<Integer>();
        for (int i = 2; i <= limit; i++) {
            if (isComposite[i]) {
                continue;
            }
            primes.add(i);
            int j = i + i;
            while (j <= limit) {
                isComposite[j] = true;
                j += i;
            }
        }
        return primes;
    }

}


B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png   When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4];  Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]);  Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4];  Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9
1 5
5 4
1 2
2 3
3 4
4 1
2 6
6 4
4 2
4
1 2 3 4
OutputCopy1 2
InputCopy7 7
1 2
2 3
3 4
4 5
5 6
6 7
7 1
7
1 2 3 4 5 6 7
OutputCopy0 0
InputCopy8 13
8 7
8 6
7 5
7 4
6 5
6 4
5 3
5 2
4 3
4 2
3 1
2 1
1 8
5
8 7 5 2 1
OutputCopy0 3

//some updates in import stuff

import static java.lang.Math.max;

import static java.lang.Math.min;

import static java.lang.Math.abs;

import java.util.*;

import java.io.*;

import java.math.*;

/*

    Always check before submitting list

    -> int to long conversion needed

    -> while loop mein break case shi ho

    -> extra kuch output na ho rha free fund mein

*/

//update this bad boi too

public class Main{

    static int mod = (int) (Math.pow(10, 9)+7);

	static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };

	static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 };

	static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };

	static final double eps = 1e-10;

	static Set<Integer> primeNumbers = new HashSet<>();

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

        MyScanner sc = new MyScanner();

        //changes in this line of code

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

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

        //Write Code Below

        int n = sc.nextInt();

        int m = sc.nextInt();

        Graph g = new Graph(n+1);

        Graph tg = new Graph(n+1);

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

            int from = sc.nextInt();

            int to = sc.nextInt();

            g.addEdge(from, to);

            tg.addEdge(to, from);

        }

        int k = sc.nextInt();

        int[] path = new int[k];

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

            path[i] = sc.nextInt();

        }

        //now solve using BFS and transposed graph baby!!! (sexy, think out of the box type of think)

        int[] dist = tg.giveDist(path[k-1]);

        Pair ans = g.minMaxPair(path[k-1],k,path, dist);

        out.println(ans.a + " " + ans.b);

        out.close();

    }

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

 //Updation Required

    //Fenwick Tree (customisable)

    //Segment Tree (customisable)

    //-----CURRENTLY PRESENT-------//

    //Graph

    //DSU

    //powerMODe

    //power

    //Segment Tree (work on this one)

    //Prime Sieve

    //Count Divisors

    //Next Permutation

    //Get NCR

    //isVowel

    //Sort (int)

    //Sort (long)

    //Binomial Coefficient

    //Pair

    //Triplet

    //lcm (int & long)

    //gcd (int & long)

    //gcd (for binomial coefficient)

    //swap (int & char)

    //reverse

    //SOME LATEST UPDATIONS!!!

    //mod_mul

    //mod_div

    //Fast input and output

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //-------------------------------------------------------------------

    //finding combinations in O(1) (basically the most basic logic you can think of)

    //not that complicated as i though it of

    //GRAPH (basic structure)

    public static class Graph{

        public int V;

        public ArrayList<ArrayList<Integer>> edges;

        //2 -> [0,1,2] (current)

        Graph(int V){

            this.V  = V;

            edges = new ArrayList<>(V+1);

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

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

            }

        }

        public void addEdge(int from , int to){

            edges.get(from).add(to);

        }

        public int[] giveDist(int fpoint){

            int[] visited = new int[V];

            int[] dist = new int[V];

            ArrayDeque<Integer> que = new ArrayDeque<>(); //transpose graph thingie is pretty cool (quality question baby)

            que.add(fpoint);

            dist[fpoint] = 0;

            while(!que.isEmpty()){

                int curr = que.poll();

                visited[curr] = 1;

                for(int edge : edges.get(curr)){

                    if(visited[edge] != 1){

                        que.add(edge);

                        visited[edge] = 1;

                        dist[edge] = dist[curr] + 1;

                    }

                }

            }

            // out.println(Arrays.toString(dist));

            return dist;

        }

        public Pair minMaxPair(int fpoint, int k, int[] path, int[] dist){

            int min = 0;

            int max = 0;

            //this function might not be working perfectly, let's think about it now

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

                int curr = path[i];

                int next = path[i+1];

                //now let's add in set

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

                for(int edge : edges.get(curr)){

                    if(dist[edge] == dist[curr]-1) set.add(edge);

                }

                // out.println(set);

                //this bad boi is pretty accurate for sure (now figure out something else)

                if(set.contains(next) && set.size() > 1){

                    max++;

                }else if(!set.contains(next)){

                    max++;

                    min++;

                }

            }

            return new Pair(min, max);

        }

    }

    //DSU (path and rank optimised)

    public static class DisjointUnionSets {

        int[] rank, parent;

        int n;

        public DisjointUnionSets(int n)

        {

            rank = new int[n];

            parent = new int[n];

            Arrays.fill(rank, 1);

            Arrays.fill(parent,-1);

            this.n = n;

        }

        public int find(int curr){

            if(parent[curr] == -1)

                return curr;

            //path compression optimisation

            return parent[curr] = find(parent[curr]);

        }

        public void union(int a, int b){

            int s1 = find(a);

            int s2 = find(b);

            if(s1 != s2){

                if(rank[s1] < rank[s2]){

                    parent[s1] = s2;

                    rank[s2] += rank[s1];

                }else{

                    parent[s2] = s1;

                    rank[s1] += rank[s2];

                }

            }

        }

    }

    //with mod

    public static long powerMOD(long x, long y)

    {

        long res = 1L;

        while (y > 0)

        {

            // If y is odd, multiply x with result

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

                x %= mod;

                res %= mod;

                res = (res * x)%mod;

            }

            // y must be even now

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

            x%= mod;

            x = (x * x)%mod;  // Change x to x^2

        }

        return res%mod;

    }

    //without mod

    public static long power(long x, long y)

    {

        long res = 1L;

        while (y > 0)

        {

            // If y is odd, multiply x with result

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

                res = (res * x);

            }

            // y must be even now

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

            x = (x * x);

        }

        return res;

    }

    public static class segmentTree{

        public long[] arr;

        public long[] tree;

        public long[] lazy;

        segmentTree(long[] array){

            int n = array.length;

            arr = new long[n];

            for(int i= 0; i < n; i++) arr[i] = array[i];

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

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

        }

        public  void build(int[]arr, int s, int e, int[] tree, int index){

            if(s == e){

                tree[index] = arr[s];

                return;

            }

            //otherwise divide in two parts and fill both sides simply

            int mid = (s+e)/2;

            build(arr, s, mid, tree, 2*index);

            build(arr, mid+1, e, tree, 2*index+1);

            //who will build the current position dude

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

        }

        public  int query(int sr, int er, int sc, int ec, int index, int[] tree){

            if(lazy[index] != 0){

                tree[index] += lazy[index];

                if(sc != ec){

                    lazy[2*index+1] += lazy[index];

                    lazy[2*index] += lazy[index];

                }

                lazy[index] = 0;

            }

            //no overlap

            if(sr > ec || sc > er) return Integer.MAX_VALUE;

            //found the index baby

            if(sr <= sc && ec <= er) return tree[index];

            //finding the index on both sides hehehehhe

            int mid = (sc + ec)/2;

            int left = query(sr, er, sc, mid, 2*index, tree);

            int right = query(sr, er, mid+1, ec, 2*index + 1, tree);

            return Integer.min(left, right);

        }

        //now we will do point update implementation

        //it should be simple then we expected for sure

        public  void update(int index, int indexr, int increment, int[] tree, int s, int e){

            if(lazy[index] != 0){

                tree[index] += lazy[index];

                if(s != e){

                    lazy[2*index+1] = lazy[index];

                    lazy[2*index] = lazy[index];

                }

                lazy[index] = 0;

            }

            //no overlap

            if(indexr < s || indexr > e) return;

            //found the required index

            if(s == e){

                tree[index] += increment;

                return;

            }

            //search for the index on both sides

            int mid = (s+e)/2;

            update(2*index, indexr, increment, tree, s, mid);

            update(2*index+1, indexr, increment, tree, mid+1, e);

            //now update the current range simply

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

        }

        public  void rangeUpdate(int[] tree , int index, int s, int e, int sr, int er, int increment){

            //if not at all in the same range

            if(e < sr || er < s) return;

            //complete then also move forward

            if(s == e){

                tree[index] += increment;

                return;

            }

            //otherwise move in both subparts

            int mid = (s+e)/2;

            rangeUpdate(tree, 2*index, s, mid, sr, er, increment);

            rangeUpdate(tree, 2*index + 1, mid+1, e, sr, er, increment);

            //update current range too na

            //i always forget this step for some reasons hehehe, idiot

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

        }

        public  void rangeUpdateLazy(int[] tree, int index, int s, int e, int sr, int er, int increment){

            //update lazy values

            //resolve lazy value before going down

            if(lazy[index] != 0){

                tree[index] += lazy[index];

                if(s != e){

                    lazy[2*index+1] += lazy[index];

                    lazy[2*index] += lazy[index];

                }

                lazy[index] = 0;

            }

            //no overlap case

            if(sr > e || s > er) return;

            //complete overlap

            if(sr <= s && er >= e){

                tree[index] += increment;

                if(s != e){

                    lazy[2*index+1] += increment;

                    lazy[2*index] += increment;

                }

                return;

            }

            //otherwise go on both left and right side and do your shit

            int mid = (s + e)/2;

            rangeUpdateLazy(tree, 2*index, s, mid, sr, er, increment);

            rangeUpdateLazy(tree, 2*index + 1, mid+1, e, sr, er, increment);

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

            return;

        }

    }

    //prime sieve

    public static void primeSieve(int n){

        BitSet bitset = new BitSet(n+1);

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

            if (i == 0 || i == 1) {

                bitset.set((int) i);

                continue;

            }

            if(bitset.get((int) i)) continue;

            primeNumbers.add((int)i);

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

                bitset.set((int)j);

        }

    }

    //number of divisors

    // public static int countDivisors(long number){

    //     if(number == 1) return 1;

    //     List<Integer> primeFactors = new ArrayList<>();

    //     int index = 0;

    //     long curr = primeNumbers.get(index);

    //     while(curr * curr <= number){

    //         while(number % curr == 0){

    //             number = number/curr;

    //             primeFactors.add((int) curr);

    //         }

    //         index++;

    //         curr = primeNumbers.get(index);

    //     }

    //     if(number != 1) primeFactors.add((int) number);

    //     int current = primeFactors.get(0);

    //     int totalDivisors = 1;

    //     int currentCount = 2;

    //     for (int i = 1; i < primeFactors.size(); i++) {

    //         if (primeFactors.get(i) == current) {

    //             currentCount++;

    //         } else {

    //             totalDivisors *= currentCount;

    //             currentCount = 2;

    //             current = primeFactors.get(i);

    //         }

    //     }

    //     totalDivisors *= currentCount;

    //     return totalDivisors;

    // }

    //now adding next permutation function to java hehe

    public static boolean next_permutation(int[] p) {

        for (int a = p.length - 2; a >= 0; --a)

          if (p[a] < p[a + 1])

            for (int b = p.length - 1;; --b)

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

                int t = p[a];

                p[a] = p[b];

                p[b] = t;

                for (++a, b = p.length - 1; a < b; ++a, --b) {

                  t = p[a];

                  p[a] = p[b];

                  p[b] = t;

                }

                return true;

              }

        return false;

    }

    //is vowel function

    public static boolean isVowel(char c)

    {

        return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' ||     c=='u' || c=='U');

    }

    //to sort the array with better method

	public static void sort(int[] a) {

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

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

		Collections.sort(l);

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

	}

    //sort long

    public static void sort(long[] a) {

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

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

		Collections.sort(l);

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

	}

    //for calculating binomialCoeff

    public static int binomialCoeff(int n, int k)

    {

        int C[] = new int[k + 1];

        // nC0 is 1

        C[0] = 1;

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

            // Compute next row of pascal

            // triangle using the previous row

            for (int j = Math.min(i, k); j > 0; j--)

                C[j] = C[j] + C[j - 1];

        }

        return C[k];

    }

    //Pair with int int

    public static class Pair{

        public int a;

        public int b;

        Pair(int a , int b){

            this.a = a;

            this.b = b;

        }

        @Override

        public String toString(){

            return a + " -> " + b;

        }

    }

    //Triplet with int int int

    public static class Triplet{

        public int a;

        public int b;

        public int c;

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

            this.a = a;

            this.b = b;

            this.c = c;

        }

        @Override

        public String toString(){

            return a + " -> " + b;

        }

    }

    //Shortcut function

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

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

    }

    //let's make one for calculating lcm basically

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

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

    }

    //int version for gcd

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

        if(b == 0)

            return a;

        return gcd(b , a%b);

    }

    //long version for gcd

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

        if(b == 0)

            return a;

        return gcd(b , a%b);

    }

     //for ncr calculator(ignore this code)

     public static long __gcd(long n1, long n2)

     {

         long gcd = 1;

         for (int i = 1; i <= n1 && i <= n2; ++i) {

             // Checks if i is factor of both integers

             if (n1 % i == 0 && n2 % i == 0) {

                 gcd = i;

             }

         }

         return gcd;

     }

    //swapping two elements in an array

    public static void swap(int[] arr, int left , int right){

        int temp = arr[left];

        arr[left] = arr[right];

        arr[right] = temp;

    }

    //for char array

    public static void swap(char[] arr, int left , int right){

        char temp = arr[left];

        arr[left] = arr[right];

        arr[right] = temp;

    }

    //reversing an array

    public static void reverse(int[] arr){

        int left = 0;

        int right = arr.length-1;

        while(left <= right){

            swap(arr, left,right);

            left++;

            right--;

        }

    }

    public static long expo(long a, long b, long mod) {

        long res = 1;

        while (b > 0) {

            if ((b & 1) == 1L) res = (res * a) % mod;  //think about this one for a second

            a = (a * a) % mod;

            b = b >> 1;

        }

        return res;

    }

    //SOME EXTRA DOPE FUNCTIONS

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

        return expo(a, b - 2, b);

    }

    public static long mod_add(long a, long b, long m) {

        a = a % m;

        b = b % m;

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

    }

    public static long mod_sub(long a, long b, long m) {

        a = a % m;

        b = b % m;

        return (((a - b) % m) + m) % m;

    }

    public static long mod_mul(long a, long b, long m) {

        a = a % m;

        b = b % m;

        return (((a * b) % m) + m) % m;

    }

    public static long mod_div(long a, long b, long m) {

        a = a % m;

        b = b % m;

        return (mod_mul(a, mminvprime(b, m), m) + m) % m;

    }

    //O(n) every single time remember that

    public static long nCr(long N, long K , long mod){

        long upper = 1L;

        long lower = 1L;

        long lowerr = 1L;

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

            upper = mod_mul(upper, i, mod);

        }

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

            lower = mod_mul(lower, i, mod);

        }

        for(long i = 1; i <= (N - K); i++){

            lowerr = mod_mul(lowerr, i, mod);

        }

        // out.println(upper + " " + lower + " " + lowerr);

        long answer = mod_mul(lower, lowerr, mod);

        answer = mod_div(upper, answer, mod);

        return answer;

    }

    // ll *fact = new ll[2 * n + 1];

	// ll *ifact = new ll[2 * n + 1];

	// fact[0] = 1;

	// ifact[0] = 1;

	// for (ll i = 1; i <= 2 * n; i++)

	// {

	// 	fact[i] = mod_mul(fact[i - 1], i, MOD1);

	// 	ifact[i] = mminvprime(fact[i], MOD1);

	// }

    //ifact is basically inverse factorial in here!!!!!(imp)

    public static long combination(long n, long r, long m, long[] fact, long[] ifact) {

        long val1 = fact[(int)n];

        long val2 = ifact[(int)(n - r)];

        long val3 = ifact[(int)r];

        return (((val1 * val2) % m) * val3) % m;

    }

    //-----------PrintWriter for faster output---------------------------------

    public static PrintWriter out;

    //-----------MyScanner class for faster input----------

    public static class MyScanner {

      BufferedReader br;

      StringTokenizer st;

        public MyScanner() {

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

        }

        // public MyScanner() throws FileNotFoundException {

        //     br = new BufferedReader(new FileReader("input.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;

        }

    }

   //--------------------------------------------------------

}


A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. Next 2t2t lines contain a description of test cases  — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100)  — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3
4 5
1 0 3 2
2 2
100 1
1 8
0
OutputCopy3
101
0
NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11:   On day one, move a haybale from pile 33 to pile 22  On day two, move a haybale from pile 33 to pile 22  On day three, move a haybale from pile 22 to pile 11  On day four, move a haybale from pile 22 to pile 11  On day five, do nothing  In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author lucasr
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		MyScanner in = new MyScanner(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		ACowAndHaybales solver = new ACowAndHaybales();
		int testCount = Integer.parseInt(in.next());
		for (int i = 1; i <= testCount; i++)
			solver.solve(i, in, out);
		out.close();
	}

	static class ACowAndHaybales {
		public static MyScanner sc;
		public static PrintWriter out;

		public void solve(int testNumber, MyScanner sc, PrintWriter out) {
			ACowAndHaybales.sc = sc;
			ACowAndHaybales.out = out;
			int n = sc.nextInt();
			int d = sc.nextInt();
			int[] piles = sc.nextIntArray(n);
			while (d > 0) {
				boolean found = false;
				for (int j = 1; j < n; j++) {
					if (piles[j] > 0 && j <= d) {
						piles[j]--;
						piles[0]++;
						d -= j;
						found = true;
						break;
					}
				}
				if (!found) break;
			}
			out.println(piles[0]);
		}

	}

	static class MyScanner {
		private BufferedReader br;
		private StringTokenizer tokenizer;

		public MyScanner(InputStream is) {
			br = new BufferedReader(new InputStreamReader(is));
		}

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

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

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

	}
}


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

import java.io.*;

import java.util.*;

public class Sol{

	public static List<Integer> adj[];

	public static int query[][];

	public static int get[][] = new int[5000][5000];

	public static int edge[];

	public static int par[];

	public static int depth[];

	public static int n, m, D;

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

		FastIO sc = new FastIO(System.in);

		PrintWriter out = new PrintWriter(System.out);

		boolean poss = true;

		n = sc.nextInt();

		par = new int[n];

		depth = new int[n];

		edge = new int[n-1];

		adj = new ArrayList[n];

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

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

		}

		int idx = 0;

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

			int a = sc.nextInt()-1;

			int b = sc.nextInt()-1;

			adj[a].add(b);

			adj[b].add(a);

			get[a][b] = idx;

			get[b][a] = idx;

			idx++;

			edge[i] = -1;

		}

		depth[0] = 0;

		par[0] = 0;

		DFS(0, 0);

		int m = sc.nextInt();

		query = new int[m][3];

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

			query[i][0] =sc.nextInt()-1;

			query[i][1] = sc.nextInt()-1;

			query[i][2] = sc.nextInt();

		}

		ColumnSort(query, 2);

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

			boolean change = false;

			int num = query[i][2];

			int curr1 = query[i][0];

			int curr2 = query[i][1];

			while(curr1!=curr2) {

				if(depth[curr1]>depth[curr2]) {

					idx = get[curr1][par[curr1]];

					if(edge[idx]==-1||edge[idx]==num) {

						edge[idx] = num;

						change = true;

					}

					curr1 = par[curr1];

				}else {

					idx = get[curr2][par[curr2]];

					if(edge[idx]==-1||edge[idx]==num) {

						edge[idx] = num;

						change = true;

					}

					curr2 = par[curr2];

				}

			}

			if(!change) poss = false;

		}

		if(!poss) {

			out.println(-1);

		}else {

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

				out.print(Math.max(edge[i], 1) + " ");

			}

			out.println();

		}

		out.close();

	}

	public static void DFS(int curr, int p) {

		for(int i: adj[curr]) {

			if(i==p) continue;

			par[i] = curr;

			depth[i] = depth[curr]+1;

			DFS(i, curr);

		}

	}

    public static void ColumnSort(int arr[][], int col) {

        Arrays.sort(arr, new Comparator<int[]>() {

            @Override

          public int compare(int[] entry1,

                             int[] entry2) {

            	Integer a = entry1[col];

            	Integer b = entry2[col];

            	return a.compareTo(b);

          }

        });

    }

	static class FastIO {

		// Is your Fast I/O being bad?

		InputStream dis;

		byte[] buffer = new byte[1 << 17];

		int pointer = 0;

		public FastIO(String fileName) throws IOException {

			dis = new FileInputStream(fileName);

		}

		public FastIO(InputStream is) throws IOException {

			dis = is;

		}

		int nextInt() throws IOException {

			int ret = 0;

			byte b;

			do {

				b = nextByte();

			} while (b <= ' ');

			boolean negative = false;

			if (b == '-') {

				negative = true;

				b = nextByte();

			}

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

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

				b = nextByte();

			}

			return (negative) ? -ret : ret;

		}

		long nextLong() throws IOException {

			long ret = 0;

			byte b;

			do {

				b = nextByte();

			} while (b <= ' ');

			boolean negative = false;

			if (b == '-') {

				negative = true;

				b = nextByte();

			}

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

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

				b = nextByte();

			}

			return (negative) ? -ret : ret;

		}

		byte nextByte() throws IOException {

			if (pointer == buffer.length) {

				dis.read(buffer, 0, buffer.length);

				pointer = 0;

			}

			return buffer[pointer++];

		}

		String next() throws IOException {

			StringBuffer ret = new StringBuffer();

			byte b;

			do {

				b = nextByte();

			} while (b <= ' ');

			while (b > ' ') {

				ret.appendCodePoint(b);

				b = nextByte();

			}

			return ret.toString();

		}

	}

}


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

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.io.PrintStream;

import java.util.Arrays;

import java.util.InputMismatchException;

import java.util.Objects;

/**

 * Built using CHelper plug-in

 * Actual solution is at the top

 */

public class Main {

	static class TaskAdapter implements Runnable {

		@Override

		public void run() {

			InputStream inputStream = System.in;

			OutputStream outputStream = System.out;

			FastReader in = new FastReader(inputStream);

			Output out = new Output(outputStream);

			DNashMatrix solver = new DNashMatrix();

			solver.solve(1, in, out);

			out.close();

		}

	}

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

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

		thread.start();

		thread.join();

	}

	static class DNashMatrix {

		private final int[] ry = new int[] {0, 1, 0, -1};

		private final int[] rx = new int[] {-1, 0, 1, 0};

		private final char[] dir = new char[] {'U', 'R', 'D', 'L'};

		private final char[] rdir = new char[] {'D', 'L', 'U', 'R'};

		Pair<Integer, Integer>[][] arr;

		Pair<Integer, Integer> p;

		char[][] ans;

		int n;

		public DNashMatrix() {

		}

		public void dfs(int x, int y) {

			Utilities.Debug.dbg(x, y);

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

				int cx = x+rx[i], cy = y+ry[i];

				if(inBounds(cx, cy)&&arr[cx][cy].equals(p)&&ans[cx][cy]==0) {

					ans[cx][cy] = rdir[i];

					dfs(cx, cy);

				}

			}

		}

		public boolean inBounds(int x, int y) {

			return x>=0&&y>=0&&x<n&&y<n;

		}

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

			n = in.nextInt();

			arr = new Pair[n][n];

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

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

					arr[i][j] = new Pair<>(Math.max(in.nextInt()-1, -1), Math.max(in.nextInt()-1, -1));

				}

			}

			ans = new char[n][n];

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

				loop:

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

					if(ans[i][j]!=0) {

						continue;

					}

					var v = arr[i][j];

					if(v.a==-1) {

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

							int cx = i+rx[k], cy = j+ry[k];

							if(inBounds(cx, cy)&&arr[cx][cy].equals(v)) {

								ans[i][j] = dir[k];

								p = new Pair<>(v);

								dfs(i, j);

								continue loop;

							}

						}

						pw.println("INVALID");

						return;

					}else if(v.a==i&&v.b==j) {

						ans[i][j] = 'X';

						p = new Pair<>(i, j);

						dfs(i, j);

					}

				}

			}

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

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

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

						pw.println("INVALID");

						return;

					}

				}

			}

			pw.println("VALID");

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

				pw.println(ans[i]);

			}

		}

	}

	static class Utilities {

		public static class Debug {

			public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null;

			private static <T> String ts(T t) {

				if(t==null) {

					return "null";

				}

				try {

					return ts((Iterable) t);

				}catch(ClassCastException e) {

					if(t instanceof int[]) {

						String s = Arrays.toString((int[]) t);

						return "{"+s.substring(1, s.length()-1)+"}";

					}else if(t instanceof long[]) {

						String s = Arrays.toString((long[]) t);

						return "{"+s.substring(1, s.length()-1)+"}";

					}else if(t instanceof char[]) {

						String s = Arrays.toString((char[]) t);

						return "{"+s.substring(1, s.length()-1)+"}";

					}else if(t instanceof double[]) {

						String s = Arrays.toString((double[]) t);

						return "{"+s.substring(1, s.length()-1)+"}";

					}else if(t instanceof boolean[]) {

						String s = Arrays.toString((boolean[]) t);

						return "{"+s.substring(1, s.length()-1)+"}";

					}

					try {

						return ts((Object[]) t);

					}catch(ClassCastException e1) {

						return t.toString();

					}

				}

			}

			private static <T> String ts(T[] arr) {

				StringBuilder ret = new StringBuilder();

				ret.append("{");

				boolean first = true;

				for(T t: arr) {

					if(!first) {

						ret.append(", ");

					}

					first = false;

					ret.append(ts(t));

				}

				ret.append("}");

				return ret.toString();

			}

			private static <T> String ts(Iterable<T> iter) {

				StringBuilder ret = new StringBuilder();

				ret.append("{");

				boolean first = true;

				for(T t: iter) {

					if(!first) {

						ret.append(", ");

					}

					first = false;

					ret.append(ts(t));

				}

				ret.append("}");

				return ret.toString();

			}

			public static void dbg(Object... o) {

				if(LOCAL) {

					System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": [");

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

						if(i!=0) {

							System.err.print(", ");

						}

						System.err.print(ts(o[i]));

					}

					System.err.println("]");

				}

			}

		}

	}

	static interface InputReader {

		int nextInt();

	}

	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 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(char[] c) {

			println(String.valueOf(c));

		}

		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 Pair<T1, T2> implements Comparable<Pair<T1, T2>> {

		public T1 a;

		public T2 b;

		public Pair(Pair<T1, T2> p) {

			this(p.a, p.b);

		}

		public Pair(T1 a, T2 b) {

			this.a = a;

			this.b = b;

		}

		public String toString() {

			return a+" "+b;

		}

		public int hashCode() {

			return Objects.hash(a, b);

		}

		public boolean equals(Object o) {

			if(o instanceof Pair) {

				Pair p = (Pair) o;

				return a.equals(p.a)&&b.equals(p.b);

			}

			return false;

		}

		public int compareTo(Pair<T1, T2> p) {

			int cmp = ((Comparable<T1>) a).compareTo(p.a);

			if(cmp==0) {

				return ((Comparable<T2>) b).compareTo(p.b);

			}

			return cmp;

		}

	}

}


D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that:  each array contains nn elements;  each element is an integer from 11 to mm;  for each array, there is exactly one pair of equal elements;  for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4
OutputCopy6
InputCopy3 5
OutputCopy10
InputCopy42 1337
OutputCopy806066790
InputCopy100000 200000
OutputCopy707899035
NoteThe arrays in the first example are:  [1,2,1][1,2,1];  [1,3,1][1,3,1];  [1,4,1][1,4,1];  [2,3,2][2,3,2];  [2,4,2][2,4,2];  [3,4,3][3,4,3].

import java.io.IOException;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.util.StringTokenizer;

public class Solution {

    static final Reader input = new Reader();

    static final int MOD = 998244353;

    static int n, m;

    static long[] fac;

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

        n = input.nextInt();

        m = input.nextInt();

        if(n == 2) {

            System.out.println(0);

            return;

        }

        fac = new long[m+1];

        fac[0] = 1;

        fac[1] = 1;

        for(int i = 2; i < fac.length; ++i) fac[i] = (i*fac[i-1]) % MOD;

        long common = 0;

        for(int x = n-2; x < m; ++x) {

            common += (((fac[x-1] * inverse(fac[x-1 - (n-3)])) % MOD) * x ) % MOD;

            if(common >= MOD) common -= MOD;

        }

        long answer = 0;

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

            answer += (common * inverse((fac[i-1]*fac[(n-1)-i-1]) % MOD)) % MOD;

            if(answer >= MOD) answer -= MOD;

        }

        System.out.println(answer);

    }

    static long inverse(long a) {

        return power(a, MOD-2);

    }

    static long power(long a, long b) {

        long result = 1;

        while(b > 0) {

            if(b % 2 == 1) result = (result*a)%MOD;

            a = (a*a) % MOD;

            b /= 2;

        }

        return result;

    }

    static class Reader {

        BufferedReader reader;

        StringTokenizer string;

        public Reader() {

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

        }

        public String next() throws IOException {

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

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

            }

            return string.nextToken();

        }

        public int nextInt() throws IOException {

            return Integer.parseInt(next());

        }

        public long nextLong() throws IOException {

            return Long.parseLong(next());

        }

    }

}


A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5
0 5 0 2 3
OutputCopy2
InputCopy7
1 0 0 5 0 0 2
OutputCopy1
NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2.

import java.io.*;

import java.util.Scanner;

import java.util.*;

public class Solution {

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

    static Kattio io = new Kattio();

    static int h = (int) 1e5 * 2 + 2;

    public static void main(String[] args) {

        int n = io.nextInt();

        int[] arr = new int[n];

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

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

            arr[i] = io.nextInt();

            vis[arr[i]] = true;

        }

        new Solution().solve(n, vis, arr);

        io.close();

    }

    public void solve(int n, boolean[] vis, int[] arr) {

        int odd = 0;

        int even = 0;

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

            if (!vis[i]) {

                if (i % 2 == 0) even++;

                else odd++;

            }

        }

        int cur = 0;

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

            if (arr[i] == 0 || arr[i - 1] == 0) continue;

            if((arr[i] + arr[i - 1]) % 2 == 1) cur++;

        }

        List<int[]> blocks = new ArrayList();

        int cnt = 0;

        int l = -1;

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

            if (arr[i] == 0) {

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

                    l = arr[i - 1] % 2;

                }

                cnt++;

            } else {

                if (cnt == 0) continue;

                blocks.add(new int[]{cnt, l, arr[i] % 2});

                cnt = 0;

            }

        }

        if (cnt > 0) {

            blocks.add(new int[]{cnt, l, -1});

        }

        List<int[]> same = new ArrayList();

        List<int[]> edge = new ArrayList();

        for (int[] block : blocks) {

            if (block[1] == -1 || block[2] == -1) {

                int x = -1;

                if (block[1] != -1) x = block[1];

                else x = block[2];

                edge.add(new int[]{block[0], x});

            } else if ((block[1] + block[2]) % 2 == 0) {

                same.add(new int[]{block[0], block[1]});

            }

        }

        int ans = blocks.size() - edge.size() - same.size();

        same.sort((a, b) -> a[0] - b[0]);

        for (int[] f : same) {

            if (f[1] == 1) {

                if (odd >= f[0]) odd -= f[0];

                else ans += 2;

            } else {

                if (even >= f[0]) even -= f[0];

                else ans += 2;

            }

        }

        for (int[] f : edge) {

            if (f[1] == -1) {

                if (n != 1) ans++;

            } else if (f[1] == 1) {

                if (odd >= f[0]) {

                    odd -= f[0];

                } else ans++;

            } else {

                if (even >= f[0]) {

                    even -= f[0];

                } else ans++;

            }

        }

        io.println(ans + cur);

    }

    public int gcd(int a, int b) {

        if (b == 0) return a;

        return gcd(b, a % b);

    }

    public int countbit(long n) {

        int count = 0;

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

            if (((1L << i) & n) != 0) count++;

        }

        return count;

    }

    public int firstbit(int n) {

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

            if (((1 << i) & n) != 0) return i;

        }

        return -1;

    }

}

class Kattio extends PrintWriter {

    private BufferedReader r;

    private StringTokenizer st;

    // 标准 IO

    public Kattio() { this(System.in, System.out); }

    public Kattio(InputStream i, OutputStream o) {

        super(o);

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

    }

    // 文件 IO

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

        super(output);

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

    }

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

    public String next() {

        try {

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

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

            return st.nextToken();

        } catch (Exception e) {}

        return null;

    }

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

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

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

}


A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat.  You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12
sin im gye gap eul byeong jeong mu gi gyeong
yu sul hae ja chuk in myo jin sa o mi sin
14
1
2
3
4
10
11
12
13
73
2016
2017
2018
2019
2020
OutputCopysinyu
imsul
gyehae
gapja
gyeongo
sinmi
imsin
gyeyu
gyeyu
byeongsin
jeongyu
musul
gihae
gyeongja
NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.

import java.util.Scanner;

/**

 *

 * @author eslam

 */

public class NewYearAndNaming {

    /**

     * @param args the command line arguments

     */

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        int n = input.nextInt();

        int m = input.nextInt();

        String sn[] =new String[n];

        String sm[] =new String[m];

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

            sn[i] = input.next();

        }

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

            sm[i] = input.next();

        }

        int q = input.nextInt();

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

            int x = input.nextInt();

            String w = "";

            if(x%n==0){

                w = w+sn[n-1];

            }else{

                w = w +sn[(x%n)-1];

            }

            if(x%m==0){

                w = w+sm[m-1];

            }else{

                w = w +sm[(x%m)-1];

            }

            System.out.println(w);

        }

    }

}


E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times:  Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair).  Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5
4 3 2 2 3
OutputCopy2
InputCopy7
3 3 4 4 4 3 3
OutputCopy2
InputCopy3
1 3 5
OutputCopy3
InputCopy1
1000
OutputCopy1
NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all.

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.ArrayDeque;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.Deque;

import java.util.HashMap;

import java.util.HashSet;

import java.util.List;

import java.util.Map;

import java.util.PriorityQueue;

import java.util.Queue;

import java.util.Set;

import java.util.Stack;

import java.util.StringTokenizer;

import java.util.function.BiFunction;

import java.util.function.Function;

public class Main {

  int a[];

  int n;

  int ddp[][];

  int getValue(int l, int r) {

    if(ddp[l][r] != 0) {

      return ddp[l][r];

    }

    if(l==r) {

      return a[l];

    }

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

      int x1 = getValue(l, i);

      int x2 = getValue(i+1, r);

      if(x1 == x2 && x1 != -1) {

        ddp[l][r] = x1 +1;

        return x1 + 1;

      }

    }

    ddp[l][r] = -1;

    return -1;

  }

  void solve() {

    n = in.nextInt();

    ddp = new int[n][n];

    a = new int[n];

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

      a[i] = in.nextInt();

    }

    int dp[] = new int[n];

    dp[0] = 1;

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

      dp[i] = Integer.MAX_VALUE;

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

        int x = getValue(l, i);

        if(x == -1) {

          continue;

        }

        x = 1;

        if (l > 0) {

          x += dp[l-1];

        }

        dp[i] = Integer.min(dp[i], x);

      }

    }

    out(dp[n-1]);

  }

    public static void main(String[] args)

    {

      new Main().solve();//.multiple();

    }

    final static  FastReader in = new FastReader();

    private void multiple() {

      int t = in.nextInt();

      for(; t >0; t--) {

        solve();

      }

    }

    private <T> void out(T s) {

      System.out.println(s);

    }

    static class FastReader {

        BufferedReader br;

        StringTokenizer st;

        public FastReader()

        {

            br = new BufferedReader(

                new InputStreamReader(System.in));

        }

        String next()

        {

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

                try {

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

                }

                catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

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

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

        double nextDouble()

        {

            return Double.parseDouble(next());

        }

        String nextLine()

        {

            String str = "";

            try {

                str = br.readLine();

            }

            catch (IOException e) {

                e.printStackTrace();

            }

            return str;

        }

    }

}


D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns.   You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster.  Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3
7 10 50 12 1 8
OutputCopy5
InputCopy1 1 100 99
100
OutputCopy1
InputCopy7 4 2 1
1 3 5 4 2 7 6
OutputCopy6

import java.io.*;

import java.util.*;

public class ProblemD {

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

		Scanner s= new Scanner();

		int n = s.readInt();

		int a = s.readInt();

		int b = s.readInt();

		int k = s.readInt();

		int arr[] = new int[n];

		int p = a+b,ans = 0;

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

			arr[i] = s.readInt();

			if(arr[i]%p == 0){

				arr[i] = b;

				arr[i]+=a;

			}else arr[i]%=p;

		}

		sort(arr);

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

			if(arr[i]>0){

				arr[i]-=a;

				if(arr[i]>0 && k>=(arr[i]+a-1)/a){

					k-=((arr[i]+a-1)/a);

					arr[i] = 0;

				}

			}

			if(arr[i]<=0)ans++;

		}

		System.out.println(ans);

	}

	public static void sort(int arr[]){

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

		for(int it:arr)list.add(it);

		Collections.sort(list);

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

	}

	static class Pair{

		int x,y;

		public Pair(int x,int y){

			this.x = x;

			this.y = y;

		}

	}

	static class Scanner{

		BufferedReader br;

		StringTokenizer st;

		public Scanner(){

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

		}

	    public String read()

	    {

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

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

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

	         }

	         return st.nextToken();

	     }

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

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

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

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

	}

}


import java.util.*;

public class Main {

    public static void main(String[] args) {

Scanner s=new Scanner(System.in);

int n=s.nextInt();

int m=s.nextInt();

s.nextLine();

String s1=s.nextLine();

String[] str=s1.split(" ");

String s2=s.nextLine();

String[] str1=s2.split(" ");

int q=s.nextInt();

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

{

    int x=s.nextInt();

    x--;

    System.out.println(str[x%n]+str1[x%m]);

}

    }

}


E. New Year and Castle Constructiontime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputKiwon's favorite video game is now holding a new year event to motivate the users! The game is about building and defending a castle; which led Kiwon to think about the following puzzle.In a 2-dimension plane, you have a set s={(x1,y1),(x2,y2),…,(xn,yn)}s={(x1,y1),(x2,y2),…,(xn,yn)} consisting of nn distinct points. In the set ss, no three distinct points lie on a single line. For a point p∈sp∈s, we can protect this point by building a castle. A castle is a simple quadrilateral (polygon with 44 vertices) that strictly encloses the point pp (i.e. the point pp is strictly inside a quadrilateral). Kiwon is interested in the number of 44-point subsets of ss that can be used to build a castle protecting pp. Note that, if a single subset can be connected in more than one way to enclose a point, it is counted only once. Let f(p)f(p) be the number of 44-point subsets that can enclose the point pp. Please compute the sum of f(p)f(p) for all points p∈sp∈s.InputThe first line contains a single integer nn (5≤n≤25005≤n≤2500).In the next nn lines, two integers xixi and yiyi (−109≤xi,yi≤109−109≤xi,yi≤109) denoting the position of points are given.It is guaranteed that all points are distinct, and there are no three collinear points.OutputPrint the sum of f(p)f(p) for all points p∈sp∈s.ExamplesInputCopy5
-1 0
1 0
-10 -1
10 -1
0 3
OutputCopy2InputCopy8
0 1
1 2
2 2
1 3
0 -1
-1 -2
-2 -2
-1 -3
OutputCopy40InputCopy10
588634631 265299215
-257682751 342279997
527377039 82412729
145077145 702473706
276067232 912883502
822614418 -514698233
280281434 -41461635
65985059 -827653144
188538640 592896147
-857422304 -529223472
OutputCopy213

import java.io.OutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.BufferedOutputStream;

import java.io.UncheckedIOException;

import java.util.Objects;

import java.nio.charset.Charset;

import java.util.StringTokenizer;

import java.io.Writer;

import java.io.OutputStreamWriter;

import java.io.BufferedReader;

import java.util.Comparator;

import java.io.InputStream;

/**

 * Built using CHelper plug-in

 * Actual solution is at the top

 *

 * @author mikit

 */

public class Main {

    public static void main(String[] args) {

        InputStream inputStream = System.in;

        OutputStream outputStream = System.out;

        LightScanner in = new LightScanner(inputStream);

        LightWriter out = new LightWriter(outputStream);

        ENewYearAndCastleConstruction solver = new ENewYearAndCastleConstruction();

        solver.solve(1, in, out);

        out.close();

    }

    static class ENewYearAndCastleConstruction {

        public void solve(int testNumber, LightScanner in, LightWriter out) {

            int n = in.ints();

            Vec2l[] points = new Vec2l[n];

            for (int i = 0; i < n; i++) points[i] = new Vec2l(in.longs(), in.longs());

            long ans = n * (n - 1L) * (n - 2L) * (n - 3L) * (n - 4L) / 24;

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

                int m = 0;

                Vec2l[] angles = new Vec2l[n - 1];

                {

                    Vec2l now = points[t];

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

                        if (i != t) {

                            angles[m] = new Vec2l(points[i].x - now.x, points[i].y - now.y);

                            m++;

                        }

                    }

                    IntroSort.sort(angles, Vec2l::compareToByAngle);

                }

                //System.out.println(Arrays.stream(angles).map(angle -> Double.toString(Math.atan2(angle.y, angle.x))).collect(Collectors.joining(", ")));

                int hi = 0;

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

                    while (hi < j + m && (hi <= j || angles[j].det(angles[hi % m]) > 0)) {

                        hi++;

                    }

                    int cnt = hi - j;

                    ans -= (cnt - 1L) * (cnt - 2L) * (cnt - 3L) / 6;

                }

            }

            out.ans(ans).ln();

        }

    }

    static class InsertionSort {

        private InsertionSort() {

        }

        static <T> void sort(T[] a, int low, int high, Comparator<? super T> comparator) {

            for (int i = low; i < high; i++) {

                for (int j = i; j > low && comparator.compare(a[j - 1], a[j]) > 0; j--) {

                    ArrayUtil.swap(a, j - 1, j);

                }

            }

        }

    }

    static class QuickSort {

        private QuickSort() {

        }

        private static <T> void med(T[] a, int low, int x, int y, int z, Comparator<? super T> comparator) {

            if (comparator.compare(a[z], a[x]) < 0) {

                ArrayUtil.swap(a, low, x);

            } else if (comparator.compare(a[y], a[z]) < 0) {

                ArrayUtil.swap(a, low, y);

            } else {

                ArrayUtil.swap(a, low, z);

            }

        }

        static <T> int step(T[] a, int low, int high, Comparator<? super T> comparator) {

            int x = low + 1, y = low + (high - low) / 2, z = high - 1;

            if (comparator.compare(a[x], a[y]) < 0) {

                med(a, low, x, y, z, comparator);

            } else {

                med(a, low, y, x, z, comparator);

            }

            int lb = low + 1, ub = high;

            while (true) {

                while (comparator.compare(a[lb], a[low]) < 0) {

                    lb++;

                }

                ub--;

                while (comparator.compare(a[low], a[ub]) < 0) {

                    ub--;

                }

                if (lb >= ub) {

                    return lb;

                }

                ArrayUtil.swap(a, lb, ub);

                lb++;

            }

        }

    }

    static interface Verified {

    }

    static final class ArrayUtil {

        private ArrayUtil() {

        }

        public static <T> void swap(T[] a, int x, int y) {

            T t = a[x];

            a[x] = a[y];

            a[y] = t;

        }

    }

    static final class BitMath {

        private BitMath() {

        }

        public static int count(int v) {

            v = (v & 0x55555555) + ((v >> 1) & 0x55555555);

            v = (v & 0x33333333) + ((v >> 2) & 0x33333333);

            v = (v & 0x0f0f0f0f) + ((v >> 4) & 0x0f0f0f0f);

            v = (v & 0x00ff00ff) + ((v >> 8) & 0x00ff00ff);

            v = (v & 0x0000ffff) + ((v >> 16) & 0x0000ffff);

            return v;

        }

        public static int msb(int v) {

            if (v == 0) {

                throw new IllegalArgumentException("Bit not found");

            }

            v |= (v >> 1);

            v |= (v >> 2);

            v |= (v >> 4);

            v |= (v >> 8);

            v |= (v >> 16);

            return count(v) - 1;

        }

    }

    static class HeapSort {

        private HeapSort() {

        }

        private static <T> void heapfy(T[] a, int low, int high, int i, T val, Comparator<? super T> comparator) {

            int child = 2 * i - low + 1;

            while (child < high) {

                if (child + 1 < high && comparator.compare(a[child], a[child + 1]) < 0) {

                    child++;

                }

                if (comparator.compare(val, a[child]) >= 0) {

                    break;

                }

                a[i] = a[child];

                i = child;

                child = 2 * i - low + 1;

            }

            a[i] = val;

        }

        static <T> void sort(T[] a, int low, int high, Comparator<T> comparator) {

            for (int p = (high + low) / 2 - 1; p >= low; p--) {

                heapfy(a, low, high, p, a[p], comparator);

            }

            while (high > low) {

                high--;

                T pval = a[high];

                a[high] = a[low];

                heapfy(a, low, high, low, pval, comparator);

            }

        }

    }

    static class LightWriter implements AutoCloseable {

        private final Writer out;

        private boolean autoflush = false;

        private boolean breaked = true;

        public LightWriter(Writer out) {

            this.out = out;

        }

        public LightWriter(OutputStream out) {

            this(new OutputStreamWriter(new BufferedOutputStream(out), Charset.defaultCharset()));

        }

        public LightWriter print(char c) {

            try {

                out.write(c);

                breaked = false;

            } catch (IOException ex) {

                throw new UncheckedIOException(ex);

            }

            return this;

        }

        public LightWriter print(String s) {

            try {

                out.write(s, 0, s.length());

                breaked = false;

            } catch (IOException ex) {

                throw new UncheckedIOException(ex);

            }

            return this;

        }

        public LightWriter ans(String s) {

            if (!breaked) {

                print(' ');

            }

            return print(s);

        }

        public LightWriter ans(long l) {

            return ans(Long.toString(l));

        }

        public LightWriter ln() {

            print(System.lineSeparator());

            breaked = true;

            if (autoflush) {

                try {

                    out.flush();

                } catch (IOException ex) {

                    throw new UncheckedIOException(ex);

                }

            }

            return this;

        }

        public void close() {

            try {

                out.close();

            } catch (IOException ex) {

                throw new UncheckedIOException(ex);

            }

        }

    }

    static class LightScanner {

        private BufferedReader reader = null;

        private StringTokenizer tokenizer = null;

        public LightScanner(InputStream in) {

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

        }

        public String string() {

            if (tokenizer == null || !tokenizer.hasMoreTokens()) {

                try {

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

                } catch (IOException e) {

                    throw new UncheckedIOException(e);

                }

            }

            return tokenizer.nextToken();

        }

        public int ints() {

            return Integer.parseInt(string());

        }

        public long longs() {

            return Long.parseLong(string());

        }

    }

    static class Vec2l implements Comparable<Vec2l> {

        public long x;

        public long y;

        public Vec2l(long x, long y) {

            this.x = x;

            this.y = y;

        }

        public long det(Vec2l other) {

            return x * other.y - other.x * y;

        }

        public boolean equals(Object o) {

            if (this == o) return true;

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

            Vec2l vec2i = (Vec2l) o;

            return x == vec2i.x &&

                    y == vec2i.y;

        }

        public int hashCode() {

            return Objects.hash(x, y);

        }

        public String toString() {

            return "(" + x + ", " + y + ")";

        }

        public int compareTo(Vec2l o) {

            if (x == o.x) {

                return Long.compare(y, o.y);

            }

            return Long.compare(x, o.x);

        }

        public int compareToByAngle(Vec2l o) {

            if ((y >= 0) != (o.y >= 0)) {

                return y >= 0 ? 1 : -1;

            } else if ((x >= 0) != (o.x >= 0)) {

                if (y >= 0) return x >= 0 ? -1 : 1;

                else return x >= 0 ? 1 : -1;

            } else {

                return Long.compare(0, x * o.y - o.x * y);

            }

        }

    }

    static class IntroSort {

        private static int INSERTIONSORT_THRESHOLD = 16;

        private IntroSort() {

        }

        static <T> void sort(T[] a, int low, int high, int maxDepth, Comparator<T> comparator) {

            while (high - low > INSERTIONSORT_THRESHOLD) {

                if (maxDepth-- == 0) {

                    HeapSort.sort(a, low, high, comparator);

                    return;

                }

                int cut = QuickSort.step(a, low, high, comparator);

                sort(a, cut, high, maxDepth, comparator);

                high = cut;

            }

            InsertionSort.sort(a, low, high, comparator);

        }

        public static <T> void sort(T[] a, Comparator<T> comparator) {

            if (a.length <= INSERTIONSORT_THRESHOLD) {

                InsertionSort.sort(a, 0, a.length, comparator);

            } else {

                sort(a, 0, a.length, 2 * BitMath.msb(a.length), comparator);

            }

        }

    }

}