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

class Brackets{
	int min, sum;
	public Brackets(int min, int sum) {
		super();
		this.min = min;
		this.sum = sum;
	}
}

public class Main {
	static String no = "No", yes = "Yes";
	static void solve() {
		int n = ni();
		List<Brackets> lBra = new ArrayList<>();
		List<Brackets> rBra = new ArrayList<>();

		for(int i=0;i<n;i++) {
			char s[] = ns().toCharArray();
			int l = 0, r = 0;
			int lmin = inf;
			for(int j=0;j<s.length;j++) {
				if(s[j]=='(')l++;
				else r++;
				lmin = min(lmin, l - r);
			}

			if(l-r>0)lBra.add(new Brackets(lmin, l-r));
			else {
				int rmin = inf;
				l = 0; r = 0;
				for(int j=s.length;j>=0;j--) {
					if(s[j]=='(')l++;
					else r++;
					rmin = min(rmin, r-l);
				}
				rBra.add(new Brackets(rmin, r-l));
			}
		}
		//登りの山を作る
		int sz = lBra.size();
		Collections.sort(lBra, (l1, l2)->{
			if(l1.min == l2.min) return l2.sum - l1.sum;
			return l2.min - l1.min;
		});
		int lsum = 0;
		for(int i=0;i<sz;i++) {
			if(lsum + lBra.get(i).min < 0) {
				out.println(no);
				return;
			}
			lsum += lBra.get(i).sum;
		}
		//下りの山を作る　rとlを反転して登りの山と思えばいい
		//rBraを作る時点で反転処理は済ませてある
		sz = rBra.size();
		Collections.sort(rBra, (l1, l2)->{
			if(l1.min == l2.min) return l2.sum - l1.sum;
			return l2.min - l1.min;
		});
		int rsum = 0;
		for(int i=0;i<sz;i++) {
			if(rsum + rBra.get(i).min < 0) {
				out.println(no);
				return;
			}
			rsum += rBra.get(i).sum;
		}
		if(lsum == rsum) out.println(yes);
		else out.println(no);
	}

	//constant
	static final long mod = (long) 1e9 + 7;
	static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };
	static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 };
	static final int inf = Integer.MAX_VALUE / 2;
	static final long linf = Long.MAX_VALUE / 3;
	static final double dinf = Double.MAX_VALUE / 3;
	static final double eps = 1e-10;
	static final double pi = Math.PI;
	static StringBuilder sb = new StringBuilder();
	static InputStream is;
	static PrintWriter out;
	static String INPUT = "";

	//libraries
	static void reverse(int ar[]) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			int t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static void reverse(long ar[]) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			long t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static void reverse(double ar[]) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			double t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static void reverse(char ar[]) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			char t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static String getReverse(String s) {
		char c[] = s.toCharArray();
		reverse(c);
		s = String.valueOf(c);
		return s;
	}

	static <T> void reverse(List<T> ls) {
		int sz = ls.size();
		for (int i = 0; i < sz / 2; i++) {
			T t = ls.get(i);
			ls.set(i, ls.get(sz - 1 - i));
			ls.set(sz - 1 - i, t);
		}
	}

	static <T> void reverse(T[] ar) {
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			T t = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = t;
		}
	}

	static void sbnl() {//StringBuilderに改行文字をappendする
		sb.append("\n");
	}

	static int lowerBound(int[] a, int x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] < x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int upperBound(int[] a, int x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] <= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rlowerBound(int[] a, int x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] > x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rupperBound(int[] a, int x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] >= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int lowerBound(long[] a, long x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] < x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int upperBound(long[] a, long x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] <= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rlowerBound(long[] a, long x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] > x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rupperBound(long[] a, long x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] >= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int lowerBound(double[] a, double x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] < x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int upperBound(double[] a, double x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] <= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rlowerBound(double[] a, double x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] > x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rupperBound(double[] a, double x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] >= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int lowerBound(char[] a, char x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] < x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int upperBound(char[] a, char x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] <= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rlowerBound(char[] a, char x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] > x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static int rupperBound(char[] a, char x) {
		int l = -1, r = a.length;
		while (r - l > 1) {
			int c = (l + r) / 2;
			if (a[c] >= x) {
				l = c;
			} else {
				r = c;
			}
		}
		return r;
	}

	static <T> int lowerBound(List<T> ls, T x) throws RuntimeException {
		if (ls.size() == 0)
			return -1;
		if (ls.get(0) instanceof Integer) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) >= 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Long) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) >= 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Double) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) >= 0 ? 1 : -1);
		} else {
			System.err.println(
					String.format("%s:数値でないリストを二分探索しています。", Thread.currentThread().getStackTrace()[1].getMethodName()));
			throw new RuntimeException();
		}
	}

	static <T> int upperBound(List<T> ls, T x) throws RuntimeException {
		if (ls.size() == 0)
			return -1;
		if (ls.get(0) instanceof Integer) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) > 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Long) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) > 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Double) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) > 0 ? 1 : -1);
		} else {
			System.err.println(
					String.format("%s:数値でないリストを二分探索しています。", Thread.currentThread().getStackTrace()[1].getMethodName()));
			throw new RuntimeException();
		}
	}

	static <T> int rupperBound(List<T> ls, T x) throws RuntimeException {
		if (ls.size() == 0)
			return -1;
		if (ls.get(0) instanceof Integer) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) < 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Long) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) < 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Double) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) < 0 ? 1 : -1);
		} else {
			System.err.println(
					String.format("%s:数値でないリストを二分探索しています。", Thread.currentThread().getStackTrace()[1].getMethodName()));
			throw new RuntimeException();
		}
	}

	static <T> int rlowerBound(List<T> ls, T x) {
		if (ls.size() == 0)
			return -1;
		if (ls.get(0) instanceof Integer) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) <= 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Long) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) <= 0 ? 1 : -1);
		} else if (ls.get(0) instanceof Double) {
			return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) <= 0 ? 1 : -1);
		} else {
			System.err.println(
					String.format("%s:数値でないリストを二分探索しています。", Thread.currentThread().getStackTrace()[1].getMethodName()));
			throw new RuntimeException();
		}
	}

	static int[] concat(int x, int arr[]) {
		int ret[] = new int[arr.length + 1];
		System.arraycopy(arr, 0, ret, 1, ret.length - 1);
		ret[0] = x;
		return ret;
	}

	static int[] concat(int arr[], int x) {
		int ret[] = new int[arr.length + 1];
		System.arraycopy(arr, 0, ret, 0, ret.length - 1);
		ret[ret.length - 1] = x;
		return ret;
	}

	static long[] concat(long x, long arr[]) {
		long ret[] = new long[arr.length + 1];
		System.arraycopy(arr, 0, ret, 1, ret.length - 1);
		ret[0] = x;
		return ret;
	}

	static long[] concat(long arr[], long x) {
		long ret[] = new long[arr.length + 1];
		System.arraycopy(arr, 0, ret, 0, ret.length - 1);
		ret[ret.length - 1] = x;
		return ret;
	}

	static char[] concat(char x, char arr[]) {
		char ret[] = new char[arr.length + 1];
		System.arraycopy(arr, 0, ret, 0, ret.length - 1);
		ret[ret.length - 1] = x;
		return ret;
	}

	static char[] concat(char arr[], char x) {
		char ret[] = new char[arr.length + 1];
		System.arraycopy(arr, 0, ret, 0, ret.length - 1);
		ret[ret.length - 1] = x;
		return ret;
	}

	static int max(int x, int y) {
		return Math.max(x, y);
	}

	static int min(int x, int y) {
		return Math.min(x, y);
	}

	static int max(int x, int y, int z) {
		x = Math.max(x, y);
		x = Math.max(x, z);
		return x;
	}

	static int min(int x, int y, int z) {
		x = Math.min(x, y);
		x = Math.min(x, z);
		return x;
	}

	static long max(long x, long y) {
		return Math.max(x, y);
	}

	static long min(long x, long y) {
		return Math.min(x, y);
	}

	static long max(long x, long y, long z) {
		x = Math.max(x, y);
		x = Math.max(x, z);
		return x;
	}

	static long min(long x, long y, long z) {
		x = Math.min(x, y);
		x = Math.min(x, z);
		return x;
	}

	static double max(double x, double y) {
		return Math.max(x, y);
	}

	static double min(double x, double y) {
		return Math.min(x, y);
	}

	static double max(double x, double y, double z) {
		x = Math.max(x, y);
		x = Math.max(x, z);
		return x;
	}

	static double min(double x, double y, double z) {
		x = Math.min(x, y);
		x = Math.min(x, z);
		return x;
	}

	static void sort(int[] ar) {
		Arrays.sort(ar);
	}

	static void sort(long[] ar) {
		Arrays.sort(ar);
	}

	static void sort(double[] ar) {
		Arrays.sort(ar);
	}

	static void sort(char[] ar) {
		Arrays.sort(ar);
	}

	static void rsort(int[] ar) {
		Arrays.sort(ar);
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			int tmp = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = tmp;
		}
	}

	static void rsort(long[] ar) {
		Arrays.sort(ar);
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			long tmp = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = tmp;
		}
	}

	static void rsort(double[] ar) {
		Arrays.sort(ar);
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			double tmp = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = tmp;
		}
	}

	static void rsort(char[] ar) {
		Arrays.sort(ar);
		int len = ar.length;
		for (int i = 0; i < len / 2; i++) {
			char tmp = ar[i];
			ar[i] = ar[len - 1 - i];
			ar[len - 1 - i] = tmp;
		}
	}

	static void fill(int arr[], int x) {
		Arrays.fill(arr, x);
	}

	static void fill(long arr[], long x) {
		Arrays.fill(arr, x);
	}

	static void fill(boolean arr[], boolean x) {
		Arrays.fill(arr, x);
	}

	static void fill(double arr[], double x) {
		Arrays.fill(arr, x);
	}

	static void fill(int arr[][], int x) {
		for (int i = 0; i < arr.length; i++)
			Arrays.fill(arr[i], x);
	}

	static void fill(long arr[][], long x) {
		for (int i = 0; i < arr.length; i++)
			Arrays.fill(arr[i], x);
	}

	static void fill(double arr[][], double x) {
		for (int i = 0; i < arr.length; i++)
			Arrays.fill(arr[i], x);
	}

	static void fill(boolean arr[][], boolean x) {
		for (int i = 0; i < arr.length; i++)
			Arrays.fill(arr[i], x);
	}

	//MOD culc
	static long plus(long x, long y) {
		long res = (x + y) % mod;
		return res < 0 ? res + mod : res;
	}

	static long sub(long x, long y) {
		long res = (x - y) % mod;
		return res < 0 ? res + mod : res;
	}

	static long mul(long x, long y) {
		long res = (x * y) % mod;
		return res < 0 ? res + mod : res;
	}

	static long div(long x, long y) {
		long res = x * pow(y, mod - 2) % mod;
		return res < 0 ? res + mod : res;
	}

	static long pow(long x, long y) {
		if (y < 0)
			return 0;
		if (y == 0)
			return 1;
		if (y % 2 == 1)
			return (x * pow(x, y - 1)) % mod;
		long root = pow(x, y / 2);
		return root * root % mod;
	}

	public static void main(String[] args) throws Exception {
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);
		solve();
		out.flush();
	}

	//input
	private static byte[] inbuf = new byte[1024];
	static int lenbuf = 0, ptrbuf = 0;

	private static int readByte() {
		if (lenbuf == -1)
			throw new InputMismatchException();
		if (ptrbuf >= lenbuf) {
			ptrbuf = 0;
			try {
				lenbuf = is.read(inbuf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (lenbuf <= 0)
				return -1;
		}
		return inbuf[ptrbuf++];
	}

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

	private static int skip() {
		int b;
		while ((b = readByte()) != -1 && isSpaceChar(b))
			;
		return b;
	}

	@SuppressWarnings("unused")
	private static double nd() {
		return Double.parseDouble(ns());
	}

	@SuppressWarnings("unused")
	private static char nc() {
		return (char) skip();
	}

	private static String ns() {
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(isSpaceChar(b))) {
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private static char[] ns(int n) {
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while (p < n && !(isSpaceChar(b))) {
			buf[p++] = (char) b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	@SuppressWarnings("unused")
	private static char[][] nm(int n, int m) {
		char[][] map = new char[n][];
		for (int i = 0; i < n; i++)
			map[i] = ns(m);
		return map;
	}

	@SuppressWarnings("unused")
	private static int[] na(int n) {
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}

	@SuppressWarnings("unused")
	private static long[] nla(int n) {
		long[] a = new long[n];
		for (int i = 0; i < n; i++)
			a[i] = nl();
		return a;
	}

	private static int ni() {
		int num = 0, b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	@SuppressWarnings("unused")
	private static long nl() {
		long num = 0;
		int b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

}

Score : 600 points

Problem Statement

A bracket sequence is a string that is one of the following:

An empty string;

The concatenation of (, A, and ) in this order, for some bracket sequence A ;

The concatenation of A and B in this order, for some non-empty bracket sequences A and B /

Given are N strings S_i. Can a bracket sequence be formed by concatenating all the N strings in some order?

Constraints

1 \leq N \leq 10^6

The total length of the strings S_i is at most 10^6.

S_i is a non-empty string consisting of ( and ).

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

If a bracket sequence can be formed by concatenating all the N strings in some order, print Yes; otherwise, print No.

Sample Input 1

2
)
(()

Sample Output 1

Yes

Concatenating (() and ) in this order forms a bracket sequence.

Sample Input 2

2
)(
()

Sample Output 2

No

Sample Input 3

4
((()))
((((((
))))))
()()()

Sample Output 3

Yes

Sample Input 4

3
(((
)
)

Sample Output 4

No


public class Main {
    public static void main(String[] args) {
        long x = (1L << 32) - 1 ;
        long n = (int)1e8;
        long p = 1;

        for (int i = 1; i <= n; i++) {
            p += i;
            p %= x;
        }

        System.out.println(p);
    }
}

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

Score : 100 points

Problem Statement

AtCoder Inc. holds a contest every Saturday.

There are two types of contests called ABC and ARC, and just one of them is held at a time.

The company holds these two types of contests alternately: an ARC follows an ABC and vice versa.

Given a string S representing the type of the contest held last week, print the string representing the type of the contest held this week.

Constraints

S is ABC or ARC.

Input

Input is given from Standard Input in the following format:

S

Output

Print the string representing the type of the contest held this week.

Sample Input 1

ABC

Sample Output 1

ARC

They held an ABC last week, so they will hold an ARC this week.

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.


import java.util.Scanner;

class Main{
      public static void main(String args[]){
	Scanner sc = new Scanner(System.in);
	String s = sc.next();
	if(s.equals("ABC"))
		System.out.println("ARC");
	else
		System.out.println("ABC");
      }
}


import java.util.Scanner;

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

        if(a.equals("ARC")) System.out.println("ABC");
        else System.out.println("ARC");
    }
}


import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int K = sc.nextInt();

        int[] A = new int[N];
        for (int i = 0;i < K; i++) {
            int d = sc.nextInt();
            for (int j = 0; j < d; j++) {
                int nsunuke = sc.nextInt() - 1;
                A[nsunuke] = 1;
            }
        }

        int count = 0;
        for (int i = 0;i < N; i++) {
            if(A[i] != 1) {
                count++;
            }
        }
        System.out.println(count);
    }
}

Score : 200 points

Problem Statement

N Snukes called Snuke 1, Snuke 2, ..., Snuke N live in a town.

There are K kinds of snacks sold in this town, called Snack 1, Snack 2, ..., Snack K. The following d_i Snukes have Snack i: Snuke A_{i, 1}, A_{i, 2}, \cdots, A_{i, {d_i}}.

Takahashi will walk around this town and make mischief on the Snukes who have no snacks. How many Snukes will fall victim to Takahashi's mischief?

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq K \leq 100

1 \leq d_i \leq N

1 \leq A_{i, 1} < \cdots < A_{i, d_i} \leq N

Input

Input is given from Standard Input in the following format:

N K
d_1
A_{1, 1} \cdots A_{1, d_1}
\vdots
d_K
A_{K, 1} \cdots A_{K, d_K}

Output

Print the answer.

Sample Input 1

3 2
2
1 3
1
3

Sample Output 1

1

Snuke 1 has Snack 1.

Snuke 2 has no snacks.

Snuke 3 has Snack 1 and 2.

Thus, there will be one victim: Snuke 2.

Sample Input 2

3 3
1
3
1
3
1
3

Sample Output 2

2


import java.util.*;

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

        int n = Integer.parseInt(sc.next());
        int k = Integer.parseInt(sc.next());
        int[] count = new int[n];

        for(int i = 0; i < k; i++){
            int d = Integer.parseInt(sc.next());
            int[] a = new int[d];
            for(int j = 0; j < d; j++){
                a[i] = Integer.parseInt(sc.next());
                count[a[i]]++;
            }
        }

        int ans = 0;
        for(int i = 0; i < n; i++){
            if(count[i] == 0)
                ans++;
        }

        System.out.println(ans);
    }
}


import java.util.Scanner;

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

		int n = scan.nextInt();
		int k = scan.nextInt();
		boolean[] human = new boolean[n];
		for (int i = 0; i < k; i++) {
			int d = scan.nextInt();
			for(int j = 0; j < d; j++)
				human[scan.nextInt()-1] = true;
		}
		scan.close();

		int ans = 0;
		for(boolean b : human)
			if(!b) ans++;

		System.out.println(ans);
	}

}


import java.io.*;
import java.util.*;
import java.lang.*;
public class Main{
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        solve(in, out);
        out.close();
    }
    static int L,R,top,bottom;
    // static int ans;
    public static void solve(InputReader sc, PrintWriter pw) {
        // int t=sc.nextInt();
        int t=1;
        u:while(t-->0){
            int n=sc.nextInt();
            int k=sc.nextInt();
            boolean []arr=new boolean[n];
            for(int i=0;i<k;i++){
                int d=sc.nextInt();
                for(int j=0;j<d;j++)
                    arr[sc.nextInt()-1]=true;
            }
            int ans=0;
            for(int i=0;i<n;i++)
                if(!arr[i])
                    ans++;
            pw.println(ans);
        }
    }
    static long ncr(long n, long k)
    {
        long res = 1;

        // Since C(n, k) = C(n, n-k)
        if ( k > n - k )
            k = n - k;

        // Calculate value of [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]
        for (long i = 0; i < k; ++i)
        {
            res *= (n - i);
            res /= (i + 1);
        }

        return res;
    }
    public static void sort(long []arr){
        ArrayList<Long> list=new ArrayList<>();
        for(int i=0;i<arr.length;i++)
            list.add(arr[i]);
        Collections.sort(list);
        for(int i=0;i<arr.length;i++)
            arr[i]=list.get(i);
    }
    public static void swap(char []chrr, int i, int j){
        char temp=chrr[i];
        chrr[i]=chrr[j];
        chrr[j]=temp;
    }
    public static int num(int n){
        int a=0;
        while(n>0){
            a+=(n&1);
            n>>=1;
        }
        return a;
    }
    static class Pair{
        int a, b,c,d;
        Pair(int a,int b, int c, int d){
            this.a=a;
            this.b=b;
            this.c=c;
            this.d=d;
        }
    }
        // public int compareTo(Pair p){
        //     return (b-p.b);
        // }
        // public int hashCode(){
        //     int hashcode = (a+" "+b).hashCode();
        //     return hashcode;
        // }

        // public boolean equals(Object obj){
        //     if (obj instanceof Pair) {
        //         Pair p = (Pair) obj;
        //         return (p.a==this.a && p.b == this.b);
        //     }
        //     return false;
        // }

    static boolean isPrime(int n) {
        if (n <= 1)
            return false;
        if (n <= 3)
            return true;
        if (n % 2 == 0 || n % 3 == 0)
            return false;
        for (int i = 5; i * i <= n; i = i + 6)
            if (n % i == 0 || n % (i + 2) == 0)
                return false;
        return true;
    }
    static int gcd(int a, int b) {
        if (b == 0)
            return a;
        return a>b?gcd(b, a % b):gcd(a, b % a);
    }
    static long fast_pow(long base,long n,long M){
        if(n==0)
           return 1;
        if(n==1)
        return base;
        long halfn=fast_pow(base,n/2,M);
        if(n%2==0)
            return ( halfn * halfn ) % M;
        else
            return ( ( ( halfn * halfn ) % M ) * base ) % M;
    }
    static long modInverse(long n,long M){
        return fast_pow(n,M-2,M);
    }
    public static void feedArr(long []arr,InputReader sc){
        for(int i=0;i<arr.length;i++)
            arr[i]=sc.nextLong();
    }
    public static void feedArr(double []arr,InputReader sc){
        for(int i=0;i<arr.length;i++)
            arr[i]=sc.nextDouble();
    }
    public static void feedArr(int []arr,InputReader sc){
        for(int i=0;i<arr.length;i++)
            arr[i]=sc.nextInt();
    }
    public static void feedArr(String []arr,InputReader sc){
        for(int i=0;i<arr.length;i++)
            arr[i]=sc.next();
    }
    public static String printArr(int []arr){
        StringBuilder sbr=new StringBuilder();
        for(int i:arr)
            sbr.append(i+" ");
        return sbr.toString();
    }
    public  static String printArr(long []arr){
        StringBuilder sbr=new StringBuilder();
        for(long i:arr)
            sbr.append(i+" ");
        return sbr.toString();
    }
    public static String printArr(String []arr){
        StringBuilder sbr=new StringBuilder();
        for(String i:arr)
            sbr.append(i+" ");
        return sbr.toString();
    }
    public static String printArr(double []arr){
        StringBuilder sbr=new StringBuilder();
        for(double i:arr)
            sbr.append(i+" ");
        return sbr.toString();
    }
    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }
        public int nextInt() {
            return Integer.parseInt(next());
        }
        public long nextLong() {
            return Long.parseLong(next());
        }
        public double nextDouble() {
            return Double.parseDouble(next());
        }
    }
}


import java.util.Arrays;
import java.util.Scanner;

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

		int N = sc.nextInt();
		int M = sc.nextInt();
		int H[] = new int[N];
		int COUNT[] = new int[N];
		Arrays.fill(COUNT, 0);
		int A = 0;
		int B = 0;
		for(int i=0; i<N; i++) {
			H[i] = sc.nextInt();
		}
		int count = 0;

		for(int i=0; i<M; i++) {
			A = sc.nextInt();
			B = sc.nextInt();
			if(H[A-1]<H[B-1]) {
				COUNT[A-1]=2;
				COUNT[B-1]=1;
			}else if(H[A-1]>H[B-1]) {
				COUNT[A-1]=1;
				COUNT[B-1]=2;
			}else if(H[A-1]==H[B-1]) {
				COUNT[A-1]=2;
				COUNT[B-1]=2;
			}
		}
		for(int i=0; i<N; i++) {
			if(COUNT[i]==1 || COUNT[i]==0) {
				count++;
			}
		}

		System.out.print(count);
	}
}

Score : 300 points

Problem Statement

There are N observatories in AtCoder Hill, called Obs. 1, Obs. 2, ..., Obs. N. The elevation of Obs. i is H_i.
There are also M roads, each connecting two different observatories. Road j connects Obs. A_j and Obs. B_j.

Obs. i is said to be good when its elevation is higher than those of all observatories that can be reached from Obs. i using just one road.
Note that Obs. i is also good when no observatory can be reached from Obs. i using just one road.

How many good observatories are there?

Constraints

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq H_i \leq 10^9

1 \leq A_i,B_i \leq N

A_i \neq B_i

Multiple roads may connect the same pair of observatories.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
H_1 H_2 ... H_N
A_1 B_1
A_2 B_2
:
A_M B_M

Output

Print the number of good observatories.

Sample Input 1

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

Sample Output 1

2

From Obs. 1, you can reach Obs. 3 using just one road. The elevation of Obs. 1 is not higher than that of Obs. 3, so Obs. 1 is not good.

From Obs. 2, you can reach Obs. 3 and 4 using just one road. The elevation of Obs. 2 is not higher than that of Obs. 3, so Obs. 2 is not good.

From Obs. 3, you can reach Obs. 1 and 2 using just one road. The elevation of Obs. 3 is higher than those of Obs. 1 and 2, so Obs. 3 is good.

From Obs. 4, you can reach Obs. 2 using just one road. The elevation of Obs. 4 is higher than that of Obs. 2, so Obs. 4 is good.

Thus, the good observatories are Obs. 3 and 4, so there are two good observatories.

Sample Input 2

6 5
8 6 9 1 2 1
1 3
4 2
4 3
4 6
4 6

Sample Output 2

3


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);
        Peaks solver = new Peaks();
        solver.solve(1, in, out);
        out.close();
    }

    static class Peaks {
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();

            long[] h = new long[n + 1];
            for (int i = 1; i <= n; i++) {
                h[i] = in.nextInt();
            }

            int[][] loads = new int[n + 1][n + 1];
            for (int i = 1; i <= m; i++) {
                int a = in.nextInt();
                int b = in.nextInt();

                loads[a][b] = 1;
                loads[b][a] = 1;
            }

            boolean[] result = new boolean[n + 1];
            for (int i = 1; i <= n; i++) {
                long max_cost = 0;
                int max_pos = 0;
                for (int j = 1; j <= n; j++) {
                    if (loads[i][j] != 1) {
                        continue;
                    }
                    if (max_cost < h[j]) {
                        max_cost = h[j];
                        max_pos = j;
                    }
                }
                if (max_cost == 0) {
                    result[i] = true;
                    continue;
                }
                if (h[max_pos] > h[i]) {
                    result[max_pos] = true;
                } else if (h[max_pos] < h[i]) {
                    result[i] = true;
                }

            }

            int count = 0;
            for (int i = 1; i <= n; i++) {
                if (result[i]) {
                    count++;
                }
            }
            out.append(String.valueOf(count));
        }

    }
}


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();
		int[] height = new int[n];
		for(int i=0;i<n;i++) {
			height[i]=sc.nextInt();
		}
		int[] count=new int[n];
		for(int j=0;j<m;j++) {
			int a=sc.nextInt(),b=sc.nextInt();
			if(height[a-1]>height[b-1]) count[b-1]=0;
			else count[a-1]=1;
		}
		int c=0;
		for(int i=0;i<n;i++) {
			if(count[i]==1)  c++;
		}
		System.out.println(c);
	}
}


import java.util.Scanner;

public class Main {

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

        final double x = sc.nextDouble();

        for (int i = -128; i <= 128; i++) {
            for (int j = -128; j <= 128; j++) {
                if (x == (Math.pow(i, 5) - Math.pow(j, 5))) {
                    System.out.println(i + " " + j);
                    return;
                }
            }
        }
    }
}

Score : 400 points

Problem Statement

Give a pair of integers (A, B) such that A^5-B^5 = X.
It is guaranteed that there exists such a pair for the given integer X.

Constraints

1 \leq X \leq 10^9

X is an integer.

There exists a pair of integers (A, B) satisfying the condition in Problem Statement.

Input

Input is given from Standard Input in the following format:

X

Output

Print A and B, with space in between.
If there are multiple pairs of integers (A, B) satisfying the condition, you may print any of them.

A B

Sample Input 1

33

Sample Output 1

2 -1

For A=2 and B=-1, A^5-B^5 = 33.

Sample Input 2

1

Sample Output 2

0 -1


import java.util.Scanner;

public class Main {
	//java11

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		long X = sc.nextLong();

		int A = 0;
		int B = 0;
		for(int i=0; i<=1000; i++) {
			for(int j=-1000; j<=1000; j++) {
				long ans = (long)Math.pow(i, 5) - (long)Math.pow(j, 5);
				if(ans == X) {
					A = i;
					B = j;
					break;
				}
			}
		}

		System.out.println(A + " " + B);

	}

}


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.HashSet;
import java.util.NoSuchElementException;

class Main implements Runnable {
	private final FastScanner sc;
	private final PrintWriter out;
	//private final long MOD = 1000000007;
	//private final int[] d8x = {-1,0,1,1,1,0,-1,-1};
	//private final int[] d8y = {-1,-1,-1,0,1,1,1,0};
	//private final int[] d4x = {0,1,0,-1};
	//private final int[] d4y = {-1,0,1,0};
	int x;

	public static void main(String[] args) {
		new Thread(null, new Main(), "", 16L * 1024 * 1024).start();
	}

	Main() {
		sc = new FastScanner();
		out = new PrintWriter(System.out);
	}

	private void init() throws Exception {
		x = sc.nextInt();
	}

	private void solve() throws Exception{
		first:for(int a=0;a<10000;a++){
			for(int b=0;b<10000;b++){
				if(a*a*a*a*a-b*b*b*b*b==x) {
					out.printf("%d %d",a,b);
					break first;
				}
				if(a*a*a*a*a+b*b*b*b*b==x){
					out.printf("%d %d", a,-b);
					break first;
				}
			}
			if(a==99){
				System.exit(1);
			}
		}
	}

	public void run() {
		try {
			init();
			sc.close();
			solve();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
		out.flush();
		out.close();
	}

	@SuppressWarnings("unused")
	private void exit(){
		out.flush();
		out.close();
		System.exit(0);
	}
}

class Data {
}

class MyMath{
	public static int floor(double a){
		BigDecimal ans = new BigDecimal(String.format("%.6f", a));
		return ans.setScale(0, RoundingMode.FLOOR).intValue();
	}
	public static int ceil(double a){
		BigDecimal ans = new BigDecimal(String.format("%.6f", a));
		return ans.setScale(0, RoundingMode.CEILING).intValue();
	}
}

class ExIntVector {
	private int[] a;
	private int cnt;
	public ExIntVector(int max){
		a = new int[max];
		cnt = 0;
	}
	public int size(){
		return cnt;
	}
	public void add(int x){
		a[cnt++] = x;
	}
	public int get(int i){
		return a[i];
	}
	public int getLast(){
		return a[cnt-1];
	}
	public int[] toArray(){
		return a;
	}
}

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 read() {
		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 boolean hasNext() {
		while (read() && !isVisibleChar(buffer[ptr]))
			ptr++;
		return read();
	}

	private int getNextChar() {
		if (read()) {
			ptr++;
			return buffer[ptr - 1];
		} else {
			return -1;
		}
	}

	private static boolean isVisibleChar(int code) {
		return code >= 33 && code <= 126;
	}

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

	public long nextLong() {
		if (!hasNext())
			throw new NoSuchElementException();
		long n = 0;
		boolean sign = true;
		int b = getNextChar();
		if (b == '-') {
			sign = false;
			b = getNextChar();
		}
		if (b < '0' || b > '9') {
			throw new NumberFormatException();
		}
		while (true) {
			if (b >= '0' && b <= '9') {
				n *= 10;
				n += b - '0';
			} else if (b == -1 || !isVisibleChar(b)) {
				return sign ? n : -n;
			} else {
				throw new NumberFormatException();
			}
			b = getNextChar();
		}
	}

	public int nextInt() {
		long n = nextLong();
		if (n < Integer.MIN_VALUE || n > Integer.MAX_VALUE)
			throw new NumberFormatException();
		return (int) n;
	}

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

	public char nextChar() {
		if (!hasNext())
			throw new NoSuchElementException();
		int b = getNextChar();
		while (!isVisibleChar(b)) {
			b = getNextChar();
		}
		return (char) b;
	}

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

class IntQueue {
	protected int[] a;
	protected int head, tail;

	public IntQueue(int max) {
		a = new int[max];
	}

	public void offer(int x) {
		a[tail++] = x;
	}

	public int poll() {
		return a[head++];
	}

	public int peek() {
		return a[head];
	}

	public int size() {
		return tail - head;
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.StringTokenizer;

public class Main
{

	static class Pair implements Comparable<Pair>
	{
		int x;
		int y;
		int type;
		Pair(int x,int y,int type)
		{
			this.x = x;
			this.y = y;
			this.type = type;
		}

		@Override
		public int compareTo(Pair o)
		{
			if(x != o.x)
			{
				if(x < o.x)
				return -1;

				else return 1;
			}
			else
			{
				if(y < o.y)
				return -1;

				else return 1;
			}
		}
	}

	static class FastReader
	{
	    BufferedReader br;
	    StringTokenizer st;

	    public FastReader()
	    {
	        br = new BufferedReader(new
	                 InputStreamReader(System.in));
	    }

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

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

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

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

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

	static int maxN = 2000000;
	static int fact[] = new int[maxN+1];
	static int factorialNumInverse[] = new int[maxN+1];
	static int naturalNumInverse[] = new int[maxN+1];

	static void InverseofNumber()
	{
		int p = mod;
	    naturalNumInverse[0] = naturalNumInverse[1] = 1;
	    for (int i = 2; i <= maxN; i++)
	        naturalNumInverse[i] = (int)((1L *naturalNumInverse[p % i] * (p - p / i))%p);
	}

	static void InverseofFactorial()
	{
		int p = mod;
	    factorialNumInverse[0] = factorialNumInverse[1] = 1;

	    for (int i = 2; i <= maxN; i++)
	        factorialNumInverse[i] = (int)((1L*naturalNumInverse[i] * factorialNumInverse[i - 1]) % p);
	}

	static void Factorial()
	{

		fact[0] = 1;
		for(int i = 1; i < maxN; i++)
		{
			fact[i] = (int)(1L *fact[i - 1] * i % mod);
		}
	}

	static int Binomial(int N, int R)
	{
	    int p = mod;
	    int ans = (int)((1L *(1L*fact[N] * factorialNumInverse[R]) % p * factorialNumInverse[(N - R)]) % p);
	    return ans;
	}
	static int paths(int x1,int y1,int x2,int y2)
	{
		int x = Math.abs(x2-x1);
		int y = Math.abs(y2-y1);

		int N = x+y;
		int R = x;

		int ans = Binomial(N,R);
		return ans;
	}

	static int mod = 998244353;

	// a b c d e f g h i j k
	// 0 1 0 1 0 1 0 1 0 1 0

	public static void main(String[] args)
	{
		OutputStream outputStream = System.out;
		FastReader sc = new FastReader();
        PrintWriter out = new PrintWriter(outputStream);

        int n = sc.nextInt();
        long a[] = new long[n];

        for(int i = 0; i < n; i++)
        {
        	a[i] = sc.nextLong();
        }
        HashMap<Long,Long> hm = new HashMap<>();

        long ans = 0;
        for(int i = 0; i < n; i++)
        {
        	if(hm.containsKey(i-a[i]))
        	{
        		ans += hm.get(i-a[i]);
        	}

        	hm.put(i+a[i],hm.getOrDefault(i+a[i],0L)+1L);
        }

        out.println(ans);
        out.close();

	}

}

Score: 500 points

Problem Statement

You are the top spy of AtCoder Kingdom. To prevent the stolen secret from being handed to AlDebaran Kingdom, you have sneaked into the party where the transaction happens.

There are N attendees in the party, and they are given attendee numbers from 1 through N. The height of Attendee i is A_i.

According to an examination beforehand, you know that a pair of attendees satisfying the condition below will make the transaction.

The absolute difference of their attendee numbers is equal to the sum of their heights.

There are \frac{N(N-1)}{2} ways to choose two from the N attendees and make a pair. Among them, how many satisfy the condition above?

P.S.: We cannot let you know the secret.

Constraints

All values in input are integers.

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

1 \leq A_i \leq 10^9\ (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

Print the number of pairs satisfying the condition.

Sample Input 1

6
2 3 3 1 3 1

Sample Output 1

3

A_1 + A_4 = 3, so the pair of Attendee 1 and 4 satisfy the condition.

A_2 + A_6 = 4, so the pair of Attendee 2 and 6 satisfy the condition.

A_4 + A_6 = 2, so the pair of Attendee 4 and 6 satisfy the condition.

No other pair satisfies the condition, so you should print 3.

Sample Input 2

6
5 2 4 2 8 8

Sample Output 2

0

No pair satisfies the condition, so you should print 0.

Sample Input 3

32
3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 9 5

Sample Output 3

22


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

public class Main {

  public static void main(String[] args) {
    InputReader in = new InputReader(System.in);

    long x = in.nextLong();

    long p = 100;
    long years = 0;
    while (p < x) {
      p += p/100;
      years++;
    }
    System.out.println(years);
  }

  static class InputReader {

    private final InputStream stream;
    private final byte[] buf = new byte[8192];
    private int curChar, snumChars;
    private SpaceCharFilter filter;

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

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

    public int nextInt() {
      int c = snext();
      while (isSpaceChar(c)) {
        c = snext();
      }
      int sgn = 1;
      if (c == '-') {
        sgn = -1;
        c = snext();
      }
      int res = 0;
      do {
        if (c < '0' || c > '9') throw new InputMismatchException();
        res *= 10;
        res += c - '0';
        c = snext();
      } while (!isSpaceChar(c));
      return res * sgn;
    }

    public long nextLong() {
      int c = snext();
      while (isSpaceChar(c)) {
        c = snext();
      }
      int sgn = 1;
      if (c == '-') {
        sgn = -1;
        c = snext();
      }
      long res = 0;
      do {
        if (c < '0' || c > '9') throw new InputMismatchException();
        res *= 10;
        res += c - '0';
        c = snext();
      } while (!isSpaceChar(c));
      return res * sgn;
    }

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

    public String readString() {
      int c = snext();
      while (isSpaceChar(c)) {
        c = snext();
      }
      StringBuilder res = new StringBuilder();
      do {
        res.appendCodePoint(c);
        c = snext();
      } while (!isSpaceChar(c));
      return res.toString();
    }

    public String nextLine() {
      int c = snext();
      while (isSpaceChar(c)) c = snext();
      StringBuilder res = new StringBuilder();
      do {
        res.appendCodePoint(c);
        c = snext();
      } while (!isEndOfLine(c));
      return res.toString();
    }

    public boolean isSpaceChar(int c) {
      if (filter != null) return filter.isSpaceChar(c);
      return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

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

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

Score : 200 points

Problem Statement

Takahashi has a deposit of 100 yen (the currency of Japan) in AtCoder Bank.

The bank pays an annual interest rate of 1 % compounded annually. (A fraction of less than one yen is discarded.)

Assuming that nothing other than the interest affects Takahashi's balance, in how many years does the balance reach X yen or above for the first time?

Constraints

101 \le X \le 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X

Output

Print the number of years it takes for Takahashi's balance to reach X yen or above for the first time.

Sample Input 1

103

Sample Output 1

3

The balance after one year is 101 yen.

The balance after two years is 102 yen.

The balance after three years is 103 yen.

Thus, it takes three years for the balance to reach 103 yen or above.

Sample Input 2

1000000000000000000

Sample Output 2

3760

Sample Input 3

1333333333

Sample Output 3

1706


import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class Main {

	static long maxScore = 0;
	static int N, M, Q;
	static int a[], b[], c[], d[];

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

		Scanner scan = new Scanner(System.in);

		N = scan.nextInt();
		M = scan.nextInt();
		Q = scan.nextInt();

		a = new int[Q + 1];
		b = new int[Q + 1];
		c = new int[Q + 1];
		d = new int[Q + 1];

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

		for (int i = 1; i <= Q; i++) {
			a[i] = scan.nextInt();
			b[i] = scan.nextInt();
			c[i] = scan.nextInt();
			d[i] = scan.nextInt();
		}

		//dfsでAを作成しながら得点を求める
		dfs(A, N, M);
		System.out.println(maxScore);

	}

	public static void dfs(List<Integer> A, int maxLength, int MaxValue) {
		if (A.size() == maxLength) {
			calcScore(A);
			return;
		}

		A.add(A.size(), 1);

		while (A.get(A.size() - 1) <= MaxValue) {
			dfs(A, maxLength, MaxValue);

			int tmp = A.get(A.size() - 1) + 1;
			A.add(A.size() - 1, tmp);

		}
	}

	public static void calcScore(List<Integer> A) {
		//スコアを計算
		long score = 0;
		for (int i = 1; i <= Q; i++) {
			if (A.get(b[i] - 1) - A.get(a[i] - 1) == c[i]) {
				score += d[i];
			}

		}

		if (score > maxScore) {
			maxScore = score;
		}
	}

	/**
	 * 文字列を反転して返す
	 * @param pStr 文字列
	 * @return 反転した文字列
	 */
	public static String myReverse(String pStr) {
		if (pStr.length() < 1) {
			return "";
		}

		StringBuffer sb = new StringBuffer(pStr);
		return sb.reverse().toString();
	}

	/**
	 * 余りを求める。
	 * @param a
	 * @param b
	 * @return 余り。余りがマイナスの時はプラスで返す。
	 */
	public static long myMod(long a, long b) {
		long ret = 0;

		ret = a % b;

		if (ret < 0) {
			ret += b;
		}

		return ret;
	}

	/**
	 * 乗数を求める ※mod対応
	 * @param kisu 基数
	 * @param josu 乗数
	 * @param primeNumMod_0 法 mod値 使わない場合は「0」
	 * @return
	 */
	public static long myPowWithMod(long kisu, long josu, long primeNumMod_0) {

		long ans = 1;

		//乗数が0の場合→1
		if (josu == 0)
			return 1;

		if (primeNumMod_0 == 0) {
			//modを使わないとき

			while (josu > 0) {

				if (josu % 2 == 0) {
					//累乗が偶数の時

					kisu *= kisu;
					josu = josu / 2;
				} else {
					//累乗が奇数の時
					ans *= kisu;
					josu--;
				}
			}

			return ans;

		} else {
			//modを使うとき

			//初めに桁を落とす
			kisu = myMod(kisu, primeNumMod_0);

			while (josu > 0) {

				if (josu % 2 == 0) {
					//累乗が偶数の時

					kisu *= myMod(kisu, primeNumMod_0);
					josu = josu / 2;

				} else {
					//累乗が奇数の時
					ans *= myMod(kisu, primeNumMod_0);
					josu--;

				}
			}

			return myMod(ans, primeNumMod_0);

		}

	}

}

Score : 300 points

Problem Statement

Given are positive integers N, M, Q, and Q quadruples of integers ( a_i , b_i , c_i , d_i ).

Consider a sequence A satisfying the following conditions:

A is a sequence of N positive integers.

1 \leq A_1 \leq A_2 \le \cdots \leq A_N \leq M.

Let us define a score of this sequence as follows:

The score is the sum of d_i over all indices i such that A_{b_i} - A_{a_i} = c_i. (If there is no such i, the score is 0.)

Find the maximum possible score of A.

Constraints

All values in input are integers.

2 ≤ N ≤ 10

1 \leq M \leq 10

1 \leq Q \leq 50

1 \leq a_i < b_i \leq N ( i = 1, 2, ..., Q )

0 \leq c_i \leq M - 1 ( i = 1, 2, ..., Q )

(a_i, b_i, c_i) \neq (a_j, b_j, c_j) (where i \neq j)

1 \leq d_i \leq 10^5 ( i = 1, 2, ..., Q )

Input

Input is given from Standard Input in the following format:

N M Q
a_1 b_1 c_1 d_1
:
a_Q b_Q c_Q d_Q

Output

Print the maximum possible score of A.

Sample Input 1

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

Sample Output 1

110

When A = \{1, 3, 4\}, its score is 110. Under these conditions, no sequence has a score greater than 110, so the answer is 110.

Sample Input 2

4 6 10
2 4 1 86568
1 4 0 90629
2 3 0 90310
3 4 1 29211
3 4 3 78537
3 4 2 8580
1 2 1 96263
1 4 2 2156
1 2 0 94325
1 4 3 94328

Sample Output 2

357500

Sample Input 3

10 10 1
1 10 9 1

Sample Output 3

1


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

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 nextDoutble(){return Double.parseDouble(next());}
}
public class Main {
    static int n,m,q;
    static ABCD[] array;
    static int max;
    static int[] A;
    public static void main(String[] args) {

        FastScanner fs = new FastScanner();
        n = fs.nextInt();
        m = fs.nextInt();
        q = fs.nextInt();
        array = new ABCD[q];
        max = 0;
        A = new int[n];
        for(int i=0;i<q;i++){
            array[i] = new ABCD(fs.nextInt(),fs.nextInt(),fs.nextInt(),fs.nextInt());
        }

        combination(0,0,1);

        System.out.println(max);

    }
    public static void combination(int pos ,int count,int val){
        if(count == n){
            int sum = 0;
            for(int i=0;i<q;i++){
                if(A[array[i].b-1]-A[array[i].a-1] == array[i].c){
                    sum+=array[i].d;
                }
            }
            max = Math.max(sum,max);
        }else{
            for(int i=val;i<=m;i++){
                A[pos] = i;
                combination(pos+1,count+1,i);
            }
        }
    }
}

class ABCD{
    int a,b,c,d;
    ABCD(int a,int b,int c,int d){
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
    }
}


import java.util.*;
import java.math.*;

public class Main {
    static final int MOD = 1_000_000_007; // 10^9+7
    // static final int MAX = 2_147_483_646; // intの最大値
    static final int INF = 1_000_000_000; // 10^9
    static final int MAX = 10_000_000;
    static long[] fact = new long[100];
        public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        long a = sc.nextLong();
        long b = sc.nextLong();
        long n = sc.nextLong();
        long min = Math.min(b,n);
        System.out.println((min * a)/b);
    }

}

Score : 400 points

Problem Statement

Given are integers A, B, and N.

Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.

Here floor(t) denotes the greatest integer not greater than the real number t.

Constraints

1 ≤ A ≤ 10^{6}

1 ≤ B ≤ 10^{12}

1 ≤ N ≤ 10^{12}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B N

Output

Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.

Sample Input 1

5 7 4

Sample Output 1

2

When x=3, floor(Ax/B)-A×floor(x/B) = floor(15/7) - 5×floor(3/7) = 2. This is the maximum value possible.

Sample Input 2

11 10 9

Sample Output 2

9


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

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

    static class ERotationMatching {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.readInt();
            int m = in.readInt();

            int l = 1;
            int r = n;

            int[] L = new int[m];
            int[] R = new int[m];

            for (int i = 0; i < m; i++) {
                L[i] = i;
            }
            for (int i = 0; i < m; i++) {
                R[m - i - 1] = m + i;
            }

            for (int i = 0; i < m; i++) {
                int a = L[i] + 1;
                int b = R[i] + 1;

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

    }

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

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

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private 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 readInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

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

        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void print(Object... objects) {
            for (int i = 0; i < objects.length; i++) {
                if (i != 0) {
                    writer.print(' ');
                }
                writer.print(objects[i]);
            }
        }

        public void println(Object... objects) {
            print(objects);
            writer.println();
        }

        public void close() {
            writer.close();
        }

    }
}

Score : 500 points

Problem Statement

You are going to hold a competition of one-to-one game called AtCoder Janken. (Janken is the Japanese name for Rock-paper-scissors.)
N players will participate in this competition, and they are given distinct integers from 1 through N.
The arena has M playing fields for two players. You need to assign each playing field two distinct integers between 1 and N (inclusive).
You cannot assign the same integer to multiple playing fields.
The competition consists of N rounds, each of which proceeds as follows:

For each player, if there is a playing field that is assigned the player's integer, the player goes to that field and fight the other player who comes there.

Then, each player adds 1 to its integer. If it becomes N+1, change it to 1.

You want to ensure that no player fights the same opponent more than once during the N rounds.
Print an assignment of integers to the playing fields satisfying this condition.
It can be proved that such an assignment always exists under the constraints given.

Constraints

1 \leq M

M \times 2 +1 \leq N \leq 200000

Input

Input is given from Standard Input in the following format:

N M

Output

Print M lines in the format below.
The i-th line should contain the two integers a_i and b_i assigned to the i-th playing field.

a_1 b_1
a_2 b_2
:
a_M b_M

Sample Input 1

4 1

Sample Output 1

2 3

Let us call the four players A, B, C, and D, and assume that they are initially given the integers 1, 2, 3, and 4, respectively.

The 1-st round is fought by B and C, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 2, 3, 4, and 1, respectively.

The 2-nd round is fought by A and B, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 3, 4, 1, and 2, respectively.

The 3-rd round is fought by D and A, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 4, 1, 2, and 3, respectively.

The 4-th round is fought by C and D, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 1, 2, 3, and 4, respectively.

No player fights the same opponent more than once during the four rounds, so this solution will be accepted.

Sample Input 2

7 3

Sample Output 2

1 6
2 5
3 4


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

class Ele {
  int ori;
  int idx;

  Ele(int ori, int idx){
    this.ori = ori;
    this.idx = idx;
  }
}

class Graph {
  public ArrayList< ArrayList<Integer> > adjacency;

  Graph(int n){
    adjacency = new ArrayList< ArrayList<Integer> >();
    for(int i = 0; i < n; i++){
      adjacency.add(new ArrayList<Integer>());
    }
  }

  public void add_edge(int from, int to, boolean is_directed){
    adjacency.get(from).add(to);
    if(!is_directed){
      adjacency.get(to).add(from);
    }
  }
}

public class Main {

  static final int INF = 1000000001;

  static int n;
  static int[] a, lis, ans;
  static boolean[] seen;

  static Deque<Ele> st = new ArrayDeque<>();

  static Graph g;

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

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

    String[] in = br.readLine().split(" ");
    n = Integer.parseInt(in[0]);

    g = new Graph(n);

    in = br.readLine().split(" ");
    a = Stream.of(in).mapToInt(Integer::parseInt).toArray();

    for(int i = 0; i < n-1; i++){
      in = br.readLine().split(" ");
      g.add_edge(Integer.parseInt(in[0]) - 1, Integer.parseInt(in[1]) - 1, false);
    }

    br.close();

    lis = new int[n+1];
    ans = new int[n];
    seen = new boolean[n];

    Arrays.fill(lis, INF);
    lis[0] = -INF;

    dfs(0, 0);

    PrintWriter out = new PrintWriter(System.out);

    for(int i = 0; i < n; i++){
      out.println(ans[i]);
    }
    out.flush();
  }

  static int binarySearch(int x, int maxIdx){
    int left = 0; int right = maxIdx + 1;
    while(right - left > 1){
      int mid = (right + left) / 2;
      if(lis[mid] < x) left = mid;
      else right = mid;
    }
    st.push(new Ele(lis[right], right));
    lis[right] = x;

    return right;
  }

  static void dfs(int now, int idx){

    idx = Math.max(idx, binarySearch(a[now], idx));

    ans[now] = idx;
    seen[now] = true;

    for(int nex : g.adjacency.get(now)){
      if(seen[nex]) continue;
      dfs(nex, idx);
    }

    Ele forRet = st.poll();
    lis[forRet.idx] = forRet.ori;

    return;
  }

}

Score : 600 points

Problem Statement

We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i.
Vertex i has an integer a_i written on it.
For every integer k from 1 through N, solve the following problem:

We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.

Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.

Constraints

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

1 \leq a_i \leq 10^9

1 \leq u_i , v_i \leq N

u_i \neq v_i

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}

Output

Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.

Sample Input 1

10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10

Sample Output 1

1
2
3
3
4
4
5
2
2
3

For example, the sequence A obtained from the shortest path from Vertex 1 to Vertex 5 is 1,2,5,3,4. Its longest increasing subsequence is A_1, A_2, A_4, A_5, with the length of 4.


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

public class Main {
	static PrintWriter out;
	static StringBuilder sb;
	static int n, m, k;
	static long mod = 998244353;
	static Boolean[][][] memo;
	static String s;
	static HashMap<Integer, Integer> nums;
	static ArrayList<Integer>[] ad;
	static boolean[] vis;
	static TreeSet<Long> al;
	static int[][] val;
	static int[] b;
	static int[] ans;
	static FenwickTree ft;

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		out = new PrintWriter(System.out);
		n = sc.nextInt();
		b = new int[n];
		TreeSet<Integer> ts = new TreeSet<>();
		for (int i = 0; i < n; i++) {
			ts.add(b[i] = sc.nextInt());
		}
		nums = new HashMap<>();
		int id = 1;
		ad = new ArrayList[n];
		for (int i = 0; i < n; i++)
			ad[i] = new ArrayList<>();
		for (int i = 0; i < n - 1; i++) {
			int a = sc.nextInt() - 1;
			int b = sc.nextInt() - 1;
			ad[a].add(b);
			ad[b].add(a);
		}
		ans = new int[n];
		while (!ts.isEmpty())
			nums.put(ts.pollFirst(), id++);
		ft = new FenwickTree(nums.size() + 1);
		ar = new int[n];
		k = -1;
		dfs(0, -1);
		for (int i = 0; i < n; i++)
			out.println(ans[i]);
		out.flush();
	}

	static int[] ar;

	static void dfs(int u, int p) {
		boolean f = false;
		int id = -1;
		int v = 0;
		if (k == -1 || ar[k] < b[u]) {
			ar[++k] = b[u];
		} else {
			f = true;
			int lo = 0;
			int hi = k;
			while (lo <= hi) {
				int mid = lo + hi >> 1;
				if (ar[mid] >= b[u]) {
					id = mid;
					hi = mid - 1;
				} else
					lo = mid + 1;
			}
			if (id != -1) {
				v = ar[id];
				ar[id] = Math.min(ar[id], b[u]);
			}
		}
		ans[u]=k+1;
		for (int ch : ad[u])
			if (ch != p) {
				dfs(ch, u);
			}
		if (f) {
			if (id != -1)
				ar[id] = v;
		} else {
			k--;
		}
	}

	public static class FenwickTree { // one-based DS

		int n;
		int[] ft;
		int[] occ;

		FenwickTree(int size) {
			n = size;
			ft = new int[n + 1];
			occ = new int[n + 1];
		}

		int rsq(int b) // O(log n)
		{
			int sum = 0;
			while (b > 0) {
				sum = Math.max(ft[b], sum);
				b -= b & -b;
			} // min?
			return sum;
		}

		ArrayList<Integer> point_update(int k, int val) // O(log n), update = increment
		{
			ArrayList<Integer> points = new ArrayList<>();
			while (k <= n) {
				if (ft[k] < val) {
					points.add(k);
					points.add(ft[k]);
				}
				ft[k] = Math.max(val, ft[k]);
				k += k & -k;
			} // min?
			return points;
		}

		void reverse(ArrayList<Integer> g) {
			for (int i = 0; i < g.size(); i += 2) {
				ft[g.get(i)] = g.get(i + 1);
			}
		}

	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

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

		public Scanner(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 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 int[] nextArrInt(int n) throws IOException {
			int[] a = new int[n];
			for (int i = 0; i < n; i++)
				a[i] = nextInt();
			return a;
		}

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

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

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


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

import static java.lang.Math.*;
import static java.util.Arrays.*;

public class Main/*Change to Main When Submitting*/ {
    static BufferedReader __in;
    static PrintWriter __out;
    static StringTokenizer input;

    static int[] ans;
    static Comparator<P> cmpi = (a, b) -> a.a == b.a ? a.b - b.b : a.a - b.a, cmpd = (a, b) -> a.a == b.a ? a.b - b.b : b.a - a.a;

    public static void main(String[] args) throws IOException {
        __in = new BufferedReader(new InputStreamReader(System.in));
        __out = new PrintWriter(new OutputStreamWriter(System.out));

        int n = ri();
        Node[] g = new Node[n];
        r();
        for(int i = 0; i < n; ++i) {
            g[i] = new Node(i, ni());
        }
        for(int i = 0; i < n - 1; ++i) {
            r();
            g[ni() - 1].add(g[ni() - 1]);
        }
        g[0].label(null);
        ans = new int[n];
        fill(ans, 1);
        g[0].solve(n);
        for(int i : ans) {
            prln(i);
        }

        close();
    }

    static class Node {
        List<Node> nei = new ArrayList<>();
        int i, v;
        Node par;

        Node(int i_, int v_) {
            i = i_;
            v = v_;
        }

        void label(Node par_) {
            par = par_;
            for(Node n : nei) {
                if(n != par) {
                    n.label(this);
                }
            }
        }

        void add(Node n) {
            nei.add(n);
            n.nei.add(this);
        }

        void solve(int tot) {
            int[] dp = new int[tot], vals = new int[tot];
            fill(dp, 1);
            vals[0] = v;
            for(Node n : nei) {
                n.solve(dp, vals, 1);
            }
        }

        void solve(int[] dp, int[] vals, int ind) {
//            prln(ind);
//            prln(dp);
//            prln(vals);
//            prln(ans);
//            prln();
            dp[ind] = 1;
            for(int i = 0; i < ind; ++i) {
                if(v > vals[i]) {
                    dp[ind] = max(dp[ind], dp[i] + 1);
                    ans[this.i] = max(ans[i], dp[ind]);
                }
            }
            vals[ind] = v;
            for(Node n : nei) {
                if(n != par) {
                    n.solve(dp, vals, ind + 1);
                }
            }
        }
    }

    /* static class Node {
        List<Node> nei = new ArrayList<>();
        int v;

        Node(int v_) {
            v = v_;
        }

        // returns {inc, dec}
        List<TreeSet<P>> solve(Node par) {
            TreeSet<P> inc = new TreeSet<>(cmpi), dec = new TreeSet<>(cmpd);
            P self = P.mk(v, 1);
            if(nei.size() == 1) {
                inc.add(self);
                dec.add(self);
            } else {
                for(Node n : nei) {
                    if(n != par) {
                        List<TreeSet<P>> res = n.solve(this);
                        inc.addAll(res.get(0));
                        dec.addAll(res.get(1));
                    }
                }
                P maxInc = inc.floor(P.mk(v - 1, 0)), maxDec = dec.floor(P.mk(v + 1, 0));
                int cur = 1;
                if(maxInc != null) {
                    cur += maxInc.b;
                    inc.add(P.mk(v, maxInc.b + 1));
                }
                if(maxDec == null) {
                    cur += maxDec.b;
                    dec.add(P.mk(v, maxDec.b + 1));
                }
                ans = max(ans, cur);
            }
            List<TreeSet<P>> ret = new ArrayList<>(2);
            ret.add(inc);
            ret.add(dec);
            return ret;
        }
    } */

    static class P {
        int a, b;

        P(int a_, int b_) {
            a = a_;
            b = b_;
        }

        @Override
        public String toString() {
            return "Pair{" + "a = " + a + ", b = " + b + '}';
        }

        public static P mk(int a, int b) {
            return new P(a, b);
        }

        public boolean equalsSafe(Object o) {
            if(this == o) return true;
            if(o == null || getClass() != o.getClass()) return false;
            P p = (P)o;
            return a == p.a && b == p.b;
        }

        public boolean equalsUnchecked(Object o) {
            P p = (P)o;
            return a == p.a && b == p.b;
        }

        @Override
        public boolean equals(Object o) {
            return equalsUnchecked(o);
        }

        @Override
        public int hashCode() {
            return Objects.hash(a, b);
        }
    }

    // references
    // IBIG = 1e9 + 7
    // IRAND ~= 3e8
    // IMAX ~= 2e10
    // LMAX ~= 9e18
    // constants
    static final int IBIG = 1000000007;
    static final int IRAND = 327859546;
    static final int IMAX = 2147483647;
    static final int IMIN = -2147483648;
    static final long LMAX = 9223372036854775807L;
    static final long LMIN = -9223372036854775808L;
    // util
    static int minof(int a, int b, int c) {return min(a, min(b, c));}
    static int minof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));}
    static int minstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));}
    static long minof(long a, long b, long c) {return min(a, min(b, c));}
    static long minof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));}
    static long minstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));}
    static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
    static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
    static int floori(double d) {return (int)d;}
    static int ceili(double d) {return (int)ceil(d);}
    static long floorl(double d) {return (long)d;}
    static long ceill(double d) {return (long)ceil(d);}
    // input
    static void r() throws IOException {input = new StringTokenizer(__in.readLine());}
    static int ri() throws IOException {return Integer.parseInt(__in.readLine());}
    static long rl() throws IOException {return Long.parseLong(__in.readLine());}
    static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}
    static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}
    static char[] rcha() throws IOException {return __in.readLine().toCharArray();}
    static String rline() throws IOException {return __in.readLine();}
    static int ni() {return Integer.parseInt(input.nextToken());}
    static long nl() {return Long.parseLong(input.nextToken());}
    // output
    static void pr(int i) {__out.print(i);}
    static void prln(int i) {__out.println(i);}
    static void pr(long l) {__out.print(l);}
    static void prln(long l) {__out.println(l);}
    static void pr(double d) {__out.print(d);}
    static void prln(double d) {__out.println(d);}
    static void pr(char c) {__out.print(c);}
    static void prln(char c) {__out.println(c);}
    static void pr(char[] s) {__out.print(new String(s));}
    static void prln(char[] s) {__out.println(new String(s));}
    static void pr(String s) {__out.print(s);}
    static void prln(String s) {__out.println(s);}
    static void pr(Object o) {__out.print(o);}
    static void prln(Object o) {__out.println(o);}
    static void prln() {__out.println();}
    static void pryes() {__out.println("yes");}
    static void pry() {__out.println("Yes");}
    static void prY() {__out.println("YES");}
    static void prno() {__out.println("no");}
    static void prn() {__out.println("No");}
    static void prN() {__out.println("NO");}
    static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};
    static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}
    static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}
    static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), i++); __out.println(a[a.length - 1]);}
    static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), i++); __out.println(a[a.length - 1]);}
    static void flush() {__out.flush();}
    static void close() {__out.close();}
    // debug
    static void debug(String desc, int... a) {System.out.print(desc); System.out.print(": "); for(int i = 0, len = a.length - 1; i < len; System.out.print(a[i]), System.out.print(", "), i++); System.out.println(a[a.length - 1]);}
    static void debug(String desc, long... a) {System.out.print(desc); System.out.print(": "); for(int i = 0, len = a.length - 1; i < len; System.out.print(a[i]), System.out.print(", "), i++); System.out.println(a[a.length - 1]);}
}


import java.util.Scanner;

class Main {

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

        int x=stdIn.nextInt();//回数

        String []a=new String[x];
        for(int i=0; i<a.length; i++){
            a[i]=stdIn.next();
        }
        int sum=0;
        for(int i=0;i<x; i++){
            for(int j=0; j<x-i-1; j++){
                if(a[i].equals(a[i+j+1])){
                    sum++;
                }
            }
        }
        System.out.println(x-sum);

    }

}

Score : 100 points

Problem Statement

There are S sheep and W wolves.

If the number of wolves is greater than or equal to that of sheep, the wolves will attack the sheep.

If the wolves will attack the sheep, print unsafe; otherwise, print safe.

Constraints

1 \leq S \leq 100

1 \leq W \leq 100

Input

Input is given from Standard Input in the following format:

S W

Output

If the wolves will attack the sheep, print unsafe; otherwise, print safe.

Sample Input 1

4 5

Sample Output 1

unsafe

There are four sheep and five wolves. The number of wolves is not less than that of sheep, so they will attack them.

Sample Input 2

100 2

Sample Output 2

safe

Many a sheep drive away two wolves.

Sample Input 3

10 10

Sample Output 3

unsafe


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringJoiner;
import java.util.StringTokenizer;
import java.util.function.IntUnaryOperator;
import java.util.function.LongUnaryOperator;

public class Main {
    static In in = new In();
    static Out out = new Out();
    static final long mod = 1000000007;
    static final long inf = 0xfffffffffffffffL;
    static final int iinf = 0xfffffff;
    static final int[] da = {-1, 0, 1, 0, -1, 1, 1, -1, -1};

    void solve() {
        int s = in.nextInt();
        int w = in.nextInt();
        out.println(w > s ? "unsafe" : "safe");
    }

    public static void main(String[]$) {
        new Main().solve();
        out.flush();
    }
}

class In {
    private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 0x10000);
    private StringTokenizer tokenizer;

    String next() {
        try {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                tokenizer = new StringTokenizer(reader.readLine());
            }
        } catch (IOException ignored) {
        }
        return tokenizer.nextToken();
    }

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

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

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

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

    int[] nextIntArray(int n, IntUnaryOperator op) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = op.applyAsInt(nextInt());
        }
        return a;
    }

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

    long[] nextLongArray(int n, LongUnaryOperator op) {
        long[] a = new long[n];
        for (int i = 0; i < n; i++) {
            a[i] = op.applyAsLong(nextLong());
        }
        return a;
    }
}

class Out {
    private PrintWriter out = new PrintWriter(System.out);
    boolean autoFlush = false;

    void println(Object... a) {
        StringJoiner joiner = new StringJoiner(" ");
        for (Object obj : a) {
            joiner.add(String.valueOf(obj));
        }
        out.println(joiner);
        if (autoFlush) {
            out.flush();
        }
    }

    void println(int[] a) {
        StringJoiner joiner = new StringJoiner(" ");
        for (int i : a) {
            joiner.add(Integer.toString(i));
        }
        out.println(joiner);
        if (autoFlush) {
            out.flush();
        }
    }

    void println(long[] a) {
        StringJoiner joiner = new StringJoiner(" ");
        for (long i : a) {
            joiner.add(Long.toString(i));
        }
        out.println(joiner);
        if (autoFlush) {
            out.flush();
        }
    }

    void flush() {
        out.flush();
    }
}


import java.util.*;

class MyStack {
    private Object stack[];
    private int stackSize;
    private int sp;
    private static final int DEFAULT_STACK_SIZE = 200000;

    public MyStack(){
        this(DEFAULT_STACK_SIZE);
    }

    public MyStack(int size){
        stack = new Object[size];
        stackSize = size;
        sp = 0;
    }

    public void clear(){
        Arrays.fill(stack,0,sp,null);
        sp = 0;
    }

    public void push(Object x){
        if(sp >= stackSize){
            throw new IllegalStateException("Stack overflow");
        }
        stack[sp++] = x;
    }

    public Object pop(){
        if(sp <= 0){
            throw new EmptyStackException();
        }
        Object value = stack[--sp];
        stack[sp] = null;
        return value;
    }

    public boolean isEmpty(){
        return sp == 0;
    }

    public String toString(){
        String s = "MyStack=[";
        for(int i = 0; i < sp; i++){
            s = s + stack[i];
            if(i < sp - 1){
                s = s + ",";
            }
        }
        s = s + "]";
        return s;
    }
    public int size(){
        return this.sp;
    }
    public String getTopObjectName(){
        String s = stack[--sp].toString();
        sp++;
        return s;
    }
}
public class Main {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int a = s.nextInt();
        List<String> list = new ArrayList<String>();
        MyStack stack = new MyStack();

        for(int i = 0; i <= a; i++){
            String x = s.nextLine();
            list.add(x.toLowerCase());
        }
        Collections.sort(list);
        stack.push(list.remove(0));
        for(int i = 0; i < list.size(); i++){
            String mo = list.get(i);
            if(mo.length() <= 10 && mo.length() >= 1 && !stack.getTopObjectName().equals(mo)){
                stack.push(mo);
            }
        }
        System.out.println(stack.size()-1);
    }
}

Score : 300 points

Problem Statement

You drew lottery N times. In the i-th draw, you got an item of the kind represented by a string S_i.

How many kinds of items did you get?

Constraints

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

S_i consists of lowercase English letters and has a length between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

Print the number of kinds of items you got.

Sample Input 1

3
apple
orange
apple

Sample Output 1

2

You got two kinds of items: apple and orange.

Sample Input 2

5
grape
grape
grape
grape
grape

Sample Output 2

1

Sample Input 3

4
aaaa
a
aaa
aa

Sample Output 3

4


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Main{

    public static void main(String[] args){
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            int number = Integer.parseInt(br.readLine());
            List<String> items = new ArrayList<>();
            int result = 0;
            for(int i = 0; i<number;i++){
                String now = br.readLine();
                if(items.contains(now)==false){
                    result++;
                }
                items.add(now);
            }
            System.out.print(result);
            br.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}


import java.util.Scanner;

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

    public static void main(String[] args) {
        int n = sc.nextInt();
        int m = sc.nextInt();
        int count = 0;
        for (int i = 0; i < m; i++) {
            int value = sc.nextInt();
            count += value;
        }
        System.out.println(Math.max(-1, n - count));
    }
}

Score : 200 points

Problem Statement

Takahashi has N days of summer vacation.

His teacher gave him M summer assignments. It will take A_i days for him to do the i-th assignment.

He cannot do multiple assignments on the same day, or hang out on a day he does an assignment.

What is the maximum number of days Takahashi can hang out during the vacation if he finishes all the assignments during this vacation?

If Takahashi cannot finish all the assignments during the vacation, print -1 instead.

Constraints

1 \leq N \leq 10^6

1 \leq M \leq 10^4

1 \leq A_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N M
A_1 ... A_M

Output

Print the maximum number of days Takahashi can hang out during the vacation, or -1.

Sample Input 1

41 2
5 6

Sample Output 1

30

For example, he can do the first assignment on the first 5 days, hang out on the next 30 days, and do the second assignment on the last 6 days of the vacation. In this way, he can safely spend 30 days hanging out.

Sample Input 2

10 2
5 6

Sample Output 2

-1

He cannot finish his assignments.

Sample Input 3

11 2
5 6

Sample Output 3

0

He can finish his assignments, but he will have no time to hang out.

Sample Input 4

314 15
9 26 5 35 8 9 79 3 23 8 46 2 6 43 3

Sample Output 4

9


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

public class Main {
    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < N - 1; i++) {
            int n = in.nextInt();
            if(map.containsKey(n)) {
                map.put(n, map.get(n) + 1);
            } else {
                map.put(n, 1);
            }
        }
        for(int i = 0; i < N; i++) {
            int n = i + 1;
            if(map.containsKey(n)) {
                System.out.println(map.get(n));
            } else {
                System.out.println(0);
            }
        }
    }

}

Score : 300 points

Problem Statement

A company has N members, who are assigned ID numbers 1, ..., N.

Every member, except the member numbered 1, has exactly one immediate boss with a smaller ID number.

When a person X is the immediate boss of a person Y, the person Y is said to be an immediate subordinate of the person X.

You are given the information that the immediate boss of the member numbered i is the member numbered A_i. For each member, find how many immediate subordinates it has.

Constraints

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

1 \leq A_i < i

Input

Input is given from Standard Input in the following format:

N
A_2 ... A_N

Output

For each of the members numbered 1, 2, ..., N, print the number of immediate subordinates it has, in its own line.

Sample Input 1

5
1 1 2 2

Sample Output 1

2
2
0
0
0

The member numbered 1 has two immediate subordinates: the members numbered 2 and 3.

The member numbered 2 has two immediate subordinates: the members numbered 4 and 5.

The members numbered 3, 4, and 5 do not have immediate subordinates.

Sample Input 2

10
1 1 1 1 1 1 1 1 1

Sample Output 2

9
0
0
0
0
0
0
0
0
0

Sample Input 3

7
1 2 3 4 5 6

Sample Output 3

1
1
1
1
1
1
0


import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long N = sc.nextLong();
        long K = sc.nextLong();
        long res = 0;
        final long INF = (long)Math.pow(10, 9) + 7;
        for (long i = K; i <= N + 1; i++) {
            long min = (i - 1) * i / 2;
            long max = i * (N - i + 1) + (i - 1) * i / 2;
            res += max - min + 1;
        }
        System.out.println(res % INF);
        sc.close();
    }
}


//import java.math.*;
import java.io.*;
import java.util.*;
//import java.lang.*;

//solution classes here

public class Main {

    //main solution here

    static Scanner sc = new Scanner(System.in);
    static PrintWriter out = new PrintWriter(System.out);
    static long mod = (long)1e9+7;
    static long MOD = 998244353;
    //static ArrayList<Integer> list[] = new ArrayList[(int)1e4+1];
    //static int color[] = new int[(int)2e6+1];
    //static int visit[] = new int[(int)1e4+1];
    //static int level[] = new int[(int)1e4+1];
    //static Deque<Integer> q = new ArrayDeque<>();

    public static void main(String[] args) throws IOException {
        int n = sc.nextInt();
        int k = sc.nextInt();
        long a[] = new long[n+2];
        a[1]=n+1;
        for(int i=2;i<=n+1;i++) {
            long min = ((i*(i-1))/2)%mod;
            long max = (mod+((n*(n+1))/2)%mod-((n-i+1)*(n-i)/2)%mod)%mod;
            a[i]=(mod+(max-min+1))%mod;
        }
        long sum=0;
        for(int i=k;i<=n+1;i++) {
            sum=(mod+sum+a[i])%mod;
        }

        out.println(sum);

        //out.println("Case #"+(test-t)+": "+fh+" "+fv);
        out.flush();
        out.close();
    }

    //solution functions here

    //---templates---
    public static void reverse (long[] array) {
        int len = array.length;
        for(int i=0;i<len/2;i++) {
            array[i]^=array[len-1-i];
            array[len-i-1]^=array[i];
            array[i]^=array[len-i-1];
        }
    }

    public static int low_bound(long[] array, long value) {
        int len = array.length;
        int lo = 0;
        int hi = len-1;
        int ans = -1;
        while(lo<=hi) {
            int mid = lo+(hi-lo)/2;
            if(array[mid]<=value) {
                lo=mid+1;
                ans=mid;
            }
            else
                hi=mid-1;
        }
        return ans;
    }

    public static int up_bound(long[] array, long value) {
        int len = array.length;
        int lo = 0;
        int hi = len-1;
        int ans = -1;
        while(lo<=hi) {
            int mid = lo+(hi-lo)/2;
            if(array[mid]>=value) {
                hi=mid-1;
                ans=mid;
            }
            else
                lo=mid+1;
        }
        return ans;
    }

    static class Scanner {
        StringTokenizer st;
        BufferedReader br;

        public Scanner(InputStream s) {
            br = new BufferedReader(new InputStreamReader(s));
        }

        public Scanner(FileReader fileReader) {
            br = new BufferedReader(fileReader);
        }

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

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

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

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

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

/* *****************************************************************************************************************************
 * I'M NOT IN DANGER, I'M THE DANGER!!!
 * *****************************************************************************************************************************
 */


import java.util.*;
public class Main {

	public static void main(String[] args) {
		int MOD = 1_000_000_007;
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int K = sc.nextInt();
		long ans = 0;
		long[] suml = new long[N+2];
		long[] sumr = new long[N+2];
		for(int i = 1; i <= N; i++) {
			suml[i] = suml[i-1];
			suml[i] += i;
		}
		for(int i = N; i >= 0; i--) {
			sumr[i] = sumr[i+1];
			sumr[i] += i;
		}
		for(int i = K; i <= N+1; i++) {
			ans += sumr[N+1-i]-suml[i-1]+1;
			ans %= MOD;
		}
		System.out.println(ans);
	}

}


import java.util.*;

public class Main {
    void run() {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] arr = new int[n][2];
        for (int i = 0; i < n; i++) {
            arr[i] = new int[]{i, sc.nextInt()};
        }

        Arrays.sort(arr, (a1, a2) -> a2[1] - a1[1]);
//        debug(arr);

        long[][] dp = new long[n + 1][n + 1];
        for (long[] x : dp) {
            Arrays.fill(x, -1);
        }
        dp[0][0] = 0;
        // dp[i][j] ... 左からi人、右からj人並べた場合のうれしさの最大値

        for (int k = 0; k < n; k++) {
            int x = arr[k][0];
            long a = (long) arr[k][1];
            for (int i = 0; i <= k; i++) {
                int j = k - i;
                if (dp[i][j] == -1) continue;
                dp[i + 1][j] = Math.max(dp[i + 1][j], dp[i][j] + a * Math.abs(x - i));
                dp[i][j + 1] = Math.max(dp[i][j + 1], dp[i][j] + a * Math.abs((n - 1 - j) - x));
            }
//            debug(dp);
        }
//        debug(dp);
        long ans = -1;
        for (int i = 0; i <= n; i++) {
            ans = Math.max(ans, dp[i][n - i]);
        }
        System.out.println(ans);
    }

    void debug(Object... os) {
        System.err.println(Arrays.deepToString(os));
    }

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

Score : 500 points

Problem Statement

There are N children standing in a line from left to right. The activeness of the i-th child from the left is A_i.

You can rearrange these children just one time in any order you like.

When a child who originally occupies the x-th position from the left in the line moves to the y-th position from the left, that child earns A_x \times |x-y| happiness points.

Find the maximum total happiness points the children can earn.

Constraints

2 \leq N \leq 2000

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 A_2 ... A_N

Output

Print the maximum total happiness points the children can earn.

Sample Input 1

4
1 3 4 2

Sample Output 1

20

If we move the 1-st child from the left to the 3-rd position from the left, the 2-nd child to the 4-th position, the 3-rd child to the 1-st position, and the 4-th child to the 2-nd position, the children earns 1 \times |1-3|+3 \times |2-4|+4 \times |3-1|+2 \times |4-2|=20 happiness points in total.

Sample Input 2

6
5 5 6 1 1 1

Sample Output 2

58

Sample Input 3

6
8 6 9 1 2 1

Sample Output 3

85


Score : 200 points

Problem Statement

Let us define the FizzBuzz sequence a_1,a_2,... as follows:

If both 3 and 5 divides i, a_i=\mbox{FizzBuzz}.

If the above does not hold but 3 divides i, a_i=\mbox{Fizz}.

If none of the above holds but 5 divides i, a_i=\mbox{Buzz}.

If none of the above holds, a_i=i.

Find the sum of all numbers among the first N terms of the FizzBuzz sequence.

Constraints

1 \leq N \leq 10^6

Input

Input is given from Standard Input in the following format:

N

Output

Print the sum of all numbers among the first N terms of the FizzBuzz sequence.

Sample Input 1

15

Sample Output 1

60

The first 15 terms of the FizzBuzz sequence are:

1,2,\mbox{Fizz},4,\mbox{Buzz},\mbox{Fizz},7,8,\mbox{Fizz},\mbox{Buzz},11,\mbox{Fizz},13,14,\mbox{FizzBuzz}

Among them, numbers are 1,2,4,7,8,11,13,14, and the sum of them is 60.

Sample Input 2

1000000

Sample Output 2

266666333332

Watch out for overflow.


import java.util.*;
public class Main{
public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int N = sc.nextInt();
    long m = 0 ;
    for(long i = 0;i<N;i++){
    if ((i%3)==0){}
    else if ((i%5)==0){}
    else{
    m = m+i;
    }
    }
	System.out.println(m);
    }
}