B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5
1 1
1 1
1 2
1 4
1 3
OutputCopy9
InputCopy3
4 2 0 2 0
6 9 9 8 8 7 7
1 6
OutputCopy7
InputCopy10
3 62 24 39
1 17
1 99
1 60
1 64
1 30
2 79 29
2 20 73
2 85 37
1 100
OutputCopy72
NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.

/*

        "Everything in the universe is balanced. Every disappointment

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

                        Keep going, never give up."

*/

import java.util.*;

import java.lang.*;

import java.io.*;

public class Solution {

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

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

        sc = new FastReader();

        int test = 1;

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

            solve();

        }

        out.close();

    }

    private static void solve() {

        int n = sc.nextInt();

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

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

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

            boolean alreadyHasAscent = false;

            int totalElements = sc.nextInt();

            int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;

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

                int value = sc.nextInt();

                if (value > min) {

                    alreadyHasAscent = true;

                }

                min = Math.min(min, value);

                max = Math.max(max, value);

            }

            if (alreadyHasAscent) {

                min = Integer.MIN_VALUE;

                max = Integer.MAX_VALUE;

            }

            minimums.add(min);

            maximums.add(max);

        }

        Collections.sort(minimums);

        Collections.sort(maximums);

        //out.println(maximums);

        long totalPairs = 0;

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

            totalPairs += binarySearch(maximums, minimums.get(i));

        }

        out.println(totalPairs);

    }

    private static long binarySearch(List<Integer> maximums, int minValue) {

        int n = maximums.size();

        int lo = 0, hi = n - 1;

        int res = n;

        while (lo <= hi) {

            int mid = (lo + hi) >> 1;

            if (maximums.get(mid) > minValue) {

                //out.println("ok");

                res = Math.min(res, mid);

                hi = mid - 1;

            }else {

                lo = mid + 1;

            }

        }

        return n - res;

    }

    public static FastReader sc;

    public static PrintWriter out;

    static class FastReader

    {

        BufferedReader br;

        StringTokenizer str;

        public FastReader()

        {

            br = new BufferedReader(new

                    InputStreamReader(System.in));

        }

        String next()

        {

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

            {

                try

                {

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

                }

                catch (IOException  end)

                {

                    end.printStackTrace();

                }

            }

            return str.nextToken();

        }

        int nextInt()

        {

            return Integer.parseInt(next());

        }

        long nextLong()

        {

            return Long.parseLong(next());

        }

        double nextDouble()

        {

            return Double.parseDouble(next());

        }

        String nextLine()

        {

            String str = "";

            try

            {

                str = br.readLine();

            }

            catch (IOException end)

            {

                end.printStackTrace();

            }

            return str;

        }

    }

}


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

/*

        "Everything in the universe is balanced. Every disappointment

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

                        Keep going, never give up."

                        Just have Patience + 1...

*/

import java.util.*;

import java.lang.*;

import java.io.*;

public class Solution {

    static int MAX = 100005, DEPTH = 25;

    static int[] tin = new int[MAX];

    static int[] tout = new int[MAX];

    static int time = 1;

    static int[] distance = new int[MAX];

    static int[][] ancestor = new int[MAX][DEPTH];

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

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

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

        sc = new FastReader();

        int test = 1;

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

            solve();

        }

        out.close();

    }

    private static void solve() {

        int n = sc.nextInt();

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

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

        }

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

            int u = sc.nextInt();

            int v = sc.nextInt();

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

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

        }

        dfs(1, 1);

        int q = sc.nextInt();

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

            // add edge between x and y

            int x = sc.nextInt();

            int y = sc.nextInt();

            // find a path from a to b having exactly k edges

            int a = sc.nextInt();

            int b = sc.nextInt();

            int k = sc.nextInt();

            // if path length between a and b is l, then since a path can contain the same vertices and same edges multiple times,

            // we can also find a path between a and b with length l + 2 * constant

            // we should find a path with length l <= k, which have parity same as parity of k

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

            // case1 : path from a to b without using added edge between x and y

            possiblePathLengths.add(findDistanceBetweenTwoNodes(a, b));

            // case2 : path from a to x, then use added edge from x to y (only once, otherwise it won't affect the parity), and then from y to b

            possiblePathLengths.add(findDistanceBetweenTwoNodes(a, x) + 1 + findDistanceBetweenTwoNodes(b, y));

            // case3 : path from a to y, then use added edge from y to x (only once, otherwise it won't affect the parity), and then from x to b

            possiblePathLengths.add(findDistanceBetweenTwoNodes(a, y) + 1 + findDistanceBetweenTwoNodes(b, x));

            boolean found = false;

            for (int length : possiblePathLengths) {

                if (length <= k && (length % 2 == k % 2)) {

                    found = true;

                    break;

                }

            }

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

        }

    }

    private static void dfs(int currNode, int parent) {

        tin[currNode] = time++;

        ancestor[currNode][0] = parent;

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

            ancestor[currNode][j] = ancestor[ancestor[currNode][j - 1]][j - 1];

        }

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

            if (adjacentNode == parent) {

                continue;

            }

            distance[adjacentNode] = distance[currNode] + 1;

            dfs(adjacentNode, currNode);

        }

        tout[currNode] = time++;

    }

    private static int findDistanceBetweenTwoNodes(int u, int v) {

        int lcaNode = findLCA(u, v);

        return distance[u] + distance[v] - 2 * distance[lcaNode];

    }

    private static int findLCA(int u, int v) {

        if (isAncestor(u, v)) {

            return u;

        }

        if (isAncestor(v, u)) {

            return v;

        }

        for (int j = DEPTH - 1; j >= 0; j--) {

            if (!isAncestor(ancestor[u][j], v)) {

                u = ancestor[u][j];

            }

        }

        return ancestor[u][0];

    }

    private static boolean isAncestor(int u, int v) { // check if u is ancestor of v

        return tin[u] <= tin[v] && tout[u] >= tout[v];

    }

    public static FastReader sc;

    public static PrintWriter out;

    static class FastReader

    {

        BufferedReader br;

        StringTokenizer str;

        public FastReader()

        {

            br = new BufferedReader(new

                    InputStreamReader(System.in));

        }

        String next()

        {

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

            {

                try

                {

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

                }

                catch (IOException  lastMonthOfVacation)

                {

                    lastMonthOfVacation.printStackTrace();

                }

            }

            return str.nextToken();

        }

        int nextInt()

        {

            return Integer.parseInt(next());

        }

        long nextLong()

        {

            return Long.parseLong(next());

        }

        double nextDouble()

        {

            return Double.parseDouble(next());

        }

        String nextLine()

        {

            String str = "";

            try

            {

                str = br.readLine();

            }

            catch (IOException lastMonthOfVacation)

            {

                lastMonthOfVacation.printStackTrace();

            }

            return str;

        }

    }

}


E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9
abacbecfd
OutputCopyYES
001010101
InputCopy8
aaabbcbb
OutputCopyYES
01011011
InputCopy7
abcdedc
OutputCopyNO
InputCopy5
abcde
OutputCopyYES
00000

/*

        "Everything in the universe is balanced. Every disappointment

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

                        Keep going, never give up."

                        Just have Patience + 1...

*/

import java.util.*;

import java.lang.*;

import java.io.*;

public class Solution {

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

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

        sc = new FastReader();

        int test = 1;

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

            solve();

        }

        out.close();

    }

    private static void solve() {

        int n = sc.nextInt();

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

        char prev = 'a', prevToPrev = 'a';

        String res = "";

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

            if (s[i] >= prev) {

                res += '0';

                prev = s[i];

            }else if (s[i] >= prevToPrev) {

                res += '1';

                prevToPrev = s[i];

            }else {

                out.println("NO");

                return;

            }

        }

        out.println("YES");

        out.println(res);

    }

    public static FastReader sc;

    public static PrintWriter out;

    static class FastReader

    {

        BufferedReader br;

        StringTokenizer str;

        public FastReader()

        {

            br = new BufferedReader(new

                    InputStreamReader(System.in));

        }

        String next()

        {

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

            {

                try

                {

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

                }

                catch (IOException  end)

                {

                    end.printStackTrace();

                }

            }

            return str.nextToken();

        }

        int nextInt()

        {

            return Integer.parseInt(next());

        }

        long nextLong()

        {

            return Long.parseLong(next());

        }

        double nextDouble()

        {

            return Double.parseDouble(next());

        }

        String nextLine()

        {

            String str = "";

            try

            {

                str = br.readLine();

            }

            catch (IOException end)

            {

                end.printStackTrace();

            }

            return str;

        }

    }

}


A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules:  every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes);  each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk;  all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors.

import java.util.*;

public class Training1 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        for (int i = 0; i < t; i++) {
            int arr[]=new int[3];
            arr[0] = sc.nextInt();
            arr[1] = sc.nextInt();
            arr[2] = sc.nextInt();
            Arrays.sort(arr);
            int res = 0;
            if (arr[0] > 0) {
                arr[0]--;
                res++;
            }
            if (arr[1] > 0) {
                arr[1]--;
                res++;
            }
            if (arr[2] > 0) {
                arr[2]--;
                res++;
            }
            if (arr[2] > 0 && arr[0] > 0) {
                arr[2]--;
                arr[0]--;
                res++;
            }
            if (arr[2] > 0 && arr[1] > 0) {
                arr[2]--;
                arr[1]--;
                res++;
            }
            if (arr[0] > 0 && arr[1] > 0) {
                arr[0]--;
                arr[1]--;
                res++;
            }
            if (arr[0] > 0 && arr[1] > 0&& arr[2]>0) {
                res++;
            }
            System.out.println(res);
        }

    }

}


B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3
5 1 1
8 10 10
1000000 1 1000000
OutputCopy5
8
499999500000
NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good.

import java.lang.reflect.Array;

import java.math.BigInteger;

import java.util.*;

import java.lang.*;

import java.io.*;

public class Solution {

    static int MAX = 31630;

    static boolean[] isPrime = new boolean[MAX];

    static List<Integer> primes = new ArrayList<>();

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

        FastReader fastReader = new FastReader();

        int t = fastReader.nextInt();

        while (t-- > 0) {

            int n =fastReader.nextInt();

            int g=fastReader.nextInt();

            int b = fastReader.nextInt();

            int goodDays =(int) Math.ceil((1.0*n)/2);

            long totalDays = (long) goodDays / g * (g+b) ;

            int remainder =goodDays%g;

            totalDays = remainder==0?totalDays-b:totalDays+remainder;

            System.out.println(Math.max(totalDays,n));

        }

    }

    private static void solve(int t) {

        int n = sc.nextInt();

        int[] arr = new int[n];

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

            arr[i] = sc.nextInt();

        }

        for (int prime : primes) {

            int count = 0;

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

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

                    count++;

                    if (count > 1) {

                        out.println("YES");

                        return;

                    }

                    while (arr[i] % prime == 0) {

                        arr[i] /= prime;

                    }

                }

            }

        }

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

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

            if (arr[i] == 1) {

                continue;

            }

            if (seen.contains(arr[i])) {

                out.println("YES");

                return;

            }

            seen.add(arr[i]);

        }

        out.println("NO");

    }

    private static void sieve() {

        Arrays.fill(isPrime, true);

        isPrime[0] = isPrime[1] = false;

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

            if (isPrime[i]) {

                primes.add(i);

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

                    isPrime[j] = false;

                }

            }

        }

    }

    public static FastReader sc;

    public static PrintWriter out;

    static class FastReader {

        BufferedReader br;

        StringTokenizer str;

        public FastReader() {

            br = new BufferedReader(new

                    InputStreamReader(System.in));

        }

        String next() {

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

                try {

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

                } catch (IOException lastMonthOfVacation) {

                    lastMonthOfVacation.printStackTrace();

                }

            }

            return str.nextToken();

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

        String nextLine() {

            String str = "";

            try {

                str = br.readLine();

            } catch (IOException lastMonthOfVacation) {

                lastMonthOfVacation.printStackTrace();

            }

            return str;

        }

    }

}


B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3
4
1 2 3 4
3
7 4 -1
3
5 -5 5
OutputCopyYES
NO
NO
NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.StringTokenizer;

public class JustEatIt {

	public static void main(String[] args) {

		// TODO Auto-generated method stub

		FastScanner fs = new FastScanner();

		PrintWriter pw = new PrintWriter(System.out);

		int T = fs.nextInt();

		while (T-- > 0)

		{

			int N = fs.nextInt();

			long[] arr = fs.readArray(N);

			long Yasser = 0;

			for (long ele : arr)

			{

				Yasser += ele;

			}

			long Abdel = Math.max(Kadane(arr,0, N - 2), Kadane(arr,1, N - 1));

			if (Yasser > Abdel)

			{

				pw.println("YES");

			}

			else

			{

				pw.println("NO");

			}

		}

        pw.close();

	}

	private static long Kadane(long[] arr, int start, int end)

	{

		long sum = 0;

		long max = Long.MIN_VALUE;

		for (int i = start; i <= end; i++)

		{

			sum += arr[i];

			max = Math.max(max, sum);

		    if (sum < 0)

		    {

		    	sum = 0;

		    }

		}

		return max;

	}

	private static class FastScanner {

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

        StringTokenizer st = new StringTokenizer("");

        public String next() {

            while (!st.hasMoreElements()) {

                try {

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

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        long[] readArray(int n) {

            long[] a = new long[n];

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

                a[i] = nextLong();

            }

            return a;

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

}

}


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

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

public class App {
    public static void main (String[] args) throws java.lang.Exception {
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        //reader = new BufferedReader(new FileReader(new File("C:\\Users\\Anjali\\Desktop\\projects\\HelloWorld\\src\\input.txt")));
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
        //writer = new BufferedWriter(new FileWriter(new File("C:\\Users\\Anjali\\Desktop\\projects\\HelloWorld\\src\\output.txt")));
		//int tests = Integer.parseInt(reader.readLine());
        int tests = 1;
		//StringBuilder sb = new StringBuilder(tests);
		while (tests-- > 0){
		    solve(reader, writer);
            writer.write("\n");
		}
		reader.close();
        writer.flush();
        writer.close();
    }

    static void solve(BufferedReader reader, BufferedWriter writer) throws  IOException {
		int tests = Integer.parseInt(reader.readLine());
		for (int i = 0; i < tests; i++) {
			int n = Integer.parseInt(reader.readLine());
			int[] a = new int[n];
			int[] b = new int[n];
			String[] input = reader.readLine().split(" ");
			for (int j = 0; j < n; j++) {
				a[j] = Integer.parseInt(input[j]);
			}
			String[] input1 = reader.readLine().split(" ");
			for (int j = 0; j < n; j++) {
				b[j] = Integer.parseInt(input1[j]);
			}
			Arrays.sort(a);
			Arrays.sort(b);
			for (int j = 0; j < n; j++) {
				writer.write(a[j] + " ");
			}
			writer.write("\n");
			for (int j = 0; j < n; j++) {
				writer.write(b[j] + " ");
			}
			writer.write("\n");
		}
	}
}


A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb.  For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5
0 10 2 3
0 10 3 3
900000000 1000000000 1 9999999
1 2 1 1
1 3 1 1
OutputCopy2
-1
10
-1
1
NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.

import java.util.Scanner;

public class MyClass {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int t = sc.nextInt();

        while(t>0)

        {

            int x = sc.nextInt();

            int y = sc.nextInt();

            int a = sc.nextInt();

            int b = sc.nextInt();

            if((int)Math.ceil((double)(y-x)/(double)(a+b)) == ((y-x)/(a+b)))

                System.out.println((y-x)/(a+b));

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

            t--;

        }

    }

}


D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules:  He starts at the top-left cell in the grid;  In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to:   in the case 'U' to the cell (i−1,j)(i−1,j);  in the case 'D' to the cell (i+1,j)(i+1,j);  in the case 'L' to the cell (i,j−1)(i,j−1);  in the case 'R' to the cell (i,j+1)(i,j+1);   He wants to run exactly kk kilometers, so he wants to make exactly kk moves;  Bashar can finish in any cell of the grid;  He can't go out of the grid so at any moment of the time he should be on some cell;  Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4
OutputCopyYES
2
2 R
2 L
InputCopy3 3 1000000000
OutputCopyNO
InputCopy3 3 8
OutputCopyYES
3
2 R
2 D
1 LLRR
InputCopy4 4 9
OutputCopyYES
1
3 RLD
InputCopy3 4 16
OutputCopyYES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):

import java.util.*;

import java.io.*;

public class Main {

    static class Scan {

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

        private int index;

        private InputStream in;

        private int total;

        public Scan()

        {

            in=System.in;

        }

        public int scan()throws IOException

        {

            if(total<0)

            throw new InputMismatchException();

            if(index>=total)

            {

                index=0;

                total=in.read(buf);

                if(total<=0)

                return -1;

            }

            return buf[index++];

        }

        public int scanInt()throws IOException

        {

            int integer=0;

            int n=scan();

            while(isWhiteSpace(n))

            n=scan();

            int neg=1;

            if(n=='-')

            {

                neg=-1;

                n=scan();

            }

            while(!isWhiteSpace(n))

            {

                if(n>='0'&&n<='9')

                {

                    integer*=10;

                    integer+=n-'0';

                    n=scan();

                }

                else throw new InputMismatchException();

            }

            return neg*integer;

        }

        public double scanDouble()throws IOException

        {

            double doub=0;

            int n=scan();

            while(isWhiteSpace(n))

            n=scan();

            int neg=1;

            if(n=='-')

            {

                neg=-1;

                n=scan();

            }

            while(!isWhiteSpace(n)&&n!='.')

            {

                if(n>='0'&&n<='9')

                {

                    doub*=10;

                    doub+=n-'0';

                    n=scan();

                }

                else throw new InputMismatchException();

            }

            if(n=='.')

            {

                n=scan();

                double temp=1;

                while(!isWhiteSpace(n))

                {

                    if(n>='0'&&n<='9')

                    {

                        temp/=10;

                        doub+=(n-'0')*temp;

                        n=scan();

                    }

                    else throw new InputMismatchException();

                }

            }

            return doub*neg;

        }

        public String scanString()throws IOException

        {

            StringBuilder sb=new StringBuilder();

            int n=scan();

            while(isWhiteSpace(n))

            n=scan();

            while(!isWhiteSpace(n))

            {

                sb.append((char)n);

                n=scan();

            }

            return sb.toString();

        }

        private boolean isWhiteSpace(int n)

        {

            if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)

            return true;

            return false;

        }

    }

    static ArrayList<Integer> adj_lst[];

    static boolean vis[];

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

        Scan input=new Scan();

        int n=input.scanInt();

        int m=input.scanInt();

        int k=input.scanInt();

        StringBuilder ans=new StringBuilder("");

        int cnt=0;

        if(n==1) {

            if(k>=m-1) {

                ans.append((m-1)+" "+"R\n");

                k-=m-1;

                cnt++;

            }

            else if(k>0) {

                ans.append(k+" "+"R\n");

                k-=k;

                cnt++;

            }

            if(k>=m-1) {

                ans.append((m-1)+" "+"L\n");

                k-=m-1;

                cnt++;

            }

            else if(k>0) {

                ans.append(k+" "+"L\n");

                k-=k;

                cnt++;

            }

            if(k!=0) {

                System.out.println("NO");

                return;

            }

            System.out.println("YES\n"+cnt+"\n"+ans);

            return;

        }

        if(m==1) {

            if(k>=n-1) {

                ans.append((n-1)+" "+"D\n");

                k-=n-1;

                cnt++;

            }

            else if(k>0) {

                ans.append(k+" "+"D\n");

                k-=k;

                cnt++;

            }

            if(k>=n-1) {

                ans.append((n-1)+" "+"U\n");

                k-=n-1;

                cnt++;

            }

            else if(k>0) {

                ans.append(k+" "+"U\n");

                k-=k;

                cnt++;

            }

            if(k!=0) {

                System.out.println("NO");

                return;

            }

            System.out.println("YES\n"+cnt+"\n"+ans);

            return;

        }

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

            if(i!=1) {

                if(k>=1) {

                    if(k>=1) {

                        ans.append(1+" "+"R\n");

                        k--;

                        cnt++;

                    }

                }

                else {

                    break;

                }

            }

            if(k>=n-1) {

                ans.append(1+" "+"D\n");

                k--;

                cnt++;

                int tmp_cnt=0;

                int j=1;

                boolean br=false;

                for(j=1;j<=n-2;j++) {

                    if(k<3) {

                        br=true;

                        break;

                    }

                    tmp_cnt++;

                    k-=3;

                }

                if(tmp_cnt>0) {

                    ans.append(tmp_cnt+" "+"RLD\n");

                    cnt++;

                }

                if(br && k>0) {

                    if(k==1) {

                        ans.append(1+" "+"R\n");

                        k--;

                        cnt++;

                    }

                    else if(k==2) {

                        ans.append(1+" "+"RL\n");

                        k-=2;

                        cnt++;

                    }

                }

            }

            else if(k!=0) {

                ans.append(k+" "+"D\n");

                k-=k;

                cnt++;

            }

            if(i!=1 && k>0) {

                ans.append(1+" "+"L\n");

                k--;

                cnt++;

            }

            if(i!=1 && k>0) {

                ans.append(1+" "+"R\n");

                k--;

                cnt++;

            }

            if(k==0) {

                break;

            }

            if(k>=1) {

                ans.append(1+" "+"R\n");

                k--;

                cnt++;

            }

            if(k==0) {

                break;

            }

            if(m%2==0 && i==m/2) {

                if(k>=n-1) {

                    cnt++;

                    k-=n-1;

                    ans.append((n-1)+" "+"U\n");

                }

                else if(k!=0){

                    ans.append(k+" "+"U\n");

                    k-=k;

                    cnt++;

                }

            }

            else {

                if(k>=n-1) {

                    ans.append(1+" "+"U\n");

                    k--;

                    cnt++;

                    int tmp_cnt=0;

                    int j=1;

                    boolean br=false;

                    for(j=1;j<=n-2;j++) {

                        if(k<3) {

                            br=true;

                            break;

                        }

                        tmp_cnt++;

                        k-=3;

                    }

                    if(tmp_cnt>0) {

                        ans.append(tmp_cnt+" "+"RLU\n");

                        cnt++;

                    }

                    if(br && k>0) {

                        if(k==1) {

                            ans.append(1+" "+"R\n");

                            k--;

                            cnt++;

                        }

                        else if(k==2) {

                            ans.append(1+" "+"RL\n");

                            k-=2;

                            cnt++;

                        }

                    }

                }

                else if(k!=0){

                    ans.append(k+" "+"U\n");

                    k-=k;

                    cnt++;

                }

            }

            if(k==0) {

                break;

            }

            if(k>=n-1) {

                ans.append((n-1)+" "+"D\n");

                k-=n-1;

                cnt++;

            }

            else if(k!=0){

                ans.append(k+" "+"D\n");

                k-=k;

                cnt++;

            }

            if(k==0) {

                break;

            }

            if(k>=1) {

                ans.append(1+" "+"L\n");

                k--;

                cnt++;

            }

            if(k==0) {

                break;

            }

            if(k>=n-1) {

                ans.append((n-1)+" "+"U\n");

                k-=n-1;

                cnt++;

            }

            else if(k!=0){

                ans.append(k+" "+"U\n");

                k-=k;

                cnt++;

            }

            if(k==0) {

                break;

            }

            if(k>=1) {

                ans.append(1+" "+"R\n");

                k--;

                cnt++;

            }

        }

        if(m%2==1) {

            if(k>=1) {

                ans.append(1+" "+"R\n");

                k--;

                cnt++;

            }

            if(k>=n-1) {

                ans.append((n-1)+" "+"D\n");

                k-=n-1;

                cnt++;

            }

            else if(k>0){

                ans.append(k+" "+"D\n");

                k-=k;

                cnt++;

            }

            if(k>=1) {

                ans.append(1+" "+"L\n");

                k--;

                cnt++;

            }

            if(k>=1) {

                ans.append(1+" "+"R\n");

                k--;

                cnt++;

            }

            if(k>=n-1) {

                ans.append((n-1)+" "+"U\n");

                k-=n-1;

                cnt++;

            }

            else if(k!=0) {

                ans.append(k+" "+"U\n");

                k-=k;

                cnt++;

            }

        }

        if(k>=m-1) {

            ans.append((m-1)+" "+"L\n");

            k-=m-1;

            cnt++;

        }

        else if(k!=0) {

            ans.append(k+" "+"L\n");

            k-=k;

            cnt++;

        }

        if(k!=0) {

            System.out.println("NO");

            return;

        }

        System.out.println("YES\n"+cnt+"\n"+ans);

    }

}


import java.util.Arrays;

import java.util.Collections;

import java.util.Scanner;

public class kuroniAndGifts {

	public static void main(String[] args) {

		Scanner s = new Scanner(System.in);

		int t = s.nextInt();

		while(t-->0) {

			int n = s.nextInt();

			int arr1[] = new int[n];

			int arr2[] = new int[n];

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

				arr1[i] = s.nextInt();

			}

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

				arr2[i] = s.nextInt();

			}

			Arrays.sort(arr1);

			Arrays.sort(arr2);

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

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

			}

			System.out.println();

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

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

			}

		}

        System.out.println();

	}

}


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 Fight_with_Monsters {

    static FastScanner fs;

    static FastWriter fw;

    static boolean checkOnlineJudge = System.getProperty("ONLINE_JUDGE") == null;

    private static final int[][] kdir = new int[][]{{-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {2, 1}, {1, 2}};

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

    private static final int iMax = (int) (1e9 + 100), iMin = (int) (-1e9 - 100);

    private static final long lMax = (long) (1e18 + 100), lMin = (long) (-1e18 - 100);

    private static final int mod1 = (int) (1e9 + 7);

    private static final int mod2 = 998244353;

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

        fs = new FastScanner();

        fw = new FastWriter();

        int t = 1;

        //t = fs.nextInt();

        while (t-- > 0) {

            solve();

        }

        fw.out.close();

    }

    private static void solve() {

        int n = fs.nextInt(), a = fs.nextInt(), b = fs.nextInt(), k = fs.nextInt();

        Integer[] monsters_power = readIntArray(n);

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

        long sum = (long) a + b;

        for (long x : monsters_power) {

            long div = ceilDiv(x, sum);

            long diff = x - ((sum * div) - b);

            if (diff <= 0) {

                list.add(0L);

                continue;

            }

            long skip = ceilDiv(diff, a);

            list.add(skip);

        }

        Collections.sort(list);

        int ans = 0;

        for (long x : list) {

            k -= x;

            if (k < 0) break;

            ans++;

        }

        fw.out.println(ans);

    }

    private static class UnionFind {

        private final int[] parent;

        private final int[] rank;

        UnionFind(int n) {

            parent = new int[n + 5];

            rank = new int[n + 5];

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

                parent[i] = i;

                rank[i] = 0;

            }

        }

        private int find(int i) {

            if (parent[i] == i)

                return i;

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

        }

        private void union(int a, int b) {

            a = find(a);

            b = find(b);

            if (a != b) {

                if (rank[a] < rank[b]) {

                    int temp = a;

                    a = b;

                    b = temp;

                }

                parent[b] = a;

                if (rank[a] == rank[b])

                    rank[a]++;

            }

        }

    }

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

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

    }

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

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

    }

    private static long pow(long a, long b, int mod) {

        long result = 1;

        while (b > 0) {

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

                result = (result * a) % mod;

            }

            a = (a * a) % mod;

            b >>= 1;

        }

        return result;

    }

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

        return ((a + b - 1) / b);

    }

    private static long getMin(long... args) {

        long min = lMax;

        for (long arg : args)

            min = Math.min(min, arg);

        return min;

    }

    private static long getMax(long... args) {

        long max = lMin;

        for (long arg : args)

            max = Math.max(max, arg);

        return max;

    }

    private static boolean isPalindrome(String s, int l, int r) {

        int i = l, j = r;

        while (j - i >= 1) {

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

                return false;

            i++;

            j--;

        }

        return true;

    }

    private static List<Integer> primes(int n) {

        boolean[] primeArr = new boolean[n + 5];

        Arrays.fill(primeArr, true);

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

            if (primeArr[i]) {

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

                    primeArr[j] = false;

                }

            }

        }

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

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

            if (primeArr[i])

                primeList.add(i);

        }

        return primeList;

    }

    private static class Pair<U, V> {

        private final U first;

        private final V second;

        @Override

        public boolean equals(Object o) {

            if (this == o) return true;

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

            Pair<?, ?> pair = (Pair<?, ?>) o;

            return first.equals(pair.first) && second.equals(pair.second);

        }

        @Override

        public int hashCode() {

            return Objects.hash(first, second);

        }

        @Override

        public String toString() {

            return "(" + first + ", " + second + ")";

        }

        private Pair(U ff, V ss) {

            this.first = ff;

            this.second = ss;

        }

    }

    private static <T> void randomizeArr(T[] arr, int n) {

        Random r = new Random();

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

            int j = r.nextInt(i + 1);

            swap(arr, i, j);

        }

    }

    private static Integer[] readIntArray(int n) {

        Integer[] arr = new Integer[n];

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

            arr[i] = fs.nextInt();

        return arr;

    }

    private static List<Integer> readIntList(int n) {

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

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

            list.add(fs.nextInt());

        return list;

    }

    private static <T> void swap(T[] arr, int i, int j) {

        T temp = arr[i];

        arr[i] = arr[j];

        arr[j] = temp;

    }

    private static <T> void displayArr(T[] arr) {

        for (T x : arr)

            fw.out.print(x + " ");

        fw.out.println();

    }

    private static <T> void displayList(List<T> list) {

        for (T x : list)

            fw.out.print(x + " ");

        fw.out.println();

    }

    private static class FastScanner {

        BufferedReader br;

        StringTokenizer st;

        FastScanner() throws IOException {

            if (checkOnlineJudge)

                this.br = new BufferedReader(new FileReader("src/input.txt"));

            else

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

            this.st = new StringTokenizer("");

        }

        public String next() {

            while (!st.hasMoreTokens()) {

                try {

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

                } catch (IOException err) {

                    err.printStackTrace();

                }

            }

            return st.nextToken();

        }

        public String nextLine() {

            if (st.hasMoreTokens()) {

                return st.nextToken("").trim();

            }

            try {

                return br.readLine().trim();

            } catch (IOException err) {

                err.printStackTrace();

            }

            return "";

        }

        public int nextInt() {

            return Integer.parseInt(next());

        }

        public long nextLong() {

            return Long.parseLong(next());

        }

        public double nextDouble() {

            return Double.parseDouble(next());

        }

    }

    private static class FastWriter {

        PrintWriter out;

        FastWriter() throws IOException {

            if (checkOnlineJudge)

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

            else

                out = new PrintWriter(System.out);

        }

    }

}


C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33:  [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66.  [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32.

// have faith in yourself!!!!!
/*
    Naive mistakes in java :
    --> Arrays.sort(primitive) is O(n^2)
    --> Never use '=' to compare to Integer data types, instead use 'equals()'
    --> -4 % 3 = -1, actually it should be 2, so add '+n' to modulo result
 */

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

public class CodeForces {

    public static void main(String[] args) throws IOException {
        openIO();
        int testCase = 1;
//        testCase = sc. nextInt();
        for (int i = 1; i <= testCase; i++) solve(i);
        closeIO();
    }
    /*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/

    public static void solve(int tCase) throws IOException {
       int n = sc.nextInt();
       mod = sc.nextInt();
       _ncr_precompute(n);
       long ans = 0;
       for(int l = 0;l<n;l++){
           ans += factorial[l+1] * _power(n-l,2)  % mod * factorial[n-l-1]  % mod;
           ans %=mod;
       }
       out.println(ans);

    }

    /*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/

    public static int mod = (int) 1e9 + 7;
    //    public static int mod =  998244353;
    public static int inf_int = (int) 1e9;
    public static long inf_long = (long) 2e18;

    public static void _sort(int[] arr, boolean isAscending) {
        int n = arr.length;
        List<Integer> list = new ArrayList<>();
        for (int ele : arr) list.add(ele);
        Collections.sort(list);
        if (!isAscending) Collections.reverse(list);
        for (int i = 0; i < n; i++) arr[i] = list.get(i);
    }

    public static void _sort(long[] arr, boolean isAscending) {
        int n = arr.length;
        List<Long> list = new ArrayList<>();
        for (long ele : arr) list.add(ele);
        Collections.sort(list);
        if (!isAscending) Collections.reverse(list);
        for (int i = 0; i < n; i++) arr[i] = list.get(i);
    }

    // time : O(1), space : O(1)
    public static int _digitCount(long num,int base){
        // this will give the # of digits needed for a number num in format : base
        return (int)(1 + Math.log(num)/Math.log(base));
    }

    // time : O(n), space: O(n)
    public static long _fact(int n){
        // simple factorial calculator
        long ans = 1;
        for(int i=2;i<=n;i++)
            ans = ans * i % mod;
        return ans;
    }

    // time for pre-computation of factorial and inverse-factorial table : O(nlog(mod))
    public static long[] factorial , inverseFact;
    public static void _ncr_precompute(int n){
        factorial = new long[n+1];
        inverseFact = new long[n+1];
        factorial[0] = inverseFact[0] = 1;
        for (int i = 1; i <=n; i++) {
            factorial[i] = (factorial[i - 1] * i) % mod;
            inverseFact[i] = _power(factorial[i], mod - 2);
        }
    }
    // time of factorial calculation after pre-computation is O(1)
    public static int _ncr(int n,int r){
        if(r > n)return 0;
        return (int)(factorial[n] * inverseFact[r] % mod * inverseFact[n - r] % mod);
    }
    public static int _npr(int n,int r){
        if(r > n)return 0;
        return (int)(factorial[n] * inverseFact[n - r] % mod);
    }

    // euclidean algorithm time O(max (loga ,logb))
    public static long _gcd(long a, long b) {
        if (a == 0)
            return b;
        return _gcd(b % a, a);
    }

    // lcm(a,b) * gcd(a,b) = a * b
    public static long _lcm(long a, long b) {
        return (a / _gcd(a, b)) * b;
    }

    // binary exponentiation time O(logn)
    public static long _power(long x, long n) {
        long ans = 1;
        while (n > 0) {
            if ((n & 1) == 1) {
                ans *= x;
                ans %= mod;
                n--;
            } else {
                x *= x;
                x %= mod;
                n >>= 1;
            }
        }
        return ans;
    }

    //sieve or first divisor time : O(mx * log ( log (mx) ) )
    public static int[]  _seive(int mx){
        int[] firstDivisor = new int[mx+1];
        for(int i=0;i<=mx;i++)firstDivisor[i] = i;
        for(int i=2;i*i<=mx;i++)
            if(firstDivisor[i] == i)
                for(int j = i*i;j<=mx;j+=i)
                    firstDivisor[j] = i;
        return firstDivisor;
    }

    // check if x is a prime # of not. time : O( n ^ 1/2 )
    private static boolean _isPrime(long x){
        for(long i=2;i*i<=x;i++)
            if(x%i==0)return false;
        return true;
    }

    static class Pair<K, V>{
        K ff;
        V ss;

        public Pair(K ff, V ss) {
            this.ff = ff;
            this.ss = ss;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || this.getClass() != o.getClass()) return false;
            Pair<?, ?> pair = (Pair<?, ?>) o;
            return ff.equals(pair.ff) && ss.equals(pair.ss);
        }

        @Override
        public int hashCode() {
            return Objects.hash(ff, ss);
        }
    }

    static FastestReader sc;
    static PrintWriter out;

    private static void openIO() throws IOException {
        sc = new FastestReader();
        out = new PrintWriter(System.out);
    }
    /*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/

    public static void closeIO() throws IOException {
        out.flush();
        out.close();
        sc.close();
    }

    private static final class FastestReader {
        private static final int BUFFER_SIZE = 1 << 16;
        private final DataInputStream din;
        private final byte[] buffer;
        private int bufferPointer, bytesRead;

        public FastestReader() {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public FastestReader(String file_name) throws IOException {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        private static boolean isSpaceChar(int c) {
            return !(c >= 33 && c <= 126);
        }

        private int skip() throws IOException {
            int b;
            //noinspection StatementWithEmptyBody
            while ((b = read()) != -1 && isSpaceChar(b)) {
            }
            return b;
        }

        public String next() throws IOException {
            int b = skip();
            final StringBuilder sb = new StringBuilder();
            while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
                sb.appendCodePoint(b);
                b = read();
            }
            return sb.toString();
        }

        public int nextInt() throws IOException {
            int ret = 0;
            byte c = read();
            while (c <= ' ') {
                c = read();
            }
            final boolean neg = c == '-';
            if (neg) {
                c = read();
            }
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');

            if (neg) {
                return -ret;
            }
            return ret;
        }

        public long nextLong() throws IOException {
            long ret = 0;
            byte c = read();
            while (c <= ' ') {
                c = read();
            }
            final boolean neg = c == '-';
            if (neg) {
                c = read();
            }
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');
            if (neg) {
                return -ret;
            }
            return ret;
        }

        public double nextDouble() throws IOException {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ') {
                c = read();
            }
            final boolean neg = c == '-';
            if (neg) {
                c = read();
            }

            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');

            if (c == '.') {
                while ((c = read()) >= '0' && c <= '9') {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg) {
                return -ret;
            }
            return ret;
        }

        private void fillBuffer() throws IOException {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1) {
                buffer[0] = -1;
            }
        }

        private byte read() throws IOException {
            if (bufferPointer == bytesRead) {
                fillBuffer();
            }
            return buffer[bufferPointer++];
        }

        public void close() throws IOException {
            din.close();
        }
    }
    /*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/
}


F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either:  find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6
1 3
3 4
4 2
2 6
5 6
5 1
OutputCopy1
1 6 4InputCopy6 8
1 3
3 4
4 2
2 6
5 6
5 1
1 4
2 5
OutputCopy2
4
1 5 2 4InputCopy5 4
1 2
1 3
2 4
2 5
OutputCopy1
3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample:

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.util.TreeSet;
import java.util.ArrayList;
import java.util.HashSet;
import java.io.InputStream;

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

    static class FEhabsLastTheorem {
        PrintWriter out;
        InputReader in;
        ArrayList<Integer>[] graph;
        HashSet<Integer>[] tset;
        int[] par;
        int[] dep;
        int max_cycle = 0;
        int start = 0;
        int end = 0;
        DSU ob;
        boolean[] visited;
        int[] tin;
        int[] low;
        int timer = 0;
        int[] cnt = new int[2];

        void dfs(int v, int p, int h) {
            dep[v] = h;
            for (int u : graph[v]) {
                if (dep[u] == -1) {
                    par[u] = v;
                    dfs(u, v, h + 1);
                } else if (u != par[v]) {
                    if (dep[v] - dep[u] + 1 > max_cycle) {
                        max_cycle = dep[v] - dep[u] + 1;
                        start = v;
                        end = u;
                    }
                }
            }
        }

        void tarjan(int v, int p) {
            visited[v] = true;
            tin[v] = low[v] = timer++;
            for (int u : graph[v]) {
                int to = u;
                if (to == p) continue;
                if (visited[to]) {
                    low[v] = Math.min(low[v], tin[to]);
                } else {
                    tarjan(to, v);
                    low[v] = Math.min(low[v], low[to]);
                    if (low[to] > tin[v]) {
                        //its a bridge
                    } else {
                        ob.unite(to, v);
                    }
                }
            }
        }

        void dfs2(int v, int p, int h) {
            dep[v] = h;
            cnt[h % 2]++;
            for (int u : tset[v]) {
                if (u != p)
                    dfs2(u, v, h + 1);
            }
        }

        TreeSet<Integer> MIS(int n) {
            TreeSet<Integer> is = new TreeSet<>();
            TreeSet<Pair> set = new TreeSet<>();
            int deg[] = new int[n + 1];
            for (int i = 0; i < n; ++i) {
                set.add(new Pair(graph[i].size(), i));
                deg[i] = graph[i].size();
            }
            while (!set.isEmpty()) {
                Pair v = set.pollFirst();
                for (int e : graph[v.y]) {
                    if (set.contains(new Pair(deg[e], e))) {
                        for (int f : graph[e]) {
                            if (set.contains(new Pair(deg[f], f))) {
                                set.remove(new Pair(deg[f], f));
                                set.add(new Pair(--deg[f], f));
                            }
                        }
                        set.remove(new Pair(deg[e], e));
                    }
                }
                is.add(v.y);
            }
            return is;
        }

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            this.out = out;
            this.in = in;
            int n = ni();
            int m = ni();
            visited = new boolean[n];
            low = new int[n];
            tin = new int[n];
            ob = new DSU(n);
            graph = new ArrayList[n];
            tset = new HashSet[n];
            par = new int[n];
            dep = new int[n];
            int sq = (int) Math.sqrt(n);
            if (sq * sq != n)
                sq++;
            int i = 0;
            for (i = 0; i < n; i++) {
                graph[i] = new ArrayList<>();
                tset[i] = new HashSet<>();
            }
            Arrays.fill(dep, -1);
            for (i = 0; i < m; i++) {
                int u = ni() - 1;
                int v = ni() - 1;
                graph[u].add(v);
                graph[v].add(u);
            }
            dfs(0, -1, 0);
            if (max_cycle >= sq) {
                pn(2);
                pn(max_cycle);
                ArrayList<Integer> ans = new ArrayList<>();
                for (i = start; i != end; i = par[i])
                    ans.add(i);
                ans.add(end);
                for (int x : ans)
                    p(x + 1 + " ");
                return;
            }
            if (n < 50) {
                TreeSet<Integer> mis = MIS(n);
                pn(1);
                int c = 0;
                for (int x : mis) {
                    p(x + 1 + " ");
                    c++;
                    if (c == sq)
                        break;
                }
                return;
            }
            tarjan(0, -1);
            int root = -1;
            HashSet<Integer> hset = new HashSet<>();
            for (i = 0; i < n; i++) {
                int father = ob.find(i);
                for (int x : graph[i]) {
                    int lull = ob.find(x);
                    if (lull == father)
                        continue;
                    tset[lull].add(father);
                    tset[father].add(lull);
                }
                hset.add(father);
                if (father == i)
                    root = i;
            }

            dfs2(root, -1, 0);
            ArrayList<Integer> ans = new ArrayList<>();
            pn(1);
            TreeSet<Integer> good = new TreeSet<>();
            for (i = 0; i < n; i++)
                good.add(i);
            if (cnt[0] > cnt[1]) {
                int c = 0;
                for (int x : hset) {
                    if (dep[x] % 2 == 0) {
                        ans.add(x);
                        good.remove(x);
                        for (int y : graph[x]) {
                            good.remove(y);
                        }
                    }
                    if (ans.size() == sq)
                        break;
                }
            } else {
                int c = 0;
                for (int x : hset) {
                    if (dep[x] % 2 != 0) {
                        ans.add(x);
                        good.remove(x);
                        for (int y : graph[x]) {
                            good.remove(y);
                        }
                    }
                    if (ans.size() == sq)
                        break;
                }
            }
            while (ans.size() < sq) {
                int x = good.pollFirst();
                ans.add(x);
                for (int y : graph[x])
                    good.remove(y);
            }
            for (int x : ans)
                p(x + 1 + " ");
        }

        int ni() {
            return in.nextInt();
        }

        void pn(long zx) {
            out.println(zx);
        }

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

        class DSU {
            int[] par;
            int[] sz;

            DSU(int n) {
                par = new int[n];
                sz = new int[n];
                int i = 0;
                for (i = 0; i < n; i++) {
                    par[i] = i;
                    sz[i] = 1;
                }
            }

            int find(int x) {
                if (par[x] != x)
                    return par[x] = find(par[x]);
                return par[x];
            }

            void unite(int x, int y) {
                int x_root = find(x);
                int y_root = find(y);
                if (x_root == y_root)
                    return;
                if (sz[x_root] <= sz[y_root]) {
                    par[x_root] = y_root;
                    sz[y_root] += sz[x_root];
                } else {
                    par[y_root] = x_root;
                    sz[x_root] += sz[y_root];
                }
            }

        }

        class Pair implements Comparable<Pair> {
            int x;
            int y;

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

            public int compareTo(Pair other) {
                if (this.x != other.x)
                    return this.x - other.x;
                return this.y - other.y;
            }

            public String toString() {
                return "(" + x + "," + y + ")";
            }

        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new UnknownError();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new UnknownError();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

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

        public String next() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuffer res = new StringBuffer();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));

            return res.toString();
        }

        private boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

    }
}


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

import java.io.*;

import java.util.*;

import java.awt.Point;

public class Ayubfunction {

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

        Scanner sc=new Scanner(System.in);

        StringBuilder sb=new StringBuilder();

        int t=sc.nextInt();

        while(t-->0){

            long n=sc.nextInt(),m=sc.nextInt();

            long zero=n-m;

            long k=zero/(m+1);

            sb.append((n*(n+1)/2)-((m+1)*k*(k+1)/2)-((k+1)*(zero%(m+1)))+"\n");

        }

        System.out.println(sb);

    }

}