import java.util.*;

/**
 * A Main
 *
 * @date 2020.09.19
 * @author 焼き鮭 <yaki-shake@up-tri.me>
 */

public class Main {
  Scanner sc;

  public static void main(String[] args) {
    new Main().execute();
  }

  public void execute() {
    this.sc = new Scanner(System.in);
    String _s = sc.next();
    String[] s = _s.split("");
    System.out.println(_s + (s[s.length - 1].equals("s") ? "es" : "s"));
  }
}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 100 points

Problem Statement

In the Kingdom of AtCoder, people use a language called Taknese, which uses lowercase English letters.

In Taknese, the plural form of a noun is spelled based on the following rules:

If a noun's singular form does not end with s, append s to the end of the singular form.

If a noun's singular form ends with s, append es to the end of the singular form.

You are given the singular form S of a Taknese noun. Output its plural form.

Constraints

S is a string of length 1 between 1000, inclusive.

S contains only lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the plural form of the given Taknese word.

Sample Input 1

apple

Sample Output 1

apples

apple ends with e, so its plural form is apples.

Sample Input 2

bus

Sample Output 2

buses

bus ends with s, so its plural form is buses.

Sample Input 3

box

Sample Output 3

boxs

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


//package atcoder.beginner179;

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

public class Main {
    static InputReader in;
    static PrintWriter out;

    public static void main(String[] args) {
        //initReaderPrinter(true);
        initReaderPrinter(false);
        //solve(in.nextInt());
        solve(1);
    }

    static void solve(int testCnt) {
        for (int testNumber = 0; testNumber < testCnt; testNumber++) {
            int n = in.nextInt();
            int q = in.nextInt();
            long total = ((long)(n - 2)) * (n - 2);
            TreeSet<int[]> ts1 = new TreeSet<>(Comparator.comparingInt(a->a[1])), ts2 = new TreeSet<>(Comparator.comparingInt(a->a[1]));
            ts1.add(new int[]{2, n-1, n});
            ts2.add(new int[]{2, n-1, n});
            int min1 = n, min2 = n;

            for(int i = 0;i < q; i++) {
                int t = in.nextInt();
                int x = in.nextInt();

                if(t == 1) {
                    int[] curr = ts1.ceiling(new int[]{x,x,0});
                    total -= (curr[2] - 1 - 1);
                    if(x < min1) {
                        //update for type2 operation
                        int[] head = ts2.pollFirst();
                        if(2 <= min2 - 1) {
                            ts2.add(new int[]{2, min2 - 1, x});
                        }
                        if(min2 + 1 <= head[1]) {
                            ts2.add(new int[]{min2 + 1, head[1], head[2]});
                        }
                        min1 = x;
                    }
                }
                else {
                    int[] curr = ts2.ceiling(new int[]{x,x,0});
                    total -= (curr[2] - 1 - 1);
                    if(x < min2) {
                        //update for type1 operation
                        int[] head = ts1.pollFirst();
                        if(2 <= min1 - 1) {
                            ts1.add(new int[]{2, min1 - 1, x});
                        }
                        if(min1 + 1 <= head[1]) {
                            ts1.add(new int[]{min1 + 1, head[1], head[2]});
                        }
                        min2 = x;
                    }
                }
            }
            out.println(total);
        }
        out.close();
    }

    static void initReaderPrinter(boolean test) {
        if (test) {
            try {
                in = new InputReader(new FileInputStream("src/input.in"));
                out = new PrintWriter(new FileOutputStream("src/output.out"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            in = new InputReader(System.in);
            out = new PrintWriter(System.out);
        }
    }

    static class InputReader {
        BufferedReader br;
        StringTokenizer st;

        InputReader(InputStream stream) {
            try {
                br = new BufferedReader(new InputStreamReader(stream), 32768);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                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;
        }

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

        Long[] nextLongArray(int n) {
            Long[] a = new Long[n];
            for (int i = 0; i < n; i++) {
                a[i] = nextLong();
            }
            return a;
        }
    }
}

Score : 600 points

Problem Statement

There is a grid with N rows and N columns of squares. Let (i, j) be the square at the i-th row from the top and the j-th column from the left.

Each of the central (N-2) \times (N-2) squares in the grid has a black stone on it.
Each of the 2N - 1 squares on the bottom side and the right side has a white stone on it.

Q queries are given. We ask you to process them in order.
There are two kinds of queries. Their input format and description are as follows:

1 x: Place a white stone on (1, x). After that, for each black stone between (1, x) and the first white stone you hit if you go down from (1, x), replace it with a white stone.

2 x: Place a white stone on (x, 1). After that, for each black stone between (x, 1) and the first white stone you hit if you go right from (x, 1), replace it with a white stone.

How many black stones are there on the grid after processing all Q queries?

Constraints

3 \leq N \leq 2\times 10^5

0 \leq Q \leq \min(2N-4,2\times 10^5)

2 \leq x \leq N-1

Queries are pairwise distinct.

Input

Input is given from Standard Input in the following format:

N Q
Query_1
\vdots
Query_Q

Output

Print how many black stones there are on the grid after processing all Q queries.

Sample Input 1

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

Sample Output 1

1

After each query, the grid changes in the following way:

Sample Input 2

200000 0

Sample Output 2

39999200004

Sample Input 3

176527 15
1 81279
2 22308
2 133061
1 80744
2 44603
1 170938
2 139754
2 15220
1 172794
1 159290
2 156968
1 56426
2 77429
1 97459
2 71282

Sample Output 3

31159505795


public class Main{

	public static void main(String[] args){

		long a = Long.getLong(args[0]);
		long b = Long.getLong(args[1]);
		long c = Long.getLong(args[2]);
		long d = Long.getLong(args[3]);

		long answer=0;

		if(Math.multiplyExact(a, c) > answer) {
			answer = Math.multiplyExact(a, c);
		}
		if(Math.multiplyExact(a, d) > answer) {
			answer = Math.multiplyExact(a, d);
		}

		if(Math.multiplyExact(b, c) > answer) {
			answer = Math.multiplyExact(a, c);
		}
		if(Math.multiplyExact(b, d) > answer) {
			answer = Math.multiplyExact(a, d);
		}
		System.out.print(answer);
	}

}

Score : 100 points

Problem Statement

Given is an integer x that is greater than or equal to 0, and less than or equal to 1.
Output 1 if x is equal to 0, or 0 if x is equal to 1.

Constraints

0 \leq x \leq 1

x is an integer

Input

Input is given from Standard Input in the following format:

x

Output

Print 1 if x is equal to 0, or 0 if x is equal to 1.

Sample Input 1

1

Sample Output 1

0

Sample Input 2

0

Sample Output 2

1


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

/**
 * Created by Ayushi on 13 Sep 2020.
 * Problem:
 * Round:
 */

public class Main {
    public static void main(String[] args) throws IOException {
        StringTokenizer st;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(br.readLine());

        if (t == 0) System.out.println(1);
        else System.out.println(0);
        br.close();
    }
}


import java.util.Scanner;

public class Main {

  public static void main(String[] args) {
    int num[] = new int[4];
    Scanner scanner = new Scanner(System.in);
    for (int i = 0; i < 4; i++){
        num[i] = Integer.parseInt(scanner.next());
    }
    scanner.close();
    long max = -1000000000;
    long tmp = 0;

    for (int j = 0; j < 2; j++){
      for (int k = 2; k < 4; k++){
        tmp = (long)num[j] * (long)num[k];
        if (max < tmp){
          max = tmp;
        }
      }
    }
    System.out.println(max);
  }
}

Score : 200 points

Problem Statement

Given are integers a,b,c and d.
If x and y are integers and a \leq x \leq b and c\leq y \leq d hold, what is the maximum possible value of x \times y?

Constraints

-10^9 \leq a \leq b \leq 10^9

-10^9 \leq c \leq d \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b c d

Output

Print the answer.

Sample Input 1

1 2 1 1

Sample Output 1

2

If x = 1 and y = 1 then x \times y = 1.
If x = 2 and y = 1 then x \times y = 2.
Therefore, the answer is 2.

Sample Input 2

3 5 -4 -2

Sample Output 2

-6

The answer can be negative.

Sample Input 3

-1000000000 0 -1000000000 0

Sample Output 3

1000000000000000000


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		long a = sc.nextLong();
		long b = sc.nextLong();
		long c = sc.nextLong();
		long d = sc.nextLong();
//		String[] array = new String[n];
//		for(int i=0;i<n;i++) {
//				array[i] = sc.next();
//		}
		sc.close();

		long ans = -1000000000L;

		ans = Math.max(ans, a*c);
		ans = Math.max(ans, a*d);
		ans = Math.max(ans, b*c);
		ans = Math.max(ans, b*d);

		System.out.println(ans);
	}
}


import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        long mod = 1000000000 + 7;
        long answer = (powMod(10,n,mod)-2*powMod(9,n,mod)+powMod(8,n,mod))%mod;
        answer = (answer+mod)%mod;
        System.out.println(answer);
    }
    public static long powMod(long a, long b, long mod) {
        long p = 1;
        if (b==1) {
            return a;
        }else if(b==2) {
            return (a*a)%mod;
        }else {
            long tmp = powMod(a,b/2,mod);
            long answer = (tmp*tmp)%mod;
            if (b%2 == 1) {
                answer = (answer * a)%mod;
            }
            return answer;
        }
    }
}

Score : 300 points

Problem Statement

How many integer sequences A_1,A_2,\ldots,A_N of length N satisfy all of the following conditions?

0 \leq A_i \leq 9

There exists some i such that A_i=0 holds.

There exists some i such that A_i=9 holds.

The answer can be very large, so output it modulo 10^9 + 7.

Constraints

1 \leq N \leq 10^6

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer modulo 10^9 + 7.

Sample Input 1

2

Sample Output 1

2

Two sequences \{0,9\} and \{9,0\} satisfy all conditions.

Sample Input 2

1

Sample Output 2

0

Sample Input 3

869121

Sample Output 3

2511445


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;

/**
 * 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;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC
    {
        public void solve(int testNumber, Scanner in, PrintWriter out)
        {
            int T = 1;
            while (T-- > 0)
            {
                solveOne(in, out);
            }
        }

        private void solveOne(Scanner in, PrintWriter out)
        {
            long MOD = 1_000_000_000 + 7;
            long N = in.nextInt();

            if (N == 1 || N == 2)
            {
                out.println(N == 1 ? 0 : 1);
                return;
            }

            long ans = CPUtils.modPower(10L, N, MOD);

            ans -= 2L * CPUtils.modPower(9L, N, MOD);
            ans += CPUtils.modPower(8L, N, MOD);

            ans %= MOD;
            if (ans < 0)
                ans += MOD;

            out.println(ans);
        }

    }

    static class CPUtils
    {
        public static long modPower(long base, long p, long m)
        {
            long ret = 1;
            for (; p > 0; p >>= 1, base = base * base % m)
            {
                if (p % 2 == 1)
                {
                    ret = ret * base % m;
                }
            }
            return ret;
        }

    }
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.stream.Stream;

public class Main {

	public static void main(String[] args) {
		try (Stream<String> lines = new BufferedReader(new InputStreamReader(System.in)).lines()) {
			new Main().exec(lines.toArray(String[]::new));
		}
	}

	void exec(String[] args) {
		int S = Integer.parseInt(args[0].split(" ")[0]);
		BigInteger n = bi(0);
		for (int i = 1; i <= S / 3; i++) {
			n = n.add(c(S, i));
		}
		System.out.println(n.remainder(bi(10).pow(9).add(bi(7))));
	}

	BigInteger bi(int n) {
		return new BigInteger(String.valueOf(n));
	}

	BigInteger c(int s, int n) {
		int a = Math.min(s - 3 * n, n - 1);
		return f(s - 2 * n - 1, a).divide(f(a, a));
	}

	BigInteger f(int a, int b) {
		BigInteger n = bi(1);
		for (int i = 0; i < b; i++) {
			n = n.multiply(bi(a).subtract(bi(i)));
		}
		return n;
	}

}

Score : 400 points

Problem Statement

Given is an integer S.
Find how many sequences there are whose terms are all integers greater than or equal to 3, and whose sum is equal to S.
The answer can be very large, so output it modulo 10^9 + 7.

Constraints

1 \leq S \leq 2000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

S

Output

Print the answer.

Sample Input 1

7

Sample Output 1

3

3 sequences satisfy the condition: \{3,4\}, \{4,3\} and \{7\}.

Sample Input 2

2

Sample Output 2

0

There are no sequences that satisfy the condition.

Sample Input 3

1729

Sample Output 3

294867501


import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
    public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		PrintWriter ou = new PrintWriter(System.out);
		int n = Integer.parseInt(sc.next());
		sc.close();
		long yono = 0;
		for(int i = 1 ; i <= n / 3 ; i++){
			yono += c(n - 2 * i - 1 , i - 1);
			yono %= (int)(Math.pow(10 , 9) + 7);
		}
		ou.println(yono);
		ou.flush();
	}
	public static int c(int a , int b){
		if(b == 0) return 1;
		else if(a == b) return 1;
		else return (c(a - 1 , b - 1) + c(a - 1 , b)) % (int)(Math.pow(10 , 9) + 7);
	}
}


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.Comparator;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
        thread.start();
        thread.join();
    }

    static class TaskAdapter implements Runnable {
        @Override
        public void run() {
            InputStream inputStream = System.in;
            OutputStream outputStream = System.out;
            FastReader in = new FastReader(inputStream);
            PrintWriter out = new PrintWriter(outputStream);
            EDistMax solver = new EDistMax();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class EDistMax {
        public void solve(int testNumber, FastReader s, PrintWriter w) {
            int n = s.nextInt();
            pair[] p = new pair[n];
            for (int i = 0; i < n; i++)
                p[i] = new pair(s.nextInt(), s.nextInt());
            for (int i = 0; i < n; i++) {
                int x = p[i].x, y = p[i].y;
                p[i].x = x - y;
                p[i].y = x + y;
            }
            func.sort(p, Comparator.comparingInt(o -> o.x));
            int mx1 = p[n - 1].x - p[0].x;
            func.sort(p, Comparator.comparingInt(o -> o.y));
            w.println(Math.max(mx1, p[n - 1].y - p[0].y));
        }

        class pair {
            int x;
            int y;

            pair(int xx, int yy) {
                x = xx;
                y = yy;
            }

        }

    }

    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 c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class func {
        public static <T> void sort(T[] arr, Comparator<T> comp) {
            int n = arr.length, mid, h, s, l, i, j, k;
            T[] res = arr.clone();
            n--;
            for (s = 1; s <= n; s <<= 1) {
                for (l = 0; l < n; l += (s << 1)) {
                    h = Math.min(l + (s << 1) - 1, n);
                    mid = Math.min(l + s - 1, n);
                    i = l;
                    j = mid + 1;
                    k = l;
                    while (i <= mid && j <= h)
                        res[k++] = comp.compare(arr[i], (arr[j])) <= 0 ? arr[i++] : arr[j++];
                    while (i <= mid) res[k++] = arr[i++];
                    while (j <= h) res[k++] = arr[j++];
                    for (k = l; k <= h; k++) arr[k] = res[k];
                }
            }
        }

    }
}

Score : 500 points

Problem Statement

There are N points on the 2D plane, i-th of which is located on (x_i, y_i).
There can be multiple points that share the same coordinate.
What is the maximum possible Manhattan distance between two distinct points?

Here, the Manhattan distance between two points (x_i, y_i) and (x_j, y_j) is defined by |x_i-x_j| + |y_i-y_j|.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq x_i,y_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print the answer.

Sample Input 1

3
1 1
2 4
3 2

Sample Output 1

4

The Manhattan distance between the first point and the second point is |1-2|+|1-4|=4, which is maximum possible.

Sample Input 2

2
1 1
1 1

Sample Output 2

0


import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.lang.reflect.Array;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
    public void exec() {
        int n = stdin.nextInt();
        long[] x = new long[n];
        long[] y = new long[n];
        for (int i = 0; i < n; i++) {
            x[i] = stdin.nextLong();
            y[i] = stdin.nextLong();
        }

        long wMax = IntStream.range(0, n).mapToLong(i -> x[i]-y[i]).max().getAsLong();
        long wMin = IntStream.range(0, n).mapToLong(i -> x[i]-y[i]).min().getAsLong();
        long zMax = IntStream.range(0, n).mapToLong(i -> x[i]+y[i]).max().getAsLong();
        long zMin = IntStream.range(0, n).mapToLong(i -> x[i]+y[i]).min().getAsLong();
        long ans = Math.max(wMax-wMin, zMax-zMin);
        stdout.println(ans);
    }

    private static final Stdin stdin = new Stdin();
    private static final Stdout stdout = new Stdout();

    public static void main(String[] args) {
        try {
            new Main().exec();
        } finally {
            stdout.flush();
        }
    }

    public static class Stdin {
        private BufferedReader stdin;
        private Deque<String> tokens;
        private Pattern delim;

        public Stdin() {
            stdin = new BufferedReader(new InputStreamReader(System.in));
            tokens = new ArrayDeque<>();
            delim = Pattern.compile(" ");
        }

        public String nextString() {
            try {
                if (tokens.isEmpty()) {
                    String line = stdin.readLine();
                    if (line == null) {
                        throw new UncheckedIOException(new EOFException());
                    }
                    delim.splitAsStream(line).forEach(tokens::addLast);
                }
                return tokens.pollFirst();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }

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

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

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

        public String[] nextStringArray(int n) {
            String[] a = new String[n];
            for (int i = 0; i < n; i++) a[i] = nextString();
            return a;
        }

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

        public double[] nextDoubleArray(int n) {
            double[] a = new double[n];
            for (int i = 0; i < n; i++) a[i] = nextDouble();
            return a;
        }

        public long[] nextLongArray(int n) {
            long[] a = new long[n];
            for (int i = 0; i < n; i++) a[i] = nextLong();
            return a;
        }
    }

    public static class Stdout {
        private PrintWriter stdout;

        public Stdout() {
            stdout =  new PrintWriter(System.out, false);
        }

        public void printf(String format, Object ... args) {
            String line = String.format(format, args);
            if (line.endsWith(System.lineSeparator())) {
                stdout.print(line);
            } else {
                stdout.println(line);
            }
        }

        public void println(Object ... objs) {
            String line = Arrays.stream(objs).map(Objects::toString).collect(Collectors.joining(" "));
            stdout.println(line);
        }

        public void printDebug(Object ... objs) {
            String line = Arrays.stream(objs).map(this::deepToString).collect(Collectors.joining(" "));
            stdout.printf("DEBUG: %s%n", line);
            stdout.flush();
        }

        private String deepToString(Object o) {
            if (o == null) {
                return "null";
            }

            // 配列の場合
            if (o.getClass().isArray()) {
                int len = Array.getLength(o);
                String[] tokens = new String[len];
                for (int i = 0; i < len; i++) {
                    tokens[i] = deepToString(Array.get(o, i));
                }
                return "{" + String.join(",", tokens) + "}";
            }

            return Objects.toString(o);
        }

        private void flush() {
            stdout.flush();
        }
    }
}


import java.io.IOException;
import java.io.InputStream;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        int n = sc.nextInt();
        long[] plus = new long[n];
        long[] minus = new long[n];
        for (int i=0;i<n;i++){
            int x = sc.nextInt();
            int y = sc.nextInt();
            plus[i]=x+y;
            minus[i]=x-y;
        }
        Arrays.sort(plus);
        Arrays.sort(minus);
        System.out.println(Math.max(plus[n-1]-plus[0],minus[n-1]-minus[0]));
    }

    public static long MOD = 1000000007L;
    public static int tenE9 = 1000000000;
    static Basic basic = new Basic();
    static FastScanner sc = new FastScanner();
    public static class FastScanner {
        private final InputStream in = System.in;
        private final byte[] buffer = new byte[1024];
        private int ptr = 0;
        private int buflen = 0;
        private boolean hasNextByte() {
            if (ptr < buflen) {
                return true;
            }else{
                ptr = 0;
                try {
                    buflen = in.read(buffer);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (buflen <= 0) {
                    return false;
                }
            }
            return true;
        }
        private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
        private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
        public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
        public String next() {
            if (!hasNext()) throw new NoSuchElementException();
            StringBuilder sb = new StringBuilder();
            int b = readByte();
            while(isPrintableChar(b)) {
                sb.appendCodePoint(b);
                b = readByte();
            }
            return sb.toString();
        }
        public long nextLong() {
            if (!hasNext()) throw new NoSuchElementException();
            long n = 0;
            boolean minus = false;
            int b = readByte();
            if (b == '-') {
                minus = true;
                b = readByte();
            }
            if (b < '0' || '9' < b) {
                throw new NumberFormatException();
            }
            while(true){
                if ('0' <= b && b <= '9') {
                    n *= 10;
                    n += b - '0';
                }else if(b == -1 || !isPrintableChar(b)){
                    return minus ? -n : n;
                }else{
                    throw new NumberFormatException();
                }
                b = readByte();
            }
        }
        public int nextInt() {
            long nl = nextLong();
            if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
            return (int) nl;
        }
        public double nextDouble() { return Double.parseDouble(next());}
    }
    public static class Basic {
        //math
        private final int MAX = 510000;
        private final long MOD = Main.MOD;
        private final long[] fac = new long[MAX];
        private final long[] finv = new long[MAX];
        private final long[] inv = new long[MAX];
        public long factorial(long num) {
            if (num < 2) return 1;
            else return num * factorial(num - 1);
        }
        public long modFactorial(long num) {
            if (num < 2) return 1;
            else return num*modFactorial(num-1)%MOD;
        }
        public int arraySum(int[] array) {
            int ans = 0;
            for (int value : array) ans += value;
            return ans;
        }
        public double log(double base, double antilogarithm) {
            return Math.log(antilogarithm) / Math.log(base);
        }
        public long gcd(long x, long y) {
            if (y == 0) return x;
            else return gcd(y, x % y);
        }
        public long lcm(long x, long y) {
            return x / gcd(x, y) * y;
        }
        public HashMap<Long, Long> factorization(long num) {
            HashMap<Long, Long> hash = new HashMap<>();
            long n = num;
            long count = 2;
            while (n > 1) {
                while (n % count == 0) {
                    n /= count;
                    if (hash.containsKey(count)) hash.put(count, hash.get(count) + 1);
                    else hash.put(count, 1L);
                }
                count++;
            }
            return hash;
        }
        public int sum(int[] num) {
            int ans = 0;
            for (int i = 0; i < num.length; i++) {
                ans += num[i];
            }
            return ans;
        }
        public int[] reduce(int small, int big) {
            int ins = 2;
            while (ins <= small) {
                if (small % ins == 0 && big % ins == 0) {
                    small /= ins;
                    big /= ins;
                    ins = 2;
                } else {
                    ins++;
                }
            }
            return new int[]{small, big};
        }
        public int reduceCount(int small, int big) {
            int ins = 2;
            int ans = 0;
            while (ins <= small) {
                if (small % ins == 0 && big % ins == 0) {
                    small /= ins;
                    big /= ins;
                    ins = 2;
                    ans++;
                } else {
                    ins++;
                }
            }
            return ans;
        }
        public int binarySearch(int[] array, int target) {
            int pos = -1;
            int left = 0;
            int right = array.length - 1;
            int middle;
            while (pos == -1 && left <= right) {
                middle = (left + right) / 2;
                if (array[middle] == target) pos = middle;
                else if (array[middle] > target) right = middle - 1;
                else left = middle + 1;
            }
            return pos;
        }
        public int upperBound(int[] ar, long d, int n, int f){
            int p = n;
            int q = f;
            while (p-q>1){
                int mid = (p+q)/2;
                if (ar[mid]==d){
                    return mid+1;
                }
                if (ar[mid]<d)q=mid;
                else p=mid;

            }
            return p;
        }
        public long modPow(long a, long n, long mod) {
            long res = 1;
            while (n > 0) {
                if ((n & 1) != 0) res = res * a % mod;
                a = a * a % mod;
                n >>= 1;
            }
            return res;
        }
        public long pow(long a, long n) {
            long res = 1;
            while (n > 0) {
                if ((n & 1) != 0) res = res * a;
                a = a * a;
                n >>= 1;
            }
            return res;
        }
        public long modinv(long a, long mod) {
            return modPow(a, mod - 2, mod);
        }
        public void COMinit() {
            fac[0] = 1;
            fac[1] = 1;
            finv[0] = 1;
            finv[1] = 1;
            inv[1] = 1;
            for (int i = 2; i < MAX; i++) {
                fac[i] = fac[i - 1] * i % MOD;
                inv[i] = MOD - inv[(int)(MOD % i)] * (MOD / i) % MOD;
                finv[i] = finv[i - 1] * inv[i] % MOD;
            }
        }
        public long COM(int n, int k) {
            if (n < k) return 0;
            if (n < 0 || k < 0) return 0;
            return fac[n] * (finv[k] * finv[n-k]%MOD)% MOD;
        }
        public long PER(int n, int k){
            return fac[n]*finv[n-k]%MOD;
        }
        public long HCOM(int n, int k) {
            return COM(n + k - 1, k);
        }
        public boolean[] getIsPrimeArray(int max){
            boolean[] ret = new boolean[max+1];
            Arrays.fill(ret,true);
            ret[0]=false;
            ret[1]=false;
            for (int i=2;i<=max;i++){
                if (ret[i]){
                    int c = 2*i;
                    while (c<=max){
                        ret[c]=false;
                        c+=i;
                    }
                }
            }
            return ret;
        }

        //array
        public int[] remove(int[] ar, int pos) {
            int[] ret = new int[ar.length - 1];
            for (int i = 0; i < pos; i++) ret[i] = ar[i];
            for (int i = pos + 1; i < ar.length; i++) ret[i - 1] = ar[i];
            return ret;
        }
        public int[] nextArray(int size,int cons){
            int[] ret = new int[size];
            for (int i=0;i<size;i++)ret[i]=sc.nextInt()+cons;
            return  ret;
        }
        public int[] reverse(int[] ar){
            int[] ret = new int[ar.length];
            for (int i=0;i<ar.length;i++){
                ret[i]=ar[ar.length-1-i];
            }
            return ret;
        }
        public long[] cumulative_sum(int[] ar){
            long[] ret = new long[ar.length+1];
            ret[0]=0;
            for (int i=0;i<ar.length;i++)ret[i+1]=ret[i]+ar[i];
            return ret;
        }
        //graph
        public void warshall_floyd(int[][] d) {
            int n = d.length;
            for (int k = 0; k < n; k++)
                for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) d[i][j] = Math.min(d[i][j], d[i][k] + d[k][j]);
        }//隣接行列が引数。辺が無い場合、INFを入力。
        public int[] bellman_ford(int[][] d, int size, int start){
            int e = d.length;
            int[] ans = new int[size];
            Arrays.fill(ans,Integer.MAX_VALUE);
            ans[start]=0;
            for (int i=0;i<size;i++){
                for (int[] a : d) {
                    if (ans[a[1]] > ans[a[0]] + a[2]) {
                        ans[a[1]] = ans[a[0]] + a[2];
                        if (i == size - 1) {
                            System.out.println("negative loop");
                            break;
                        }
                    }
                }
            }
            return ans;
        }//辺を配列の要素として管理。

    }
    public static class Queue<T>{
        private final int max = 10000000;
        private final T[] queue = (T[]) new Object[max];
        private int tail = 0; private int head = 0;
        public void init(){this.head = 0; tail = 0;}
        public boolean isEmpty(){return (head==tail);}
        public boolean isFull(){return (head == (tail+1)%max);}
        public void enqueue(T v){
            if (isFull()){
                System.out.println("error: queue is full.");
                return;
            }
            queue[tail++] = v;
            if (tail == max) tail = 0;
        }
        public T dequeue(){
            if (isEmpty()){
                System.out.println("error: queue is empty");
                return null;
            }
            T res = queue[head];
            ++head;
            if (head == max) head = 0;
            return res;
        }
    }
    public static class Deque<T>{
        private final int max = 10000000;
        private final T[] queue = (T[]) new Object[max];
        private int tail = 0; private int head = 0;
        public void init(){this.head = 0; tail = 0;}
        public boolean isEmpty(){return (head==tail);}
        public boolean isFull(){
            return (head == (tail+1)%max);
        }
        public void pushFirst(T v){
            if (isFull()){
                System.out.println("error: queue is full.");
                return;
            }
            head--;
            if (head==-1)head=max-1;
            queue[head] = v;
        }
        public void pushLast(T v){
            if (isFull()){
                System.out.println("error: queue is full.");
                return;
            }
            queue[tail++] = v;
            if (tail == max) tail = 0;
        }
        public T popFirst(){
            if (isEmpty()){
                System.out.println("error: queue is empty");
                return null;
            }
            T res = queue[head];
            ++head;
            if (head == max) head = 0;
            return res;
        }
        public T popLast(){
            if (isEmpty()){
                System.out.println("error: queue is empty");
                return null;
            }
            if (--tail==-1)tail=max-1;
            return queue[tail];
        }

        public T peekFirst(){
            if (isEmpty()){
                System.out.println("error: queue is empty");
                return null;
            }
            return queue[head];
        }
        public T peekLast(){
            if (isEmpty()){
                System.out.println("error: queue is empty");
                return null;
            }
            return queue[tail];
        }
    }
    public static class Stack<T>{
        private final int max = 100000;
        private final T[] stack =(T[]) new Object[max];
        private int top = 0;
        public boolean isEmpty(){return (top==0);}
        public boolean isFull(){return (top==max);}
        public void init(){top=0;}
        public void push(T v){
            if (isFull()){
                System.out.println("error: stack is full.");
                return;
            }
            stack[top++] = v;
        }
        public T pop(){
            if (isEmpty()){
                System.out.println("error: stack is empty");
                return null;
            }
            return stack[--top];
        }
        public T peek(){
            if (isEmpty()){
                System.out.println("error: stack is empty");
                return null;
            }
            return stack[top];
        }
    }
    public static class Pair<K,V>{
        private K A;
        private V B;
        Pair(K a,V b){
            A=a;
            B=b;
        }
        public void changeA(K a){A=a;}
        public void changeB(V b){B=b;}
        public void changeAB(K a,V b){A=a;B=b;}
        public static Comparator numberSortWithA = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Pair p = (Pair)o1;
                Pair q = (Pair)o2;
                if ((int)p.A<(int)q.A)return -1;
                else if ((int)p.A==(int)q.A){
                    if ((int)p.B<(int)q.B)return -1;
                    else if ((int)p.B==(int)q.B)return 0;
                    else return 1;
                }
                else return 1;
            }
        };
        public static Comparator numberSortWithB = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Pair p = (Pair)o1;
                Pair q = (Pair)o2;
                if ((int)p.B<(int)q.B)return -1;
                else if ((int)p.B==(int)q.B){
                    if ((int)p.A<(int)q.A)return -1;
                    else if ((int)p.A==(int)q.A)return 0;
                    else return 1;
                }
                else return 1;
            }
        };
    }
    public static class Graph{
        private final HashMap<Integer,HashSet<Integer>> graph = new HashMap<>();
        private final int Size;
        Graph(int size){
            for (int i=0;i<size;i++)graph.put(i,new HashSet<>());
            Size = size;
        }

        public void addEdge(int node1,int node2){
            if (graph.containsKey(node1)&&graph.containsKey(node2)){
                graph.get(node1).add(node2);
                graph.get(node2).add(node1);
            }
        }
        public void addDirectEdge(int from,int to){
            if (graph.containsKey(from)&&graph.containsKey(to)){
                graph.get(from).add(to);
            }
        }
        public int[] depth(int root){
            Queue<Integer> q = new Queue<>();
            q.enqueue(root);
            boolean[] seen = new boolean[Size];
            Arrays.fill(seen, false);
            seen[root]=true;
            int[] depth = new int[Size];
            Arrays.fill(depth,-1);
            depth[root]=0;
            while (!q.isEmpty()){
                int v = q.dequeue();
                for (int u : graph.get(v)){
                    if (!seen[u]){
                        seen[u]=true;
                        q.enqueue(u);
                        depth[u]=depth[v]+1;
                    }
                }
            }
            return depth;
        }
        public HashSet<Integer> getConnected(int pos){return graph.get(pos);}
        public boolean isConnected(int from,int to){return graph.get(from).contains(to);}
    }
    public static class WeightedGraph{
        private final HashMap<Integer,HashMap<Integer,Integer>> graph = new HashMap<>();
        private final int Size;
        private long[] Depth;
        WeightedGraph(int size){
            for (int i=0;i<size;i++)graph.put(i,new HashMap<>());
            Size = size;
        }

        public void addEdge(int node1,int node2,int weight){
            if (graph.containsKey(node1)&&graph.containsKey(node2)){
                graph.get(node1).put(node2,weight);
                graph.get(node2).put(node1,weight);
            }
        }
        public void addDirectEdge(int from,int to,int weight){
            if (graph.containsKey(from)&&graph.containsKey(to)){
                graph.get(from).put(to,weight);
            }
        }
        public int[] dijkstra(int root){
            Comparator<int[]> c = new Comparator<int[]>() {
                @Override
                public int compare(int[] o1, int[] o2) {
                    return Integer.compare(o1[1], o2[1]);
                }
            };
            PriorityQueue<int[]> q = new PriorityQueue<>(c);
            q.add(new int[]{root,0});
            int[] ret = new int[Size];
            Arrays.fill(ret,Integer.MAX_VALUE);
            ret[root]=0;
            while (!q.isEmpty()){
                int[] v = q.poll();
                if (v[1]<=ret[v[0]]){
                    HashMap<Integer,Integer> h = graph.get(v[0]);
                    for (int u : h.keySet()){
                        if (ret[u]>v[1]+h.get(u)){
                            ret[u]=v[1]+h.get(u);
                            q.add(new int[]{u,ret[u]});
                        }
                    }
                }
            }
            return ret;
        }

        public long[] Depth(int root){
            Queue<Integer> q = new Queue<>();
            q.enqueue(root);
            boolean[] seen = new boolean[Size];
            Arrays.fill(seen, false);
            seen[root]=true;
            long[] depth = new long[Size];
            depth[root]=0;
            while (!q.isEmpty()){
                int v = q.dequeue();
                for (int u : graph.get(v).keySet()){
                    if (!seen[u]){
                        seen[u]=true;
                        q.enqueue(u);
                        depth[u]=depth[v]+graph.get(v).get(u);
                    }
                }
            }
            Depth = depth.clone();
            return depth;
        }

    }
    public static class UnionFindTree{
        int[] parent;
        int[] rank;
        int[] Size;
        int Number;
        public UnionFindTree(int size){
            this.parent = new int[size];
            this.rank = new int[size];
            this.Size = new int[size];
            makeSet();
        }
        public void makeSet(){
            for (int i=0;i<Size.length;i++){
                parent[i]=i;
                rank[i]=0;
                Size[i]=1;
            }
            Number= Size.length;
        }
        public void unite(int x, int y){
            int xRoot = find(x);
            int yRoot = find(y);
            if (rank[xRoot]>rank[yRoot]){
                parent[yRoot] = xRoot;
                Size[xRoot]+=Size[yRoot];
                Number--;
            }else if (rank[xRoot]<rank[yRoot]){
                parent[xRoot] = yRoot;
                Size[yRoot]+=Size[xRoot];
                Number--;
            }else if (xRoot!=yRoot){
                parent[yRoot] = xRoot;
                rank[xRoot]++;
                Size[xRoot]+=Size[yRoot];
                Number--;
            }
        }
        public int find(int i){
            if (i!= parent[i]){
                parent[i]=find(parent[i]);
            }
            return parent[i];
        }
        public boolean same(int x, int y){
            return find(x) == find(y);
        }
        public int getSize(int i){return Size[find(i)];}
        boolean isConnected(){
            return Number<2;
        }
    }
    public static class BitSearch<T>{
        T[] Array;
        int Width;
        int Length;
        BitSearch(T[] t, int width){
            Array = t;
            Width = width;
            Length = Array.length;
        }
        void start(){
            long max = (long)Math.pow(Width,Length);
            for (long i=0;i<max;i++){
                StringBuilder s = new StringBuilder(Long.toString(i, Width));
                while (s.length()<Length) s.insert(0, "0");
                run(s);
            }
        }
        void run(StringBuilder s){

        }
    }

}


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.util.function.BinaryOperator;
import java.util.function.Function;

public class Main {
	static final long MOD1=1000000007;
	static final long MOD2=998244353;
	public static void main(String[] args) {
		PrintWriter out = new PrintWriter(System.out);
		InputReader sc=new InputReader(System.in);
		int N=sc.nextInt();
		int Q=sc.nextInt();
		S[] dat = new S[N];
		for (int i = 0; i < dat.length; i++) {
			dat[i]=new S(sc.nextLong(), 1L);
		}
		LazySegTree<S, F> lazySegTree=new LazySegTree<S, F>(dat, S::op, S.E,S::map,F::composite,F.I);
		for (int i = 0; i< Q; i++) {
			int c=sc.nextInt();
			int s=sc.nextInt();
			int t=sc.nextInt();
			if (c==0) {
				long a=sc.nextLong();
				long b=sc.nextLong();
				lazySegTree.apply(s, t, new F(a, b));

			}else {
				out.println(lazySegTree.prod(s, t).sum);
			}
		}
		out.flush();
	}
	static class F {
        static final F I = new F(1,0);
        long a;
        long b;
        public F (long a, long b) {
        	super();
            this.a = a;
            this.b = b;
        }
        public static F composite(F f, F g) {
            return new F((f.a*g.a)%MOD2,((g.a*f.b)%MOD2+g.b)%MOD2);
        }
    }
	static class S {
        static final S E = new S(0,0);
        long sum;
        long size;
        public S (long sum,long size) {
        	super();
            this.sum = sum;
            this.size=size;
        }
        public static S op(S s1, S s2) {
            return new S((s1.sum+s2.sum)%MOD2,(s1.size+s2.size)%MOD2);
        }
        static S map(F f,  S s) {
    		return new S(((s.sum*f.a)%MOD2 + (f.b * s.size)%MOD2)%MOD2, s.size);
    	}
    }
	static class LazySegTree<S, F> {
	    final int MAX;

	    final int N;
	    final int Log;
	    final java.util.function.BinaryOperator<S> Op;
	    final S E;
	    final java.util.function.BiFunction<F, S, S> Mapping;
	    final java.util.function.BinaryOperator<F> Composition;
	    final F Id;

	    final S[] Dat;
	    final F[] Laz;

	    @SuppressWarnings("unchecked")
	    public LazySegTree(int n, java.util.function.BinaryOperator<S> op, S e, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BinaryOperator<F> composition, F id) {
	        this.MAX = n;
	        int k = 1;
	        while (k < n) k <<= 1;
	        this.N = k;
	        this.Log = Integer.numberOfTrailingZeros(N);
	        this.Op = op;
	        this.E = e;
	        this.Mapping = mapping;
	        this.Composition = composition;
	        this.Id = id;
	        this.Dat = (S[]) new Object[N << 1];
	        this.Laz = (F[]) new Object[N];
	        java.util.Arrays.fill(Dat, E);
	        java.util.Arrays.fill(Laz, Id);
	    }

	    public LazySegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BinaryOperator<F> composition, F id) {
	        this(dat.length, op, e, mapping, composition, id);
	        build(dat);
	    }

	    private void build(S[] dat) {
	        int l = dat.length;
	        System.arraycopy(dat, 0, Dat, N, l);
	        for (int i = N - 1; i > 0; i--) {
	            Dat[i] = Op.apply(Dat[i << 1 | 0], Dat[i << 1 | 1]);
	        }
	    }

	    private void push(int k) {
	        if (Laz[k] == Id) return;
	        int lk = k << 1 | 0, rk = k << 1 | 1;
	        Dat[lk] = Mapping.apply(Laz[k], Dat[lk]);
	        Dat[rk] = Mapping.apply(Laz[k], Dat[rk]);
	        if (lk < N) Laz[lk] = Composition.apply(Laz[k], Laz[lk]);
	        if (rk < N) Laz[rk] = Composition.apply(Laz[k], Laz[rk]);
	        Laz[k] = Id;
	    }

	    private void pushTo(int k) {
	        for (int i = Log; i > 0; i--) push(k >> i);
	    }

	    private void pushTo(int lk, int rk) {
	        for (int i = Log; i > 0; i--) {
	            if (((lk >> i) << i) != lk) push(lk >> i);
	            if (((rk >> i) << i) != rk) push(rk >> i);
	        }
	    }

	    private void updateFrom(int k) {
	        k >>= 1;
	        while (k > 0) {
	            Dat[k] = Op.apply(Dat[k << 1 | 0], Dat[k << 1 | 1]);
	            k >>= 1;
	        }
	    }

	    private void updateFrom(int lk, int rk) {
	        for (int i = 1; i <= Log; i++) {
	            if (((lk >> i) << i) != lk) {
	                int lki = lk >> i;
	                Dat[lki] = Op.apply(Dat[lki << 1 | 0], Dat[lki << 1 | 1]);
	            }
	            if (((rk >> i) << i) != rk) {
	                int rki = (rk - 1) >> i;
	                Dat[rki] = Op.apply(Dat[rki << 1 | 0], Dat[rki << 1 | 1]);
	            }
	        }
	    }

	    public void set(int p, S x) {
	        exclusiveRangeCheck(p);
	        p += N;
	        pushTo(p);
	        Dat[p] = x;
	        updateFrom(p);
	    }

	    public S get(int p) {
	        exclusiveRangeCheck(p);
	        p += N;
	        pushTo(p);
	        return Dat[p];
	    }

	    public S prod(int l, int r) {
	        if (l > r) {
	            throw new IllegalArgumentException(
	                String.format("Invalid range: [%d, %d)", l, r)
	            );
	        }
	        inclusiveRangeCheck(l);
	        inclusiveRangeCheck(r);
	        if (l == r) return E;
	        l += N; r += N;
	        pushTo(l, r);
	        S sumLeft = E, sumRight = E;
	        while (l < r) {
	            if ((l & 1) == 1) sumLeft = Op.apply(sumLeft, Dat[l++]);
	            if ((r & 1) == 1) sumRight = Op.apply(Dat[--r], sumRight);
	            l >>= 1; r >>= 1;
	        }
	        return Op.apply(sumLeft, sumRight);
	    }

	    public S allProd() {
	        return Dat[1];
	    }

	    public void apply(int p, F f) {
	        exclusiveRangeCheck(p);
	        p += N;
	        pushTo(p);
	        Dat[p] = Mapping.apply(f, Dat[p]);
	        updateFrom(p);
	    }

	    public void apply(int l, int r, F f) {
	        if (l > r) {
	            throw new IllegalArgumentException(
	                String.format("Invalid range: [%d, %d)", l, r)
	            );
	        }
	        inclusiveRangeCheck(l);
	        inclusiveRangeCheck(r);
	        if (l == r) return;
	        l += N; r += N;
	        pushTo(l, r);
	        for (int l2 = l, r2 = r; l2 < r2;) {
	            if ((l2 & 1) == 1) {
	                Dat[l2] = Mapping.apply(f, Dat[l2]);
	                if (l2 < N) Laz[l2] = Composition.apply(f, Laz[l2]);
	                l2++;
	            }
	            if ((r2 & 1) == 1) {
	                r2--;
	                Dat[r2] = Mapping.apply(f, Dat[r2]);
	                if (r2 < N) Laz[r2] = Composition.apply(f, Laz[r2]);
	            }
	            l2 >>= 1; r2 >>= 1;
	        }
	        updateFrom(l, r);
	    }

	    public int maxRight(int l, java.util.function.Predicate<S> g) {
	        inclusiveRangeCheck(l);
	        if (!g.test(E)) {
	            throw new IllegalArgumentException("Identity element must satisfy the condition.");
	        }
	        if (l == MAX) return MAX;
	        l += N;
	        pushTo(l);
	        S sum = E;
	        do {
	            l >>= Integer.numberOfTrailingZeros(l);
	            if (!g.test(Op.apply(sum, Dat[l]))) {
	                while (l < N) {
	                    push(l);
	                    l = l << 1;
	                    if (g.test(Op.apply(sum, Dat[l]))) {
	                        sum = Op.apply(sum, Dat[l]);
	                        l++;
	                    }
	                }
	                return l - N;
	            }
	            sum = Op.apply(sum, Dat[l]);
	            l++;
	        } while ((l & -l) != l);
	        return MAX;
	    }

	    public int minLeft(int r, java.util.function.Predicate<S> g) {
	        inclusiveRangeCheck(r);
	        if (!g.test(E)) {
	            throw new IllegalArgumentException("Identity element must satisfy the condition.");
	        }
	        if (r == 0) return 0;
	        r += N;
	        pushTo(r - 1);
	        S sum = E;
	        do {
	            r--;
	            while (r > 1 && (r & 1) == 1) r >>= 1;
	            if (!g.test(Op.apply(Dat[r], sum))) {
	                while (r < N) {
	                    push(r);
	                    r = r << 1 | 1;
	                    if (g.test(Op.apply(Dat[r], sum))) {
	                        sum = Op.apply(Dat[r], sum);
	                        r--;
	                    }
	                }
	                return r + 1 - N;
	            }
	            sum = Op.apply(Dat[r], sum);
	        } while ((r & -r) != r);
	        return 0;
	    }

	    private void exclusiveRangeCheck(int p) {
	        if (p < 0 || p >= MAX) {
	            throw new IndexOutOfBoundsException(
	                String.format("Index %d is not in [%d, %d).", p, 0, MAX)
	            );
	        }
	    }

	    private void inclusiveRangeCheck(int p) {
	        if (p < 0 || p > MAX) {
	            throw new IndexOutOfBoundsException(
	                String.format("Index %d is not in [%d, %d].", p, 0, MAX)
	            );
	        }
	    }

	    // **************** DEBUG **************** //

	    private int indent = 6;

	    public void setIndent(int newIndent) {
	        this.indent = newIndent;
	    }

	    @Override
	    public String toString() {
	        return toString(1, 0);
	    }

	    private String toString(int k, int sp) {
	        if (k >= N) return indent(sp) + Dat[k];
	        String s = "";
	        s += toString(k << 1 | 1, sp + indent);
	        s += "\n";
	        s += indent(sp) + Dat[k] + "/" + Laz[k];
	        s += "\n";
	        s += toString(k << 1 | 0, sp + indent);
	        return s;
	    }

	    private static String indent(int n) {
	        StringBuilder sb = new StringBuilder();
	        while (n --> 0) sb.append(' ');
	        return sb.toString();
	    }
	}
	//funはlamda式で定義
	//prodで取得,setで更新(一点加算なら更新でおｋ)
	//二ブタンも出来る

		static class InputReader {
		private InputStream in;
		private byte[] buffer = new byte[1024];
		private int curbuf;
		private int lenbuf;
		public InputReader(InputStream in) {
			this.in = in;
			this.curbuf = this.lenbuf = 0;
		}

		public boolean hasNextByte() {
			if (curbuf >= lenbuf) {
				curbuf = 0;
				try {
					lenbuf = in.read(buffer);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (lenbuf <= 0)
					return false;
			}
			return true;
		}

		private int readByte() {
			if (hasNextByte())
				return buffer[curbuf++];
			else
				return -1;
		}

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

		private void skip() {
			while (hasNextByte() && isSpaceChar(buffer[curbuf]))
				curbuf++;
		}

		public boolean hasNext() {
			skip();
			return hasNextByte();
		}

		public String next() {
			if (!hasNext())
				throw new NoSuchElementException();
			StringBuilder sb = new StringBuilder();
			int b = readByte();
			while (!isSpaceChar(b)) {
				sb.appendCodePoint(b);
				b = readByte();
			}
			return sb.toString();
		}

		public int nextInt() {
			if (!hasNext())
				throw new NoSuchElementException();
			int c = readByte();
			while (isSpaceChar(c))
				c = readByte();
			boolean minus = false;
			if (c == '-') {
				minus = true;
				c = readByte();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res = res * 10 + c - '0';
				c = readByte();
			} while (!isSpaceChar(c));
			return (minus) ? -res : res;
		}

		public long nextLong() {
			if (!hasNext())
				throw new NoSuchElementException();
			int c = readByte();
			while (isSpaceChar(c))
				c = readByte();
			boolean minus = false;
			if (c == '-') {
				minus = true;
				c = readByte();
			}
			long res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res = res * 10 + c - '0';
				c = readByte();
			} while (!isSpaceChar(c));
			return (minus) ? -res : res;
		}

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

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

		public long[] nextLongArray(int n) {
			long[] a = new long[n];
			for (int i = 0; i < n; i++)
				a[i] = nextLong();
			return a;
		}

		public char[][] nextCharMap(int n, int m) {
			char[][] map = new char[n][m];
			for (int i = 0; i < n; i++)
				map[i] = next().toCharArray();
			return map;
		}
	}
}

Score : 100 points

Problem Statement

You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.

0 l r b c: For each i = l, l+1, \dots, {r - 1}, set a_i \gets b \times a_i + c.

1 l r: Print \sum_{i = l}^{r - 1} a_i \bmod 998244353.

Constraints

1 \leq N, Q \leq 500000

0 \leq a_i, c < 998244353

1 \leq b < 998244353

0 \leq l < r \leq N

All values in Input are integer.

Input

Input is given from Standard Input in the following format:

N Q
a_0 a_1 ... a_{N - 1}
\textrm{Query}_0
\textrm{Query}_1
:
\textrm{Query}_{Q - 1}

Output

For each query of the latter type, print the answer.

Sample Input 1

5 7
1 2 3 4 5
1 0 5
0 2 4 100 101
1 0 3
0 1 3 102 103
1 2 5
0 2 5 104 105
1 0 5

Sample Output 1

15
404
41511
4317767


import java.util.*;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int D = sc.nextInt();
    int T = sc.nextInt();
    int S = sc.nextInt();

    if (D <= T * S) {
      System.out.println("Yes");
    } else {
      System.out.println("No");
    }
  }
}

Score : 100 points

Problem Statement

Takahashi is meeting up with Aoki.

They have planned to meet at a place that is D meters away from Takahashi's house in T minutes from now.

Takahashi will leave his house now and go straight to the place at a speed of S meters per minute.

Will he arrive in time?

Constraints

1 \leq D \leq 10000

1 \leq T \leq 10000

1 \leq S \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

D T S

Output

If Takahashi will reach the place in time, print Yes; otherwise, print No.

Sample Input 1

1000 15 80

Sample Output 1

Yes

It takes 12.5 minutes to go 1000 meters to the place at a speed of 80 meters per minute. They have planned to meet in 15 minutes so he will arrive in time.

Sample Input 2

2000 20 100

Sample Output 2

Yes

It takes 20 minutes to go 2000 meters to the place at a speed of 100 meters per minute. They have planned to meet in 20 minutes so he will arrive just on time.

Sample Input 3

10000 1 1

Sample Output 3

No

He will be late.


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

import static java.lang.Long.max;

public class Main {
  static class Pair {
    int num;
    int cut;

    Pair(int num, int cut) {
      this.num = num;
      this.cut = cut;
    }
  }
  public static void main(String[] args) throws IOException {
    sc = new MScanner(System.in);
    pw = new PrintWriter(System.out);
    int D = sc.nextInt();
    int T = sc.nextInt();
    int S = sc.nextInt();
    if(S * T >= D) {
      pw.println("Yes");
    } else  {
      pw.println("No");
    }

    //pw.println();
    // pw.println("end");
    // pw.println();

    pw.flush();
    // System.out.println(cnt);
  }

  /**
   * https://www.slideshare.net/hcpc_hokudai/binary-indexed-tree A space efficient version segment
   * tree. Usually for range sum. Or the required metric can be calulated in that:
   *
   *
right_metric = parant_metric - left_metric Only then, we can stop memoizing right_metric
   *
   *
The internal structure is a 1-base array, to simplify calculation of parent node's idx. lsb
   * = 3 & -3 = 2 (0x0011 & 0x1101 = 0x0001) lastParentOf3 = 3 - lsb = 2 curParentOf3 = 3 + lsb = 4
   */
  static class FenwickTree {
    private final long[] state;
    private final int size;

    FenwickTree(int size) {
      this.size = size;
      state = new long[size + 1];
    }

    @Override
    public String toString() {
      return Arrays.toString(state);
    }

    long queryRangeSumFromZeroTo(int idx) {
      long sum = 0;
      while (idx != 0) {
        sum += state[idx];
        idx -= (idx & -idx);
      }
      return sum;
    }

    /** @param val can be negative */
    void updateElement(int idx, long val) {
      while (idx <= size) {
        state[idx] += val;
        idx += (idx & -idx);
      }
    }
  }

  // sc.close();
  // pw.println(cnt);
  // pw.flush();

  static PrintWriter pw;
  static MScanner sc;

  static class MScanner {
    StringTokenizer st;
    BufferedReader br;

    public MScanner(InputStream system) {
      br = new BufferedReader(new InputStreamReader(system));
    }

    public MScanner(String file) throws Exception {
      br = new BufferedReader(new FileReader(file));
    }

    public String next() throws IOException {
      while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
      return st.nextToken();
    }

    public int[] intArr(int n) throws IOException {
      int[] in = new int[n];
      for (int i = 0; i < n; i++) in[i] = nextInt();
      return in;
    }

    public long[] longArr(int n) throws IOException {
      long[] in = new long[n];
      for (int i = 0; i < n; i++) in[i] = nextLong();
      return in;
    }

    public int[] intSortedArr(int n) throws IOException {
      int[] in = new int[n];
      for (int i = 0; i < n; i++) in[i] = nextInt();
      shuffle(in);
      Arrays.sort(in);
      return in;
    }

    public long[] longSortedArr(int n) throws IOException {
      long[] in = new long[n];
      for (int i = 0; i < n; i++) in[i] = nextLong();
      shuffle(in);
      Arrays.sort(in);
      return in;
    }

    public Integer[] IntegerArr(int n) throws IOException {
      Integer[] in = new Integer[n];
      for (int i = 0; i < n; i++) in[i] = nextInt();
      return in;
    }

    public Long[] LongArr(int n) throws IOException {
      Long[] in = new Long[n];
      for (int i = 0; i < n; i++) in[i] = nextLong();
      return in;
    }

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

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

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

    public char nextChar() throws IOException {
      return next().charAt(0);
    }

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

    public boolean ready() throws IOException {
      return br.ready();
    }

    public void waitForInput() throws InterruptedException {
      Thread.sleep(3000);
    }
  }

  static void shuffle(int[] in) {
    for (int i = 0; i < in.length; i++) {
      int idx = (int) (Math.random() * in.length);
      int tmp = in[i];
      in[i] = in[idx];
      in[idx] = tmp;
    }
  }

  static void shuffle(long[] in) {
    for (int i = 0; i < in.length; i++) {
      int idx = (int) (Math.random() * in.length);
      long tmp = in[i];
      in[i] = in[idx];
      in[idx] = tmp;
    }
  }
}


import java.util.*;

class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s = sc.next();
		String t = sc.next();
		int sol = t.length();
		for (int i = 0; i <= s.length() - t.length(); i++) {
			int count = 0;
			int k = i;
			for (int j = 0; j < t.length(); j++) {
				if (s.charAt(k) != t.charAt(j)) {
					count++;
				}
				k++;
			}
			sol = Math.min(count, sol);
		}
		System.out.println(sol);
	}

}

Score : 200 points

Problem Statement

Given are two strings S and T.

Let us change some of the characters in S so that T will be a substring of S.

At least how many characters do we need to change?

Here, a substring is a consecutive subsequence. For example, xxx is a substring of yxxxy, but not a substring of xxyxx.

Constraints

The lengths of S and T are each at least 1 and at most 1000.

The length of T is at most that of S.

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the minimum number of characters in S that need to be changed.

Sample Input 1

cabacc
abc

Sample Output 1

1

For example, changing the fourth character a in S to c will match the second through fourth characters in S to T.

Since S itself does not have T as its substring, this number of changes - one - is the minimum needed.

Sample Input 2

codeforces
atcoder

Sample Output 2

6


import java.util.*;

public class Main {
    public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	String s = sc.next();
	String t = sc.next();
	int min = Integer.MAX_VALUE;
	int count = 0;
	for (int i=0; i<=s.length()-t.length(); i++) {
	    String sis = s.substring(i,i+t.length());
	    count = 0;
	    for (int j=0; j<t.length(); j++) {
		if (sis.charAt(j) != t.charAt(j)) {
		    count++;
		}
	    }
	    if (count < min) {
		min = count;
	    }
	}
	System.out.print(count);
    }
}


import java.util.Scanner;
import java.util.HashSet;
import java.util.ArrayList;

class Main{
	public static void main(String args[]){
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();
		HashSet<Integer> hs = new HashSet<>();
		ArrayList<HashSet<Integer>> groups = new ArrayList<>();
		for(int i=1;i<=n;i++)
			hs.add(i);
		for(int i=0;i<m;i++){
			int a = sc.nextInt();
			int b = sc.nextInt();
			if (hs.contains(a)){
				boolean added = false;
				hs.remove(a);
				for(int j=0;j<groups.size();j++){
					if (groups.get(j).contains(b)){
						groups.get(j).add(a);
						added = true;
					}
				}
				if (!added){
					HashSet<Integer> hs2 = new HashSet<Integer>();
					hs2.add(a);
					groups.add(hs2);
				}
			}
			if (hs.contains(b)){
				boolean added = false;
				for(int j=0;j<groups.size();j++){
					if(groups.get(j).contains(a)){
						groups.get(j).add(b);
						added = true;
					}
				}
				if (!added){
					HashSet<Integer> hs2 = new HashSet<Integer>();
					hs2.add(a);
					groups.add(hs2);
				}
			}
		}
		int max = 0;
		for(int i=0;i<groups.size();i++){
			if (max < groups.get(i).size())
				max = groups.get(i).size();
		}
		System.out.println(max);
		sc.close();
	}
}

Score : 400 points

Problem Statement

There are N persons called Person 1 through Person N.

You are given M facts that "Person A_i and Person B_i are friends." The same fact may be given multiple times.

If X and Y are friends, and Y and Z are friends, then X and Z are also friends. There is no friendship that cannot be derived from the M given facts.

Takahashi the evil wants to divide the N persons into some number of groups so that every person has no friend in his/her group.

At least how many groups does he need to make?

Constraints

2 \leq N \leq 2\times 10^5

0 \leq M \leq 2\times 10^5

1\leq A_i,B_i\leq N

A_i \neq B_i

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
\vdots
A_M B_M

Output

Print the answer.

Sample Input 1

5 3
1 2
3 4
5 1

Sample Output 1

3

Dividing them into three groups such as \{1,3\}, \{2,4\}, and \{5\} achieves the goal.

Sample Input 2

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

Sample Output 2

4

Sample Input 3

10 4
3 1
4 1
5 9
2 6

Sample Output 3

3


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ

		Scanner sc = new Scanner (System.in);

		int n = sc.nextInt();
		int x = sc.nextInt();
		int t = sc.nextInt();
		int min =0;

		if(n%x==0) {
			min = (n/x)*t;
		}else if(n%x != 0) {
			min = (n/x+1)*t;
		}

		System.out.println(min);

	}

}

Score : 100 points

Problem Statement

Takahashi loves takoyaki - a ball-shaped snack.

With a takoyaki machine, he can make at most X pieces of takoyaki at a time, taking T minutes regardless of the number of pieces to make.

How long does it take to make N takoyaki?

Constraints

1 \leq N,X,T \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X T

Output

Print an integer representing the minimum number of minutes needed to make N pieces of takoyaki.

Sample Input 1

20 12 6

Sample Output 1

12

He can make 12 pieces of takoyaki in the first 6 minutes and 8 more in the next 6 minutes, so he can make 20 in a total of 12 minutes.

Note that being able to make 12 in 6 minutes does not mean he can make 2 in 1 minute.

Sample Input 2

1000 1 1000

Sample Output 2

1000000

It seems to take a long time to make this kind of takoyaki.


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();
		int x = sc.nextInt();
		int t = sc.nextInt();

		if(n%x==0) {
			n--;
		}
		System.out.println(((n/x)+1)*t);
	}

}


import java.io.*;

public class Main {

	public static void main(String[] args) {
		int sum = 0;

		try(FileReader fw = new FileReader("data.txt");) {
			int input = fw.read();
			while(input != -1) {
				sum += input;
			}
		} catch (Exception e) {
			;
		}
		if(sum%9 == 0) {
			System.out.print("Yes");
		} else {
			System.out.print("No");
		}

	}

}

Score : 200 points

Problem Statement

An integer N is a multiple of 9 if and only if the sum of the digits in the decimal representation of N is a multiple of 9.

Determine whether N is a multiple of 9.

Constraints

0 \leq N < 10^{200000}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is a multiple of 9, print Yes; otherwise, print No.

Sample Input 1

123456789

Sample Output 1

Yes

The sum of these digits is 1+2+3+4+5+6+7+8+9=45, which is a multiple of 9, so 123456789 is a multiple of 9.

Sample Input 2

0

Sample Output 2

Yes

Sample Input 3

31415926535897932384626433832795028841971693993751058209749445923078164062862089986280

Sample Output 3

No


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

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

    static class CStep {
        public void solve(int testNumber, MyScanner sc, PrintWriter out) {
            int N = sc.nextInt();
            int[] vals = sc.nextIntArray(N);
            long ans = 0, max = vals[0];
            for (int i = 1; i < N; i++) {
                ans += Math.max(0, max - vals[i]);
                max = Math.max(max, vals[i]);
            }
            out.println(ans);
        }

    }

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

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

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

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

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

    }
}

Score : 300 points

Problem Statement

N persons are standing in a row. The height of the i-th person from the front is A_i.

We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:

Condition: Nobody in front of the person is taller than the person. Here, the height of a person includes the stool.

Find the minimum total height of the stools needed to meet this goal.

Constraints

1 \leq N \leq 2\times 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print the minimum total height of the stools needed to meet the goal.

Sample Input 1

5
2 1 5 4 3

Sample Output 1

4

If the persons stand on stools of heights 0, 1, 0, 1, and 2, respectively, their heights will be 2, 2, 5, 5, and 5, satisfying the condition.

We cannot meet the goal with a smaller total height of the stools.

Sample Input 2

5
3 3 3 3 3

Sample Output 2

0

Giving a stool of height 0 to everyone will work.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) throws IOException {
        InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8);
        BufferedReader in = new BufferedReader(reader);
        long size = Long.parseLong(in.readLine());
        String[] str = in.readLine().split(" ");
        long num1 = 0;
        long num2 = 0;
        long step = 0;
        long res = 0;

        for(int i=0; i < size-1; i++) {
        	num1 = Long.parseLong(str[i]) + step;
        	num2 = Long.parseLong(str[i+1]);

        	if(num1 > num2) {
        		step = num1 - num2;
        		res += step;
        	}else {
        		step = 0;
        	}
        }

        System.out.println(res);

    }
}


import java.io.IOException;
import java.util.Scanner;

public class Main {

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

		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int[] A = new int[N];
		for(int i=0; i<N; i++) A[i]=sc.nextInt();

		int old_hight = 0;
		int sum = 0;

		for(int h : A) {
			if(old_hight!=0){
				if(h >= old_hight) {
					old_hight=h;
				}
				else {
					int s = h - old_hight;
					sum = sum + s;
					old_hight = h;
				}
			}
		}

		System.out.println(sum);

	}
}


import java.util.Scanner;

public class Main {

	public static void main(final String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int[] a = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = sc.nextInt();
		}
		int r = 0;
		for (int i=1;i<n;i++) {
			if (a[i] < a[i - 1]) {
				r += a[i - 1] - a[i];
				a[i] = a[i - 1];
			}
		}
		System.out.println(r);
	}
}


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int count = 0;
        int N = sc.nextInt();
        int [] arr = new int[N];

        for(int i = 0; i < N; i++) {
            arr[i] = sc.nextInt();
        }

        for(int i = 0; i < N; i++) {
            for(int j = i + 1; j < N; j++) {
                if(arr[i] != arr[j]) {
                    for(int k = j + 1; k < N; k++) {
                        if(arr[k] != arr[i] && arr[k] != arr[j]) {
                            if(isTriangle(arr[i], arr[j], arr[k])) {
                                count++;
                            }
                        }
                    }
                }
            }
        }

        System.out.println(count);
    }

    public static boolean isTriangle(int a, int b, int c) {
        if((a + b > c) && (a + c > b) && (c + b > a)) {
            return true;
        } else  {
            return false;
        }
    }
}

Score : 200 points

Problem Statement

We have sticks numbered 1, \cdots, N. The length of Stick i (1 \leq i \leq N) is L_i.

In how many ways can we choose three of the sticks with different lengths that can form a triangle?

That is, find the number of triples of integers (i, j, k) (1 \leq i < j < k \leq N) that satisfy both of the following conditions:

L_i, L_j, and L_k are all different.

There exists a triangle whose sides have lengths L_i, L_j, and L_k.

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 \cdots L_N

Output

Print the number of ways to choose three of the sticks with different lengths that can form a triangle.

Sample Input 1

5
4 4 9 7 5

Sample Output 1

5

The following five triples (i, j, k) satisfy the conditions: (1, 3, 4), (1, 4, 5), (2, 3, 4), (2, 4, 5), and (3, 4, 5).

Sample Input 2

6
4 5 4 3 3 5

Sample Output 2

8

We have two sticks for each of the lengths 3, 4, and 5. To satisfy the first condition, we have to choose one from each length.

There is a triangle whose sides have lengths 3, 4, and 5, so we have 2 ^ 3 = 8 triples (i, j, k) that satisfy the conditions.

Sample Input 3

10
9 4 6 1 9 6 10 6 6 8

Sample Output 3

39

Sample Input 4

2
1 1

Sample Output 4

0

No triple (i, j, k) satisfies 1 \leq i < j < k \leq N, so we should print 0.


import java.util.*;

class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		long X = sc.nextLong();
		long K = sc.nextLong();
		long D = sc.nextLong();
		sc.close();
		long c = 0;
		long x_ = X;
		/*while(x_ != X%D){
			if(c == K){
				break;
			}
			if(x_ > 0){
				x_ -= D;
			}else{
				x_ += D;
			}
			c++;
			System.out.println("["+c+"]"+x_);
		}*/
		c = (-(X % D) + x_) / D;
		x_ -= D*c;
		if(c==K){
			System.out.println(Math.abs(x_));
		}else if(c>K){
			x_ += D*(c-K);
			System.out.println(Math.abs(x_));
		}else{
			if((K-c) % 2 == 0){
				System.out.println(Math.abs(x_));
			}else{
				if(x_>0){
					System.out.println(Math.abs(x_-D));
				}else{
					System.out.println(Math.abs(x_+D));
				}
			}
		}
	}
}

Score : 300 points

Problem Statement

Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.

More specifically, in one move, he can go from coordinate x to x + D or x - D.

He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.

Find the minimum possible absolute value of the coordinate of the destination.

Constraints

-10^{15} \leq X \leq 10^{15}

1 \leq K \leq 10^{15}

1 \leq D \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X K D

Output

Print the minimum possible absolute value of the coordinate of the destination.

Sample Input 1

6 2 4

Sample Output 1

2

Takahashi is now at coordinate 6. It is optimal to make the following moves:

Move from coordinate 6 to (6 - 4 =) 2.

Move from coordinate 2 to (2 - 4 =) -2.

Here, the absolute value of the coordinate of the destination is 2, and we cannot make it smaller.

Sample Input 2

7 4 3

Sample Output 2

1

Takahashi is now at coordinate 7. It is optimal to make, for example, the following moves:

Move from coordinate 7 to 4.

Move from coordinate 4 to 7.

Move from coordinate 7 to 4.

Move from coordinate 4 to 1.

Here, the absolute value of the coordinate of the destination is 1, and we cannot make it smaller.

Sample Input 3

10 1 2

Sample Output 3

8

Sample Input 4

1000000000000000 1000000000000000 1000000000000000

Sample Output 4

1000000000000000

The answer can be enormous.


import java.util.*;
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        Scanner sc=new Scanner(System.in);
        long x=sc.nextLong();
        long k=sc.nextLong();
        long d=sc.nextLong();
        if(x==k && k==d)
        {
        	System.out.println(x);

            System.exit(0);
        }
        x=Math.abs(x);
        k=k-(x/d);
        x=x%d;
        if(k<=0)
        {
        	System.out.println((x-(k*d)));
        	System.exit(0);
        }
        else
        {
        	if(k%2==1)
        		System.out.println(Math.abs(x-d));
        	else
        		System.out.println(x);
        }

	}

}


import java.util.*;

public class Main{
    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args){
        int n = Integer.parseInt(sc.next());
        int k = Integer.parseInt(sc.next());

        int[] p = new int[n];
        int[] c = new int[n];
        for(int i=0; i<n; i++){
            p[i] = Integer.parseInt(sc.next())-1;
        }
        for(int i=0; i<n; i++){
            c[i] = Integer.parseInt(sc.next());
        }

        int[][] dbgp = new int[45][n];
        long[][] dbgc = new long[45][n];
        for(int i=0; i<n; i++){
            dbgp[0][i] = p[i];
            dbgc[0][i] = c[p[i]];
        }
        for(int i=0; i<43; i++){
            for(int j=0; j<n; j++){
                dbgp[i+1][j] = dbgp[i][dbgp[i][j]];
                dbgc[i+1][j] = dbgc[i][j]+dbgc[i][dbgp[i][j]];
            }
        }

        long max = -(long)1e18;
        for(int i=0; i<n; i++){
            long ans = 0;
            int now = i;
            for(int j=0; j<Math.min(5050, k); j++){
                ans += c[p[now]];
                now = p[now];
                max = Math.max(ans, max);
            }
        }

        for(int d=0; d<n; d++){
            for(int i=0; i<n; i++){
                long ans = 0;
                int idx = 0;
                int t = k-d;
                int now = i;
                while(t > 0){
                    if(t%2==1){
                        ans += dbgc[idx][now];
                        now = dbgp[idx][now];
                    }
                    t/=2;
                    idx++;
                }
                max = Math.max(max, ans);
            }
        }

        System.out.println(max);
    }
}

Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

Print the maximum possible score at the end of the game.

Sample Input 1

5 2
2 4 5 1 3
3 4 -10 -8 8

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.


import java.io.InputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
public class Main {
	public static void main(String[] args)throws Exception{
		PrintWriter out = new PrintWriter(System.out);
		int N=nextInt();
		long K=nextInt();
		int P[]=new int[N];
		long C[]=new long[N];
		long ans=(long)Math.pow(-10,18)*-1-3,U=K;
		for(int i=0;i<N;i++){
			P[i]=nextInt()-1;
		}
		for(int i=0;i<N;i++){
			C[i]=nextInt();
		}
		for(int i=0;i<N;i++){
			long R[]=new long[N];
			boolean V[]=new boolean[N];
			int p[]=new int[N];
			int now=i;
			K=U;
			for(int j=0;j<N+1;j++){
				if(V[now]==false){
					V[now]=true;
					p[now]=j;
					if(j!=0)
						R[j]=C[P[now]]+R[j-1];
					else
						R[j]=C[P[now]];
					now=P[now];
				}
				else{
					if(j>K)
						for(int k=0;k<K;k++){
							if(ans<R[k])
								ans=R[k];
						}
					else{
						long n=0;
						if(p[now]!=0)
							n=R[p[now]-1];
						if(R[j-1]-n<=0){
							for(int k=0;k<N;k++){
								if(ans<R[k])
									ans=R[k];
							}
							break;
						}
						long max=0;
						if(p[now]!=0){
							max=n;
							K-=p[now];
						}
						long cnt=j-p[now];
						if(K%cnt==0){
							cnt=K/cnt-1;
							max+=cnt*(R[j-1]-n);
						}
						else{
							cnt=K/cnt;
							max+=cnt*(R[j-1]-n);
						}
						K-=cnt*(j-p[now]);
						long m=R[p[now]]-n;
						for(int k=1;k<K;k++){
							if(m<R[k+p[now]]-n)
								m=R[k+p[now]]-n;
						}
						if(ans<max+m)
							ans=max+m;
					}
					break;
				}
			}
		}
		System.out.println(ans);
	}
	public static long lmod(long i, long j) {
	     return (i%j)<0?(i%j)+0+(j<0?-j:j):(i%j+0);
	 }
	static boolean isOK(int index,int key,int[]a){
		if (a[index]>=key) return true;
	    else return false;
	}
	static int binary_search(int key,int[] a) {
	    int ng = -1; //「index = 0」が条件を満たすこともあるので、初期値は -1
	    int ok = (int)a.length; // 「index = a.size()-1」が条件を満たさないこともあるので、初期値は a.size()
	    while (Math.abs(ok - ng) > 1) {
	        int mid = (ok + ng) / 2;
	        if (isOK(mid,key,a)) ok = mid;
	        else ng = mid;
	    }
	    return ok;
	}
	//FastScanner
	static InputStream in = System.in;
	static  byte[] buffer = new byte[1024];
	static int length = 0, p = 0;
	public static boolean hasNextByte () {
		if (p < length) return true;
		else {
			p = 0;
			try {length = in.read(buffer);}
			catch (Exception e) {e.printStackTrace();}
			if (length == 0) return false;
		}
		return true;
	}
	public static int readByte () {
		if (hasNextByte() == true) return buffer[p++];
		return -1;
	}
	public static boolean isPrintable (int n) {return 33<=n&&n<=126;}
	public static void skip () {
		while (hasNextByte() && !isPrintable(buffer[p])) p++;
	}
	public static boolean hasNext () {skip(); return hasNextByte();}
	public static String next () {
		if (!hasNext()) throw new NoSuchElementException();
		StringBuilder sb = new StringBuilder();
		int temp = readByte();
		while (isPrintable(temp)) {
			sb.appendCodePoint(temp);
			temp = readByte();
		}
		return sb.toString();
	}
	public static int nextInt () {return Math.toIntExact(nextLong());}
	public static int[] nextInts (int n) {
		int[] ar = new int[n];
		for (int i=0; i<n; i++) ar[i] = nextInt();
		return ar;
	}
	public static long nextLong () {
		if (!hasNext()) throw new NoSuchElementException();
		boolean minus = false;
		int temp = readByte();
		if (temp == '-') {
			minus = true;
			temp = readByte();
		}
		if (temp<'0' || '9'<temp) throw new NumberFormatException();
		long n = 0;
		while (isPrintable(temp)) {
			if ('0'<=temp && temp<='9') {
				n *= 10;
				n += temp - '0';
			}
			temp = readByte();
		}
		return minus? -n : n;
	}
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.stream.IntStream;
import java.util.Arrays;
import java.util.stream.LongStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedOutputStream;
import java.io.UncheckedIOException;
import java.nio.charset.Charset;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;

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

    static class DMovingPiece {
        static int n;
        static int[][] p;
        static long[][] c;

        public void solve(int testNumber, LightScanner in, LightWriter out) {
            n = in.ints();
            p = new int[n][30];
            c = new long[n][30];
            IntUnionFind uf = new IntUnionFind(n);
            long k = in.longs();
            for (int i = 0; i < n; i++) {
                p[i][0] = in.ints() - 1;
                uf.union(i, p[i][0]);
            }
            long[] c0 = in.longs(n);
            for (int i = 0; i < n; i++) c[i][0] = c0[p[i][0]];
            for (int i = 1; i < 30; i++) {
                for (int j = 0; j < n; j++) {
                    int t = p[j][i - 1];
                    p[j][i] = p[t][i - 1];
                    c[j][i] = c[j][i - 1] + c[t][i - 1];
                }
            }

            long ans = Long.MIN_VALUE;
            for (int i = 0; i < n; i++) {
                ans = Math.max(ans, sum(i, k));
                for (int j = 1; j <= uf.size(i); j++) {
                    ans = Math.max(ans, sum(i, j));
                    ans = Math.max(ans, sum(i, k - j));
                }
            }
            out.ans(ans).ln();
        }

        private static long sum(int now, long k) {
            if (k <= 0) return Long.MIN_VALUE;
            long res = 0;
            for (int j = 29; j >= 0; j--) {
                if (((1L << j) & k) == 0) continue;
                res += c[now][j];
                now = p[now][j];
            }
            return res;
        }

    }

    static final class IntUnionFind {
        private int groups;
        private final int[] nodes;
        private final int[] rank;

        public IntUnionFind(int n) {
            groups = n;
            nodes = new int[n];
            Arrays.fill(nodes, -1);
            rank = new int[n];
        }

        public int find(int i) {
            int ans = nodes[i];
            if (ans < 0) {
                return i;
            } else {
                return nodes[i] = find(ans);
            }
        }

        public int size(int i) {
            return -nodes[find(i)];
        }

        public boolean union(int x, int y) {
            x = find(x);
            y = find(y);
            if (x == y) {
                return false;
            } else if (rank[x] < rank[y]) {
                nodes[y] += nodes[x];
                nodes[x] = y;
            } else if (rank[x] == rank[y]) {
                rank[x]++;
                nodes[x] += nodes[y];
                nodes[y] = x;
            } else {
                nodes[x] += nodes[y];
                nodes[y] = x;
            }
            groups--;
            return true;
        }

    }

    static class LightScanner implements AutoCloseable {
        private BufferedReader reader = null;
        private StringTokenizer tokenizer = null;

        public LightScanner(InputStream in) {
            reader = new BufferedReader(new InputStreamReader(in));
        }

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

        public int ints() {
            return Integer.parseInt(string());
        }

        public long longs() {
            return Long.parseLong(string());
        }

        public long[] longs(int length) {
            return IntStream.range(0, length).mapToLong(x -> longs()).toArray();
        }

        public void close() {
            try {
                this.reader.close();
            } catch (IOException ex) {
                throw new UncheckedIOException(ex);
            }
        }

    }

    static class LightWriter implements AutoCloseable {
        private final Writer out;
        private boolean autoflush = false;
        private boolean breaked = true;

        public LightWriter(Writer out) {
            this.out = out;
        }

        public LightWriter(OutputStream out) {
            this(new OutputStreamWriter(new BufferedOutputStream(out), Charset.defaultCharset()));
        }

        public LightWriter print(char c) {
            try {
                out.write(c);
                breaked = false;
            } catch (IOException ex) {
                throw new UncheckedIOException(ex);
            }
            return this;
        }

        public LightWriter print(String s) {
            try {
                out.write(s, 0, s.length());
                breaked = false;
            } catch (IOException ex) {
                throw new UncheckedIOException(ex);
            }
            return this;
        }

        public LightWriter ans(String s) {
            if (!breaked) {
                print(' ');
            }
            return print(s);
        }

        public LightWriter ans(long l) {
            return ans(Long.toString(l));
        }

        public LightWriter ln() {
            print(System.lineSeparator());
            breaked = true;
            if (autoflush) {
                try {
                    out.flush();
                } catch (IOException ex) {
                    throw new UncheckedIOException(ex);
                }
            }
            return this;
        }

        public void close() {
            try {
                out.close();
            } catch (IOException ex) {
                throw new UncheckedIOException(ex);
            }
        }

    }
}