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

import java.io.IOException;

import java.io.InputStream;

import java.io.PrintWriter;

import java.util.InputMismatchException;

import java.io.IOException;

import java.util.ArrayList;

import java.io.InputStream;

/**

 * Built using CHelper plug-in

 * Actual solution is at the top

 */

public class Main {

    public static void main(String[] args) {

        InputStream inputStream = System.in;

        OutputStream outputStream = System.out;

        FastReader in = new FastReader(inputStream);

        PrintWriter out = new PrintWriter(outputStream);

        DTimeToRun solver = new DTimeToRun();

        solver.solve(1, in, out);

        out.close();

    }

    static class DTimeToRun {

        public void solve(int testNumber, FastReader s, PrintWriter out) {

            int n = s.nextInt();

            int m = s.nextInt();

            int k = s.nextInt();

            if (k > (4 * n * m) - (2 * n) - (2 * m)) {

                out.println("NO");

                return;

            }

            out.println("YES");

            ArrayList<DTimeToRun.pair> list = new ArrayList<>();

            if (n == 1) {

                if (k >= m - 1) {

                    list.add(new DTimeToRun.pair(m - 1, "R"));

                    k -= (m - 1);

                    list.add(new DTimeToRun.pair(k, "L"));

                } else {

                    list.add(new DTimeToRun.pair(k, "R"));

                }

            } else if (m == 1) {

                if (k >= n - 1) {

                    list.add(new DTimeToRun.pair(n - 1, "D"));

                    k -= (n - 1);

                    list.add(new DTimeToRun.pair(k, "U"));

                } else {

                    list.add(new DTimeToRun.pair(k, "D"));

                }

            } else {

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

                    if (k >= m - 1) {

                        list.add(new DTimeToRun.pair(m - 1, "R"));

                        k -= (m - 1);

                    } else {

                        list.add(new DTimeToRun.pair(k, "R"));

                        k = 0;

                    }

                    if (k == 0) {

                        break;

                    }

                    if (i == 0) {

                        if (k >= m - 1) {

                            list.add(new DTimeToRun.pair(m - 1, "L"));

                            k -= (m - 1);

                        } else {

                            list.add(new DTimeToRun.pair(k, "R"));

                            k = 0;

                        }

                    } else {

                        if (k >= 3 * (m - 1)) {

                            list.add(new DTimeToRun.pair(m - 1, "UDL"));

                            k = k - (3 * (m - 1));

                        } else {

                            if (k >= 3) {

                                list.add(new DTimeToRun.pair(k / 3, "UDL"));

                            }

                            k %= 3;

                            if (k == 2) {

                                list.add(new DTimeToRun.pair(1, "UD"));

                            } else if (k == 1) {

                                list.add(new DTimeToRun.pair(1, "U"));

                            }

                            k = 0;

                        }

                    }

                    if (k == 0) {

                        break;

                    }

                    if (i == n - 1) {

                        if (k >= n - 1) {

                            list.add(new DTimeToRun.pair(n - 1, "U"));

                            k -= (n - 1);

                        } else {

                            list.add(new DTimeToRun.pair(k, "U"));

                            k = 0;

                        }

                    } else {

                        if (k >= 1) {

                            list.add(new DTimeToRun.pair(1, "D"));

                            k--;

                        }

                    }

                }

            }

            out.println(list.size());

            out.println(DTimeToRun.arrayLists.print(list));

        }

        private static class pair {

            int val;

            String str;

            public pair(int val, String str) {

                this.val = val;

                this.str = str;

            }

            public String toString() {

                return this.val + " " + this.str;

            }

        }

        private static class arrayLists {

            static StringBuilder print(ArrayList<?> list) {

                StringBuilder ans = new StringBuilder();

                for (Object curr : list) {

                    ans.append(curr.toString()).append("\n");

                }

                return ans;

            }

        }

    }

    static class FastReader {

        private InputStream stream;

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

        private int curChar;

        private int numChars;

        private FastReader.SpaceCharFilter filter;

        public FastReader(InputStream stream) {

            this.stream = stream;

        }

        public int read() {

            if (numChars == -1) {

                throw new InputMismatchException();

            }

            if (curChar >= numChars) {

                curChar = 0;

                try {

                    numChars = stream.read(buf);

                } catch (IOException e) {

                    throw new InputMismatchException();

                }

                if (numChars <= 0) {

                    return -1;

                }

            }

            return buf[curChar++];

        }

        public int nextInt() {

            int c = read();

            while (isSpaceChar(c)) {

                c = read();

            }

            int sgn = 1;

            if (c == '-') {

                sgn = -1;

                c = read();

            }

            int res = 0;

            do {

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

                    throw new InputMismatchException();

                }

                res *= 10;

                res += c - '0';

                c = read();

            } while (!isSpaceChar(c));

            return res * sgn;

        }

        public boolean isSpaceChar(int c) {

            if (filter != null) {

                return filter.isSpaceChar(c);

            }

            return isWhitespace(c);

        }

        public static boolean isWhitespace(int c) {

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

        }

        public interface SpaceCharFilter {

            public boolean isSpaceChar(int ch);

        }

    }

}


D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5
5 0 3 1 2
1 8 9 1 3
1 2 3 4 5
9 1 0 3 7
2 3 0 6 3
6 4 1 7 0
OutputCopy1 5

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

public class Main{

    static int n, m;
    static int[]t;
    static int[][] a;
    static int x, y;

    static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
    static int nextInt()throws Exception{
        in.nextToken();
        return (int)in.nval;
    }

    static boolean check(int v){
        Arrays.fill(t, 0);
        for(int i=1; i<=n; i++){
            int c = 0;
            for(int j=0; j<m; j++)
                c += a[i][j]>=v?1<<j:0;
            if(t[c]==0) t[c] = i;
        }

        for(int i=0; i<(1<<m); i++)
            if(t[i]>0)
                for(int j=i; j<(1<<m); j++)
                    if(t[j]>0&&(i|j)==(1<<m)-1){
                        x = t[i]; y  = t[j];
                        return true;
                    }

        return false;
    }

    public static void main(String[] args)throws Exception{
        n = nextInt(); m = nextInt();
        if(n==1){
            System.out.println(1+" "+1);
            return;
        }
        a = new int[n+1][m];
        t = new int[(1<<m)];
        for(int i=1; i<=n; i++)
            for(int j=0; j<m; j++)
                a[i][j] = nextInt();

        int l, r;
        l = 0; r = 1000000000;

        while(l<r){

            int mid = l + r + 1 >> 1;

            if(check(mid)) l = mid;

            else r = mid - 1;

        }
        check(l);
        System.out.println(x+" "+y);
    }
}


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

/*

4 1 2

1 16 10 3

18

19

13

15

Number of people, number of players chosen for the team, number of players chosen for the audience

Bonus that each person adds if they are put into the audience

For every person, bonus that they add if they are put into the team at position i

Bitmask DP - dp[i][j] = max score that Alice can get given the first i people and that j slots in the team are filled

*/

import java.util.*;

import java.io.*;

public class Main{

  public static int n; //total people in town

  public static int p; //players for the team

  public static int k; //players for the audience

  public static Person[] people;

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

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

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

    n = Integer.parseInt(details.nextToken());

    p = Integer.parseInt(details.nextToken());

    k = Integer.parseInt(details.nextToken());

    people = new Person[n];

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

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

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

      long[] ps = new long[p];

      for(int b = 0; b < p; b++) ps[b] = Long.parseLong(pos.nextToken());

      people[a] = new Person(a, Long.parseLong(ad.nextToken()), ps);

    }

    Arrays.sort(people);

    //System.out.println(Arrays.toString(people));

    long[][] dp = new long[n + 1][(1 << p)];

    for(long[] row : dp) Arrays.fill(row, -1000000000000000000L);

    dp[0][0] = 0;

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

      //forward dp? Try putting this person in the team at position b, or putting them in the audience (?) --> how to figure out which people are in the audience and not in the audience?

      for(int mask = 0; mask < (1 << p); mask++){

        //either occupied or not occupied, try putting this person at position pos

        dp[a][mask] = dp[a - 1][mask];

        int aud = a - 1 - Integer.bitCount(mask); //size of current audience

        if(aud < k) dp[a][mask] = Math.max(dp[a - 1][mask] + people[a - 1].add, dp[a][mask]);

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

          if((mask & (1 << pos)) > 0){

            dp[a][mask] = Math.max(dp[a][mask], dp[a - 1][mask - (1 << pos)] + people[a - 1].pAdd[pos]);

          }

          //can also try just putting this person in the audience, sorted from greatest contribution to the audience to least contribution to the audience

        }

      }

    }

    System.out.println(dp[n][(1 << p) - 1]);

    br.close();

  }

}

class Person implements Comparable<Person>{

  int id;

  long add;

  long[] pAdd;

  public Person(int i, long a, long[] pa){

    id = i;

    add = a;

    pAdd = pa;

  }

  public String toString(){

    return id + " id, adds " + add + " to audience, cost for each pos is " + Arrays.toString(pAdd);

  }

  public int compareTo(Person p){

    if(add > p.add) return -1;

    if(add < p.add) return 1;

    return id - p.id;

  }

}


G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk.  The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2
1 4
4 3
3 5
3 6
5 2
OutputCopy2
1 2 1 1 2 InputCopy4 2
3 1
1 4
1 2
OutputCopy1
1 1 1 InputCopy10 2
10 3
1 2
1 3
1 4
2 5
2 6
2 7
3 8
3 9
OutputCopy3
1 1 2 3 2 3 1 3 1

import java.io.*;

import java.util.*;

public class Codeforces

{

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

    {

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

        StringBuilder sb=new StringBuilder();

        String s[]=bu.readLine().split(" ");

        int n=Integer.parseInt(s[0]),k=Integer.parseInt(s[1]);

        int i,sz[]=new int[n];

        ArrayList<Road> g[]=new ArrayList[n];

        for(i=0;i<n;i++) g[i]=new ArrayList<>();

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

        {

            s=bu.readLine().split(" ");

            int u=Integer.parseInt(s[0])-1,v=Integer.parseInt(s[1])-1;

            g[u].add(new Road(v,i));

            g[v].add(new Road(u,i));

            sz[u]++; sz[v]++;

        }

        int l=1,r=n-1,ans=r,mid,f[]=new int[n];

        while(l<=r)

        {

            mid=(l+r)>>1;

            if(possible(sz,mid,k))

            {

                ans=mid;

                r=mid-1;

            }

            else l=mid+1;

        }

        fill(g,f,ans);

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

        for(i=0;i<n-1;i++) sb.append(f[i]+1+" ");

        sb.append("\n");

        System.out.print(sb);

    }

    static boolean possible(int g[],int m,int k)

    {

        int i,n=g.length,y=0;

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

        {

            if(g[i]>m) y++;

            if(y>k) return false;

        }

        return true;

    }

    static void fill(ArrayList<Road> g[],int f[],int m)

    {

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

        boolean v[]=new boolean[f.length];

        v[0]=true;

        int col=0,y=0,c[]=new int[f.length];

        for(Road x:g[0])

        {

            q.add(x.v);

            f[x.i]=col;

            v[x.v]=true;

            c[x.v]=col;

            col++; col%=m;

        }

        while(!q.isEmpty())

        {

            int p=q.poll();

            col=c[p];

            col++; col%=m;

            for(Road x:g[p])

            if(!v[x.v])

            {

                q.add(x.v);

                v[x.v]=true;

                c[x.v]=col;

                f[x.i]=col;

                col++; col%=m;

            }

        }

    }

    static class Road

    {

        int v,i;

        Road(int a,int b)

        {

            v=a;

            i=b;

        }

    }

}


B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6
1
10
19
9876
12345
1000000000
OutputCopy1
11
21
10973
13716
1111111111

import java.util.ArrayList;

import java.util.Scanner;

public class CF0911{

	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);

		int testCases = scan.nextInt();

		while(testCases>0){

			long currentMoney = scan.nextLong();

			int totalSpent = 0;

			while(currentMoney>=10){

				totalSpent += currentMoney - currentMoney%10;

				currentMoney = currentMoney/10 + currentMoney%10;

			}

			System.out.println(currentMoney + totalSpent);

			testCases--;

		}

	}

}


F1. Same Sum Blocks (Easy)time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that:  They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li.  For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk].  The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k.   The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤501≤n≤50) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7
4 1 2 2 1 5 3
OutputCopy3
7 7
2 3
4 5
InputCopy11
-5 -4 -3 -2 -1 0 1 2 3 4 5
OutputCopy2
3 4
1 1
InputCopy4
1 1 1 1
OutputCopy4
4 4
1 1
2 2
3 3

import java.util.*;

import java.lang.*;

import java.io.*;

import java.awt.*;

// U KNOW THAT IF THIS DAY WILL BE URS THEN NO ONE CAN DEFEAT U HERE................

//JUst keep faith in ur strengths ..................................................

// ASCII = 48 + i ;// 2^28 = 268,435,456  > 2* 10^8 // log 10 base 2 = 3.3219

// odd:: (x^2+1)/2 , (x^2-1)/2 ; x>=3// even:: (x^2/4)+1 ,(x^2/4)-1  x >=4

// FOR ANY ODD NO N : N,N-1,N-2

//ALL ARE PAIRWISE COPRIME

//THEIR COMBINED LCM IS PRODUCT OF ALL THESE NOS

// two consecutive odds are always coprime to each other

// two consecutive even have always gcd  = 2 ;

// Rectangle r = new Rectangle(int x , int y,int widht,int height)

//Creates a rect. with bottom left cordinates as (x, y) and top right as ((x+width),(y+height))

//BY DEFAULT Priority Queue is MIN in nature in java

//to use as max , just push with negative sign and change sign after removal

// We can make a sieve of max size 1e7 .(no time or space issue)

// In 1e7 starting nos we have about 66*1e4 prime nos

 public class Main

{

    // static int[] arr = new int[100002] ;

    // static int[] dp = new int[100002] ;

     static PrintWriter out;

	static class FastReader{

		BufferedReader br;

		StringTokenizer st;

		public FastReader(){

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

			out=new PrintWriter(System.out);

		}

		String next(){

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

				try{

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

				}

				catch (IOException e){

					e.printStackTrace();

				}

			}

			return st.nextToken();

		}

		int nextInt(){

			return Integer.parseInt(next());

		}

		long nextLong(){

			return Long.parseLong(next());

		}

		double nextDouble(){

			return Double.parseDouble(next());

		}

		String nextLine(){

			String str = "";

			try{

				str=br.readLine();

			}

			catch(IOException e){

				e.printStackTrace();

			}

			return str;

		}

	}

////////////////////////////////////////////////////////////////////////////////////

 public static int countDigit(long n)

    {

        return (int)Math.floor(Math.log10(n) + 1);

    }

/////////////////////////////////////////////////////////////////////////////////////////

 public static int sumOfDigits(long n)

 {

  if( n< 0)return -1 ;

  int sum = 0;

  while( n > 0)

  {

      sum = sum + (int)( n %10) ;

      n /= 10 ;

  }

  return sum ;

 }

 //////////////////////////////////////////////////////////////////////////////////////////////////

public static long arraySum(int[] arr , int start , int end)

{

    long ans = 0 ;

    for(int i = start ; i <= end  ; i++)ans += arr[i] ;

    return ans  ;

}

/////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////

public static void swapArray(int[] arr , int start , int end)

{

    while(start < end)

    {

        int temp = arr[start] ;

        arr[start] = arr[end];

        arr[end] = temp;

        start++ ;end-- ;

    }

}

//////////////////////////////////////////////////////////////////////////////////

static long factorial(long a)

{

    if(a== 0L || a==1L)return 1L ;

    return a*factorial(a-1L) ;

}

///////////////////////////////////////////////////////////////////////////////

public static int[][] rotate(int[][] input){

int n =input.length;

int m = input[0].length ;

int[][] output = new int [m][n];

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

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

		output [j][n-1-i] = input[i][j];

return output;

}

///////////////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////// ////////////////////////////////////////////////

public static boolean isPowerOfTwo(long n)

{

    if(n==0)

    return false;

if(((n ) & (n-1)) == 0 ) return true ;

else return false  ;

}

/////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////

public static String reverse(String input)

{

  StringBuilder str  = new StringBuilder("") ;

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

    {

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

    }

return str.toString() ;

}

///////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////////////

public static boolean isPossibleTriangle(int a  ,int b , int c)

{

      if( a + b > c && c+b > a && a +c > b)return true  ;

      else return false  ;

}

////////////////////////////////////////////////////////////////////////////////////////////

static long xnor(long num1, long num2) {

		if (num1 < num2) {

			long temp = num1;

			num1 = num2;

			num2 = temp;

		}

		num1 = togglebit(num1);

		return num1 ^ num2;

	}

	static long togglebit(long n) {

		if (n == 0)

			return 1;

		long i = n;

		n |= n >> 1;

		n |= n >> 2;

		n |= n >> 4;

		n |= n >> 8;

		n |= n >> 16;

		return i ^ n;

	}

///////////////////////////////////////////////////////////////////////////////////////////////

public static int xorOfFirstN(int n)

{

 if( n % 4 ==0)return n ;

 else if( n % 4 == 1)return 1 ;

 else if( n % 4 == 2)return n+1 ;

 else return 0 ;

}

//////////////////////////////////////////////////////////////////////////////////////////////

public static int gcd(int a, int b )

{

if(b==0)return a ;

else return gcd(b,a%b) ;

}

public static long gcd(long a, long b )

{

if(b==0)return a ;

else return gcd(b,a%b) ;

}

////////////////////////////////////////////////////////////////////////////////////

public static int lcm(int a, int b ,int c , int d )

{

int temp = lcm(a,b , c) ;

 int ans = lcm(temp ,d ) ;

return ans  ;

}

///////////////////////////////////////////////////////////////////////////////////////////

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

{

int temp = lcm(a,b) ;

int ans =  lcm(temp ,c) ;

return ans  ;

}

////////////////////////////////////////////////////////////////////////////////////////

public static int lcm(int a , int b )

{

int gc = gcd(a,b);

return (a/gc)*b ;

}

public static long lcm(long a , long b )

{

long gc = gcd(a,b);

return (a/gc)*b;

}

///////////////////////////////////////////////////////////////////////////////////////////

static boolean isPrime(long n)

{

      if(n==1)

      {

            return false  ;

      }

      boolean ans =  true  ;

      for(long i = 2L; i*i <= n ;i++)

      {

            if(n% i ==0)

            {

                  ans = false  ;break ;

            }

      }

      return ans  ;

}

static boolean isPrime(int n)

{

      if(n==1)

      {

            return false  ;

      }

      boolean ans =  true  ;

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

      {

            if(n% i ==0)

            {

                  ans = false  ;break ;

            }

      }

      return ans  ;

}

///////////////////////////////////////////////////////////////////////////

static int sieve =  1000000 ;

static boolean[] prime =  new boolean[sieve + 1] ;

public static void sieveOfEratosthenes()

    {

        // FALSE == prime

        // TRUE ==  COMPOSITE

        // FALSE== 1

        // time complexity = 0(NlogLogN)== o(N)

        // gives prime nos bw 1 to N

        for(int i = 4; i<= sieve ; i++)

        {

            prime[i] = true  ;

            i++ ;

        }

        for(int p = 3; p*p <= sieve; p++)

        {

            if(prime[p] == false)

            {

                for(int i = p*p; i <= sieve; i += p)

                    prime[i] = true;

            }

            p++ ;

        }

    }

///////////////////////////////////////////////////////////////////////////////////

public static void sortD(int[] arr , int s  , int e)

{

      sort(arr ,s , e) ;

      int i =s ; int j = e  ;

      while( i < j)

      {

            int temp = arr[i] ;

            arr[i] =arr[j] ;

            arr[j] = temp ;

            i++ ; j-- ;

      }

      return ;

}

/////////////////////////////////////////////////////////////////////////////////////////

public static long countSubarraysSumToK(long[] arr ,long sum )

    {

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

      int n = arr.length ;

      long prefixsum = 0 ;

      long count = 0L ;

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

      {

          prefixsum  = prefixsum +  arr[i] ;

          if(sum == prefixsum)count = count+1 ;

          if(map.containsKey(prefixsum -sum))

          {

              count = count + map.get(prefixsum -sum) ;

          }

          if(map.containsKey(prefixsum ))

          {

              map.put(prefixsum , map.get(prefixsum) +1 );

          }

          else{

              map.put(prefixsum , 1L );

          }

      }

      return count  ;

    }

///////////////////////////////////////////////////////////////////////////////////////////////

// KMP ALGORITHM : TIME COMPL:O(N+M)

// FINDS THE OCCURENCES OF PATTERN AS A  SUBSTRING IN STRING

//RETURN THE ARRAYLIST OF INDEXES

// IF SIZE OF LIST IS ZERO MEANS PATTERN IS NOT PRESENT IN STRING

public static ArrayList<Integer> kmpAlgorithm(String str , String pat)

     {

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

        int n = str.length() ;

        int m = pat.length() ;

        String q = pat + "#" + str ;

        int[] lps  =new int[n+m+1] ;

         longestPefixSuffix(lps, q,(n+m+1)) ;

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

         {

             if(lps[i] == m)

             {

                 list.add(i-2*m) ;

             }

         }

        return list ;

    }

public static void longestPefixSuffix(int[] lps ,String str , int n)

    {

        lps[0] =  0 ;

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

        {

          int l = lps[i-1] ;

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

          {

              l = lps[l-1] ;

          }

          if(str.charAt(i) == str.charAt(l))

          {

              l++ ;

          }

          lps[i] = l ;

        }

    }

///////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////////////////

 // CALCULATE TOTIENT Fn FOR ALL VALUES FROM 1 TO n

    // TOTIENT(N) = count of nos less than n and grater than 1 whose gcd with n is 1

    // or n and the no  will be coprime in nature

    //time : O(n*(log(logn)))

    public static void eulerTotientFunction(int[] arr ,int n )

    {

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

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

      {

          if(arr[i] == i)

          {

              arr[i] =i-1 ;

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

              {

                  arr[j] = (arr[j]*(i-1))/i ;

              }

          }

      }

      return  ;

    }

/////////////////////////////////////////////////////////////////////////////////////////////

public static long nCr(int n,int k)

{

    long ans=1L;

    k=k>n-k?n-k:k;

    int j=1;

    for(;j<=k;j++,n--)

    {

        if(n%j==0)

        {

            ans*=n/j;

        }else

        if(ans%j==0)

        {

            ans=ans/j*n;

        }else

        {

            ans=(ans*n)/j;

        }

    }

    return ans;

}

///////////////////////////////////////////////////////////////////////////////////////////

public static ArrayList<Integer> allFactors(int n)

{

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

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

    {

          if( n % i == 0)

          {

              if(i*i == n)

              {

                    list.add(i) ;

              }

              else{

                    list.add(i) ;

                    list.add(n/i) ;

              }

          }

    }

     return list ;

}

public static ArrayList<Long> allFactors(long n)

{

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

    for(long i = 1L; i*i <= n ;i++)

    {

          if( n % i == 0)

          {

              if(i*i == n)

              {

                    list.add(i) ;

              }

              else{

                    list.add(i) ;

                    list.add(n/i) ;

              }

          }

    }

     return list ;

}

////////////////////////////////////////////////////////////////////////////////////////////////////

  static final int MAXN = 1000001;

    static int spf[] = new int[MAXN];

    static void sieve()

    {

        spf[1] = 1;

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

            spf[i] = i;

        for (int i=4; i<MAXN; i+=2)

            spf[i] = 2;

        for (int i=3; i*i<MAXN; i++)

        {

            if (spf[i] == i)

            {

                for (int j=i*i; j<MAXN; j+=i)

                    if (spf[j]==j)

                        spf[j] = i;

            }

        }

    }

    static ArrayList<Integer> getPrimeFactorization(int x)

    {

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

        while (x != 1)

        {

            ret.add(spf[x]);

            x = x / spf[x];

        }

        return ret;

    }

 //////////////////////////////////////////////////////////////////////////////////////////////////

 //////////////////////////////////////////////////////////////////////////////////////////////////

public static void merge(int arr[], int l, int m, int r)

    {

        // Find sizes of two subarrays to be merged

        int n1 = m - l + 1;

        int n2 = r - m;

        /* Create temp arrays */

        int L[] = new int[n1];

        int R[] = new int[n2];

       //Copy data to temp arrays

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

            L[i] = arr[l + i];

        for (int j=0; j<n2; ++j)

            R[j] = arr[m + 1+ j];

        /* Merge the temp arrays */

        // Initial indexes of first and second subarrays

        int i = 0, j = 0;

        // Initial index of merged subarry array

        int k = l;

        while (i < n1 && j < n2)

        {

            if (L[i] <= R[j])

            {

                arr[k] = L[i];

                i++;

            }

            else

            {

                arr[k] = R[j];

                j++;

            }

            k++;

        }

        /* Copy remaining elements of L[] if any */

        while (i < n1)

        {

            arr[k] = L[i];

            i++;

            k++;

        }

        /* Copy remaining elements of R[] if any */

        while (j < n2)

        {

            arr[k] = R[j];

            j++;

            k++;

        }

    }

    // Main function that sorts arr[l..r] using

    // merge()

  public static void sort(int arr[], int l, int r)

    {

        if (l < r)

        {

            // Find the middle point

            int m = (l+r)/2;

            // Sort first and second halves

            sort(arr, l, m);

            sort(arr , m+1, r);

            // Merge the sorted halves

            merge(arr, l, m, r);

        }

    }

public static void sort(long arr[], int l, int r)

    {

        if (l < r)

        {

            // Find the middle point

            int m = (l+r)/2;

            // Sort first and second halves

            sort(arr, l, m);

            sort(arr , m+1, r);

            // Merge the sorted halves

            merge(arr, l, m, r);

        }

    }

public static void merge(long arr[], int l, int m, int r)

    {

        // Find sizes of two subarrays to be merged

        int n1 = m - l + 1;

        int n2 = r - m;

        /* Create temp arrays */

        long L[] = new long[n1];

        long R[] = new long[n2];

        //Copy data to temp arrays

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

            L[i] = arr[l + i];

        for (int j=0; j<n2; ++j)

            R[j] = arr[m + 1+ j];

        /* Merge the temp arrays */

        // Initial indexes of first and second subarrays

        int i = 0, j = 0;

        // Initial index of merged subarry array

        int k = l;

        while (i < n1 && j < n2)

        {

            if (L[i] <= R[j])

            {

                arr[k] = L[i];

                i++;

            }

            else

            {

                arr[k] = R[j];

                j++;

            }

            k++;

        }

        /* Copy remaining elements of L[] if any */

        while (i < n1)

        {

            arr[k] = L[i];

            i++;

            k++;

        }

        /* Copy remaining elements of R[] if any */

        while (j < n2)

        {

            arr[k] = R[j];

            j++;

            k++;

        }

    }

 /////////////////////////////////////////////////////////////////////////////////////////

	public static long knapsack(int[] weight,long value[],int maxWeight){

        int n=  value.length ;

	//dp[i] stores the profit with KnapSack capacity "i"

  long []dp = new long[maxWeight+1];

    //initially profit with 0 to W KnapSack capacity is 0

    Arrays.fill(dp, 0);

    // iterate through all items

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

        //traverse dp array from right to left

        for(int j = maxWeight; j >= weight[i]; j--)

            dp[j] = Math.max(dp[j] , value[i] + dp[j - weight[i]]);

    /*above line finds out maximum of dp[j](excluding ith element value)

    and val[i] + dp[j-wt[i]] (including ith element value and the

    profit with "KnapSack capacity - ith element weight") */

    return dp[maxWeight];

	}

///////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////

// to return max sum of any subarray in given array

public static long kadanesAlgorithm(long[] arr)

{

    if(arr.length == 0)return  0 ;

      long[] dp = new long[arr.length] ;

      dp[0] = arr[0] ;

      long max =  dp[0] ;

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

      {

            if(dp[i-1] > 0)

            {

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

            }

            else{

                  dp[i] = arr[i] ;

            }

            if(dp[i] >  max)max = dp[i] ;

      }

      return max  ;

}

/////////////////////////////////////////////////////////////////////////////////////////////

public static long kadanesAlgorithm(int[] arr)

{

     if(arr.length == 0)return  0 ;

      long[] dp = new long[arr.length] ;

      dp[0] = arr[0] ;

      long max =  dp[0] ;

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

      {

            if(dp[i-1] > 0)

            {

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

            }

            else{

                  dp[i] = arr[i] ;

            }

            if(dp[i] >  max)max = dp[i] ;

      }

      return max  ;

}

///////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////

//TO GENERATE ALL(DUPLICATE ALSO EXIST) PERMUTATIONS OF A STRING

// JUST CALL generatePermutation( str,  start,  end) start :inclusive ,end : exclusive

//Function for swapping the characters at position I with character at position j

    public static String swapString(String a, int i, int j) {

        char[] b =a.toCharArray();

        char ch;

        ch = b[i];

        b[i] = b[j];

        b[j] = ch;

        return String.valueOf(b);

    }

//Function for generating different permutations of the string

    public static void generatePermutation(String str, int start, int end)

    {

        //Prints the permutations

        if (start == end-1)

            System.out.println(str);

        else

        {

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

            {

                //Swapping the string by fixing a character

                str = swapString(str,start,i);

                //Recursively calling function generatePermutation() for rest of the characters

                generatePermutation(str,start+1,end);

                //Backtracking and swapping the characters again.

                str = swapString(str,start,i);

            }

        }

    }

////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////

public static long factMod(long n, long mod) {

    if (n <= 1) return 1;

    long ans = 1;

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

      ans = (ans * i) % mod;

    }

    return ans;

  }

/////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////

public static long power(int a  ,int b)

    {

        //time comp : o(logn)

        long x = (long)(a) ;

         long n = (long)(b) ;

        if(n==0)return 1 ;

        if(n==1)return x;

        long ans =1L  ;

      while(n>0)

      {

          if(n % 2 ==1)

          {

              ans = ans *x ;

          }

          n = n/2L ;

          x =  x*x ;

      }

      return ans ;

    }

    public static long power(long a  ,long b)

    {

        //time comp : o(logn)

        long x = (a) ;

         long n = (b) ;

        if(n==0)return 1L ;

        if(n==1)return x;

        long ans =1L  ;

      while(n>0)

      {

          if(n % 2 ==1)

          {

              ans = ans *x ;

          }

          n = n/2L ;

          x =  x*x ;

      }

      return ans ;

    }

////////////////////////////////////////////////////////////////////////////////////////////////////

public static long powerMod(long x, long n, long mod) {

    //time comp : o(logn)

    if(n==0)return 1L ;

        if(n==1)return x;

    long ans = 1;

    while (n > 0) {

      if (n % 2 == 1) ans = (ans * x) % mod;

      x = (x * x) % mod;

      n /= 2;

    }

    return ans;

  }

//////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////

/*

lowerBound - finds largest element equal or less than value paased

upperBound - finds smallest element equal or more than value passed

if not present return -1;

*/

public static long lowerBound(long[] arr,long k)

	{

		long ans=-1;

		int start=0;

		int end=arr.length-1;

		while(start<=end)

		{

			int mid=(start+end)/2;

			if(arr[mid]<=k)

			{

				ans=arr[mid];

				start=mid+1;

			}

			else

			{

				end=mid-1;

			}

		}

		return ans;

	}

	public static int lowerBound(int[] arr,int k)

	{

		int ans=-1;

		int start=0;

		int end=arr.length-1;

		while(start<=end)

		{

			int mid=(start+end)/2;

			if(arr[mid]<=k)

			{

				ans=arr[mid];

				start=mid+1;

			}

			else

			{

				end=mid-1;

			}

		}

		return ans;

	}

	public static long upperBound(long[] arr,long k)

	{

		long ans=-1;

		int start=0;

		int end=arr.length-1;

		while(start<=end)

		{

			int mid=(start+end)/2;

			if(arr[mid]>=k)

			{

				ans=arr[mid];

				end=mid-1;

			}

			else

			{

				start=mid+1;

			}

		}

		return ans;

	}

	public static int upperBound(int[] arr,int k)

	{

		int ans=-1;

		int start=0;

		int end=arr.length-1;

		while(start<=end)

		{

			int mid=(start+end)/2;

			if(arr[mid]>=k)

			{

				ans=arr[mid];

				end=mid-1;

			}

			else

			{

				start=mid+1;

			}

		}

		return ans;

	}

//////////////////////////////////////////////////////////////////////////////////////////

public static void printArray(int[] arr , int si ,int ei)

{

    for(int i = si  ; i  <= ei ; i++)

    {

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

    }

}

public static void printArrayln(int[] arr , int si ,int ei)

{

    for(int i = si  ; i  <= ei ; i++)

    {

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

    }

    out.println() ;

}

public static void printLArray(long[] arr , int si , int ei)

{

    for(int i = si ; i  <= ei ; i++)

    {

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

    }

}

public static void printLArrayln(long[] arr , int si , int ei)

{

    for(int i = si ; i  <= ei ; i++)

    {

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

    }

    out.println() ;

}

public static void printtwodArray(int[][] ans)

{

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

    {

        for(int j  = 0 ; j <  ans[0].length ; j++)out.print(ans[i][j] +" ");

        out.println() ;

    }

    out.println() ;

}

   static long modPow(long a, long x, long p) {

    //calculates a^x mod p in logarithmic time.

    a = a % p ;

    if(a == 0)return 0L ;

    long res = 1L;

    while(x > 0) {

        if( x % 2 != 0) {

            res = (res * a) % p;

        }

        a = (a * a) % p;

        x =x/2;

    }

    return res;

}

  static long modInverse(long a, long p) {

    //calculates the modular multiplicative of a mod p.

    //(assuming p is prime).

    return modPow(a, p-2, p);

}

 static long[] factorial =  new long[1000001] ;

 static void modfac(long mod)

 {

     factorial[0]=1L ; factorial[1]=1L ;

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

     {

         factorial[i] = factorial[i-1] *(long)(i) ;

          factorial[i] = factorial[i] % mod ;

     }

 }

static long modBinomial(long n, long r, long p) {

// calculates C(n,r) mod p (assuming p is prime).

  if(n < r) return 0L ;

    long num = factorial[(int)(n)] ;

    long den = (factorial[(int)(r)]*factorial[(int)(n-r)]) %  p ;

    long ans  = num*(modInverse(den,p)) ;

    ans = ans % p ;

    return ans  ;

}

 static void update(int val , long[] bit ,int n)

 {

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

     {

         bit[val]++ ;

     }

 }

 static long query(int val , long[] bit , int n)

 {

     long ans = 0L;

     for( ; val >=1 ; val-=(val&(-val))  )ans += bit[val];

     return ans ;

 }

static int countSetBits(long n)

    {

        int count = 0;

        while (n > 0) {

            n = (n) & (n - 1L);

            count++;

        }

        return count;

    }

static int abs(int x)

{

    if(x < 0)x = -1*x ;

    return x ;

}

static long abs(long x)

{

    if(x < 0)x = -1L*x ;

    return x ;

}

////////////////////////////////////////////////////////////////////////////////////////////////

static void p(int val)

{

    out.print(val) ;

}

static void p()

{

    out.print(" ") ;

}

static void pln(int val)

{

    out.println(val) ;

}

static void pln()

{

    out.println() ;

}

static void p(long val)

{

    out.print(val) ;

}

static void pln(long val)

{

    out.println(val) ;

}

////////////////////////////////////////////////////////////////////////////////////////////

 // calculate total no of nos greater than or equal to key in  sorted array arr

static  int bs(int[] arr, int s ,int e  ,int key)

{

    if( s> e)return 0 ;

     int mid = (s+e)/2 ;

        if(arr[mid] <key)

        {

            return bs(arr ,mid+1,e , key) ;

        }

        else{

             return bs(arr ,s ,mid-1, key)  + e-mid+1;

        }

}

// static ArrayList<Integer>[] adj ;

// static int mod= 1000000007 ;

//////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////

public static void solve()

{

FastReader scn = new FastReader() ;

//Scanner scn = new Scanner(System.in);

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

// product of first 11 prime nos is greater than 10 ^ 12;

//sieve() ;

//ArrayList<Integer> arr[] = new ArrayList[n] ;

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

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

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

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

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

//ArrayList<String> lists = new ArrayList<>() ;

HashMap<Integer,ArrayList<Pair>> map = new HashMap<>() ;

//HashMap<Long,Long> map = new HashMap<>() ;

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

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

//HashMap<String,Integer> maps = new HashMap<>() ;

//HashMap<Integer,Boolean> mapb = new HashMap<>() ;

//HashMap<Point,Integer> point = new HashMap<>() ;

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

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

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

StringBuilder sb =new StringBuilder("") ;

//Collections.sort(list);

//if(map.containsKey(arr[i]))map.put(arr[i] , map.get(arr[i]) +1 ) ;

//else map.put(arr[i],1) ;

// if(map.containsKey(temp))map.put(temp , map.get(temp) +1 ) ;

// else map.put(temp,1) ;

//int bit  =Integer.bitCount(n);

// gives total no of set bits in n;

// Arrays.sort(arr, new Comparator<Pair>() {

// 			@Override

// 			public int compare(Pair a, Pair b) {

// 				if (a.first != b.first) {

// 					return a.first - b.first; // for increasing order of first

// 				}

// 				return a.second - b.second ; //if first is same then sort on second basis

// 			}

// 		});

int testcase = 1;

 //testcase = scn.nextInt() ;

for(int testcases =1  ; testcases <= testcase ;testcases++)

{

 //if(map.containsKey(arr[i]))map.put(arr[i],map.get(arr[i])+1) ;else map.put(arr[i],1) ;

 //if(map.containsKey(temp))map.put(temp,map.get(temp)+1) ;else map.put(temp,1) ;

 //adj = new ArrayList[n] ;

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

// {

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

// }

// long n = scn.nextLong() ;

//String s = scn.next() ;

int n= scn.nextInt() ;

int[] arr= new int[n] ;

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

{

    arr[i]= scn.nextInt();

}

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

{

    int sum = 0 ;

    for(int l =r ;l>= 0 ;l--)

    {

       sum = sum + arr[l] ;

       if(map.containsKey(sum))

       {

           map.get(sum).add(new Pair(l,r)) ;

       }

       else{

           map.put(sum,new ArrayList<Pair>());

            map.get(sum).add(new Pair(l,r)) ;

       }

    }

}

 ArrayList<Pair> ans = null ;

 int bestcount = 0 ;

for(int x : map.keySet())

{

    ArrayList<Pair> curr = map.get(x) ;

    ArrayList<Pair> now = new ArrayList<Pair>() ;

    int r=-1  ;

    int count = 0 ;

    for(Pair seg : curr)

    {

      if(seg.first > r)

      {

          count++ ;

          now.add(seg) ;

          r= seg.second  ;

      }

    }

    if(count > bestcount)

    {

        ans = now ;

        bestcount = count  ;

    }

}

pln(bestcount) ;

if(bestcount >0)

{

for(Pair x :  ans)

{

    out.println((x.first+1) +" " +( x.second+1)) ;

}

}

//out.println(ans) ;

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

//out.println("Case #" + testcases + ": "  + ans ) ;

//out.println("@") ;

set.clear() ;

sb.delete(0 , sb.length()) ;

list.clear() ;lista.clear() ;listb.clear() ;

map.clear() ;

mapx.clear() ;

mapy.clear() ;

setx.clear() ;sety.clear() ;

} // test case  end loop

out.flush() ;

} // solve fn ends

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

{

solve() ;

}

}

 class Pair

{

  int first ;

int second  ;

   public Pair(int l , int r)

   {

       first = l ;second = r ;

   }

@Override

	public String toString() {

	String ans = "" ;

	ans  += this.first ;

	ans += " ";

	ans += this.second ;

	return ans  ;

	}

}


D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n)  — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n)  — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
OutputCopy3
InputCopy5 4 2
2 4
1 2
2 3
3 4
4 5
OutputCopy3
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33.   The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.

import java.io.*;

import java.util.*;

public class Main {

    static List<Integer>[] g;

    static void bfs(int u, int[] dis) {

        dis[u] = 0;

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

        q.add(u);

        while(!q.isEmpty()) {

            int v = q.peek();

            q.remove();

            for(int w: g[v])

                if(dis[w] > dis[v] + 1) {

                    dis[w] = dis[v] + 1;

                    q.add(w);

                }

        }

    }

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

        Scanner in = new Scanner(System.in);

        int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();

        g = new List[n];

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

            g[i] = new ArrayList<Integer>();

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

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

            a.add(in.nextInt() - 1);

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

            int u = in.nextInt() - 1, v = in.nextInt() - 1;

            g[u].add(v);

            g[v].add(u);

        }

        int[] d1 = new int[n];

        int[] dn = new int[n];

        Arrays.fill(d1, 100000000);

        Arrays.fill(dn, 100000000);

        bfs(0, d1);

        bfs(n - 1, dn);

        int best = 0, mx = -100000000;

        Collections.sort(a, new Comparator<Integer>() {

            @Override public int compare(Integer b, Integer c) {

                return d1[b] - dn[b] - d1[c] + dn[c];

            }

        });

        for(int e: (List<Integer>) a) {

            best = Math.max(best, mx + dn[e]);

            mx = Math.max(mx, d1[e]);

        }

        System.out.println(Math.min(best + 1, d1[n - 1]));

    }

}


D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.You have to answer tt independent test cases. InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8
1 2 3
123 321 456
5 10 15
15 18 21
100 100 101
1 22 29
3 19 38
6 30 46
OutputCopy1
1 1 3
102
114 228 456
4
4 8 16
6
18 18 18
1
100 100 100
7
1 22 22
2
1 19 38
8
6 24 48

/*

        "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 = 20000, INF = (int) 1e9;

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

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

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

        sc = new FastReader();

        precompute();

        int test = sc.nextInt();

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

            solve();

        }

        out.close();

    }

    private static void precompute() {

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

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

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

                    list.add(new int[]{i, j, k});

                }

            }

        }

    }

    private static void solve() {

        int a = sc.nextInt();

        int b = sc.nextInt();

        int c = sc.nextInt();

        int[] res = new int[]{0, 0, 0};

        int minOperations = INF;

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

            int[] curr = list.get(i);

            int operations = Math.abs(curr[0] - a) + Math.abs(curr[1] - b) + Math.abs(curr[2] - c);

            if (minOperations > operations) {

                minOperations = operations;

                res = curr;

            }

        }

        out.println(minOperations);

        out.println(res[0] + " " + res[1] + " " + res[2]);

    }

    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;

        }

    }

}


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

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

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

        var n = scanner.nextInt();
        var target = new int[n + 1][n + 1];
        var blocks = new ArrayList<Integer>();
        var starts = new HashMap<Integer, List<Integer>>();
        for (int x = 1; x <= n; x++) {
            for (int y = 1; y <= n; y++) {
                var h = hash(n, x, y);
                var x1 = scanner.nextInt();
                var y1 = scanner.nextInt();
                int h1 = hash(n, x1, y1);
                target[x][y] = h1;
                if (x == x1 && y == y1) {
                    blocks.add(h1);
                } else if (x1 >= 1) {
                    starts.compute(h1, (k, v) -> {
                        if (v == null) {
                            v = new ArrayList<>();
                        }
                        v.add(h);
                        return v;
                    });
                }
            }
        }
        var ans = new char[n + 1][n + 1];
        var valid = true;
        // 最起码，所有starts的终点的终点都是自己
        for (Integer t : starts.keySet()) {
            if (t < 0) {
                valid = false;
                break;
            }
            var xy = dehash(t, n);
            if (target[xy[0]][xy[1]] != t) {
                valid = false;
                break;
            }
        }
        if (!valid) {
            writer.println("INVALID");
        } else {
            // 首先，所有的blocks要能够走到到自己的所有出发点。
            for (Integer block : blocks) {
                bfs(block, ans, n, target);
                if (!allStartsReach(block, starts, ans, n)) {
                    valid = false;
                    break;
                }
            }
            if (!valid) {
                writer.println("INVALID");
            } else {
                // 其次所有的(-1,-1)不能是孤立的。
                if (!fillInfinite(ans, n)) {
                    writer.println("INVALID");
                } else {
                    writer.println("VALID");
                    for (int x = 1; x <= n; x++) {
                        writer.println(Arrays.copyOfRange(ans[x], 1, n + 1));
                    }
                }
            }
        }

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

    private static boolean fillInfinite(char[][] ans, int n) {
        for (int x = 1; x <= n; x++) {
            for (int y = 1; y <= n; y++) {
                if (ans[x][y] == 0) {
                    var q = new LinkedList<int[]>();
                    q.add(new int[]{x, y});
                    {
                        for (int i = 0; i < 4; i++) {
                            var x1 = x + dx[i];
                            var y1 = y + dy[i];
                            if (1 <= x1 && x1 <= n && 1 <= y1 && y1 <= n && ans[x1][y1] == 0) {
                                q.add(new int[]{x1, y1});
                                ans[x][y] = dn[i];
                                ans[x1][y1] = dn[3 - i];
                                break;
                            }
                        }
                    }
                    if (q.size() < 2) {
                        return false;
                    }
                    while (!q.isEmpty()) {
                        var xy = q.poll();
                        for (int i = 0; i < 4; i++) {
                            var x1 = xy[0] + dx[i];
                            var y1 = xy[1] + dy[i];
                            if (1 <= x1 && x1 <= n && 1 <= y1 && y1 <= n && ans[x1][y1] == 0) {
                                ans[x1][y1] = dn[3 - i];
                                q.add(new int[]{x1, y1});
                            }
                        }
                    }
                }
            }
        }
        return true;
    }

    private static boolean allStartsReach(Integer block, HashMap<Integer, List<Integer>> starts, char[][] ans, int n) {
        List<Integer> ss = starts.get(block);
        if (ss == null) {
            return true;
        }
        for (Integer start : ss) {
            var xy = dehash(start, n);
            if (ans[xy[0]][xy[1]] == 0) {
                return false;
            }
        }
        return true;
    }

    static int[] dx = new int[]{1, 0, 0, -1};
    static int[] dy = new int[]{0, 1, -1, 0};
    static char[] dn = new char[]{'D', 'R', 'L', 'U'};

    private static void bfs(int block, char[][] ans, int n, int[][] target) {
        var q = new LinkedList<int[]>();
        {
            var xy = dehash(block, n);
            ans[xy[0]][xy[1]] = 'X';
            q.add(xy);
        }
        while (!q.isEmpty()) {
            var xy = q.poll();
            for (int i = 0; i < 4; i++) {
                var x1 = xy[0] + dx[i];
                var y1 = xy[1] + dy[i];
                if (1 <= x1 && x1 <= n && 1 <= y1 && y1 <= n && target[x1][y1] == block && ans[x1][y1] == 0) {
                    ans[x1][y1] = dn[3 - i];
                    q.add(new int[]{x1, y1});
                }
            }
        }
    }

    private static int[] dehash(int block, int n) {
        return new int[]{block / (n + 1), block % (n + 1)};
    }

    private static int hash(int n, int x, int y) {
        return x * (n + 1) + y;
    }

    public static class BufferedScanner {
        BufferedReader br;
        StringTokenizer st;

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

        public BufferedScanner() {
            this(new InputStreamReader(System.in));
        }

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

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

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

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

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

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

    }

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

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

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

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

}


D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlogn) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3
3 <<
7 >><>><
5 >>><
OutputCopy1 2 3
1 2 3
5 4 3 7 2 1 6
4 3 1 7 5 2 6
4 3 2 1 5
5 4 2 1 3
NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.

import java.io.*;

import java.util.*;

public class Main {

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

	{

		FastScanner f = new FastScanner();

		int ttt=1;

		ttt=f.nextInt();

		PrintWriter out=new PrintWriter(System.out);

		for(int tt=0;tt<ttt;tt++) {

			int n=f.nextInt();

			char[] l=f.next().toCharArray();

			int num = n, last = 0;

			int[] ans=new int[n];

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

			{

				if (i == n - 1 || l[i] == '>')

				{

					for (int j = i; j >= last; j--)

						ans[j] = num--;

					last = i + 1;

				}

			}

			for (int i:ans) out.print(i+" ");

			out.println();

			ans=new int[n];

			num = 1;

			last = 0;

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

			{

				if (i == n - 1 || l[i] == '<')

				{

					for (int j = i; j >= last; j--)

						ans[j] = num++;

					last = i + 1;

				}

			}

			for (int i:ans) out.print(i+" ");

			out.println();

		}

		out.close();

	}

	static void sort(int[] p) {

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

        for (int i: p) q.add( i);

        Collections.sort(q);

        for (int i = 0; i < p.length; i++) p[i] = q.get(i);

    }

	static class FastScanner {

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

		StringTokenizer st=new StringTokenizer("");

		String next() {

			while (!st.hasMoreTokens())

				try {

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

				} catch (IOException e) {

					e.printStackTrace();

				}

			return st.nextToken();

		}

		int nextInt() {

			return Integer.parseInt(next());

		}

		int[] readArray(int n) {

			int[] a=new int[n];

			for (int i=0; i<n; i++) a[i]=nextInt();

			return a;

		}

		long nextLong() {

			return Long.parseLong(next());

		}

		double nextDouble() {

			return Double.parseDouble(next());

		}

		long[] readLongArray(int n) {

			long[] a=new long[n];

			for (int i=0; i<n; i++) a[i]=nextLong();

			return a;

		}

	}

}


B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5
3
1 2 1
5
1 2 2 3 2
3
1 1 2
4
1 2 2 1
10
1 1 2 2 3 3 4 4 5 5
OutputCopyYES
YES
NO
YES
NO
NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.

import java.util.Scanner;

public class Codeforces1324 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = Integer.parseInt(in.nextLine());
        StringBuffer sb = new StringBuffer();

        for (int i=0;i < n;++i) {
            int m = Integer.parseInt(in.nextLine());
            String[] items = in.nextLine().split(" ");
            int j = 0;
            boolean found = false;
            while (j < m - 2) {
                for (int k = m - 1; k > j + 1;--k) {
                    if (items[j].equals(items[k])) {
                        found = true;
                        break;
                    }
                }
                if (found)                         {
                    sb.append("YES").append("\n");
                    break;
                } else {
                    ++j;
                }
            }
            if (!found)  sb.append("NO").append("\n");
        }
        System.out.print(sb.substring(0, sb.length() - 1));

    }
}


B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6
3 2
3 2 1
1 2
4 2
4 1 2 3
3 2
5 1
1 2 3 4 5
1
4 2
2 1 4 3
1 3
4 2
4 3 2 1
1 3
5 2
2 1 2 3 3
1 4
OutputCopyYES
NO
YES
YES
NO
YES

import java.io.BufferedOutputStream;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.math.BigInteger;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.HashMap;

import java.util.Map;

import java.util.StringTokenizer;

import java.util.function.Supplier;

import java.util.stream.Collectors;

public class cf {

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

    public static PrintWriter out;

    public static int cnt;

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

    public static class MyScanner {

        BufferedReader br;

        StringTokenizer st;

        public MyScanner() {

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

        }

        String next() {

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

                try {

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

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            return st.nextToken();

        }

        int nextInt() {

            return Integer.parseInt(next());

        }

        long nextLong() {

            return Long.parseLong(next());

        }

        double nextDouble() {

            return Double.parseDouble(next());

        }

        String nextLine(){

            String str = "";

        try {

            str = br.readLine();

        } catch (IOException e) {

            e.printStackTrace();

        }

        return str;

        }

	        }

    static boolean isPrime(int n)

{

    // Corner cases

    if (n <= 1)

        return false;

    if (n <= 3)

        return true;

    // This is checked so that we can skip

    // middle five numbers in below loop

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

        return false;

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

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

            return false;

    return true;

}

    public static int reverseBits(int n)

    {

        int rev = 0;

        // traversing bits of 'n'

        // from the right

        while (n > 0)

        {

            // bitwise left shift

            // 'rev' by 1

            rev <<= 1;

            // if current bit is '1'

            if ((int)(n & 1) == 1)

                rev ^= 1;

            // bitwise right shift

            //'n' by 1

            n >>= 1;

        }

        // required number

        return rev;

    }

    public static ArrayList<String> getSequence(String str)

    {

        // If string is empty

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

            // Return an empty arraylist

            ArrayList<String> empty = new ArrayList<>();

            empty.add("");

            return empty;

        }

        // Take first character of str

        char ch = str.charAt(0);

        // Take sub-string starting from the

        // second character

        String subStr = str.substring(1);

        // Recursive call for all the sub-sequences

        // starting from the second character

        ArrayList<String> subSequences =

                              getSequence(subStr);

        // Add first character from str in the beginning

        // of every character from the sub-sequences

        // and then store it into the resultant arraylist

        ArrayList<String> res = new ArrayList<>();

        for (String val : subSequences) {

            res.add(val);

            res.add(ch + val);

        }

        return res;

    }

	public static void main(String[] args)

	{

		MyScanner sc = new MyScanner();

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

		StringBuilder sb = new StringBuilder();

		int t=sc.nextInt();

		while(t-->0)

		{

			int n=sc.nextInt();

			int m=sc.nextInt();

			long arr[]=new long[n];

			long brr[]=new long[m];

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

			{

				arr[i]=sc.nextLong();

			}

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

			{

				brr[i]=sc.nextLong();

			}

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

			Arrays.sort(brr);

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

			{

				int i1=(int) brr[i]-1;

				while(i+1<m &&brr[i+1]-brr[i]==1 )

				{

					i++;

				}

				int i2=(int)brr[i];

				if(i2>i1)

				{

					long crr[]=Arrays.copyOfRange(arr,i1, i2+1);

					Arrays.sort(crr);

					int k=0;

					for(int i3=i1;i3<=i2;i3++)

					{

						arr[i3]=crr[k];

						k++;

					}

				}

				else

				{

					long a=Math.max(arr[i1],arr[i1+1]);

					long b=Math.min(arr[i1],arr[i1+1]);

					arr[i1+1]=a;

					arr[i1]=b;

				}

			}

			long crr[]=Arrays.copyOf(arr, n);

			Arrays.sort(crr);

			if(Arrays.equals(arr,crr))

			{

				out.println("YES");

			}

			else

			{

				out.println("NO");

			}

		}

		out.close();

	}

}