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

public class Main {
    static class Scanner {
        BufferedReader br;
        StringTokenizer tk = new StringTokenizer("");

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

        public int nextInt() throws IOException {
            if (tk.hasMoreTokens())
                return Integer.parseInt(tk.nextToken());
            tk = new StringTokenizer(br.readLine());
            return nextInt();
        }

        public long nextLong() throws IOException {
            if (tk.hasMoreTokens())
                return Long.parseLong(tk.nextToken());
            tk = new StringTokenizer(br.readLine());
            return nextLong();
        }

        public String next() throws IOException {
            if (tk.hasMoreTokens())
                return (tk.nextToken());
            tk = new StringTokenizer(br.readLine());
            return next();
        }

        public String nextLine() throws IOException {
            tk = new StringTokenizer("");
            return br.readLine();
        }

        public double nextDouble() throws IOException {
            if (tk.hasMoreTokens())
                return Double.parseDouble(tk.nextToken());
            tk = new StringTokenizer(br.readLine());
            return nextDouble();
        }

        public char nextChar() throws IOException {
            if (tk.hasMoreTokens())
                return (tk.nextToken().charAt(0));
            tk = new StringTokenizer(br.readLine());
            return nextChar();
        }

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

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

        public int[] nextIntArrayOneBased(int n) throws IOException {
            int a[] = new int[n + 1];
            for (int i = 1; i <= n; i++)
                a[i] = nextInt();
            return a;
        }

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

    }

    public static void main(String args[]) throws IOException {
        new Thread(null, new Runnable() {
            public void run() {
                try {
                    solve();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "1", 1 << 26).start();

    }
    static ArrayList<Integer> g[][];
    static int n, m;
    static int dp[][][][]=new int[2][3][302][302];
    static void solve() throws IOException {
        Scanner in = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        n=in.nextInt();
        m=in.nextInt();
        g=new ArrayList[n+1][4];
        for(int i=0;i<=n;i++)
            for(int j=0;j<4;j++)
                g[i][j]=new ArrayList<>();

        for(int i=0;i<m;i++){
            int l=in.nextInt();
            int r=in.nextInt();
            int x=in.nextInt();
            g[r][x].add(l);

        }

        for(int i=n+1;i>0;i--) {
            for(int lcu=0;lcu<3;lcu++){
                for(int c1=0;c1<i;c1++)
                    for(int c2=0;c2<i;c2++){
                        if(c1!=0 && c1==c2)
                            continue;
                        boolean val=true;
                        for(int ct=1;ct<=3;ct++){
                            for(int iii=0;iii<g[i-1][ct].size();iii++){
                                int x=g[i-1][ct].get(iii);
                                int vv=1;
                                if(c1>=x)
                                    vv++;
                                if(c2>=x)
                                    vv++;
                                if(vv!=ct)
                                {
                                    val=false;
                                    ct=5;
                                    break;
                                }
                            }
                        }
                        if(!val){
                            dp[i&1][lcu][c1][c2]=0;
                            continue;
                        }

                        if(i==n+1) {
                            dp[i&1][lcu][c1][c2] = 1;
                            continue;
                        }
                        long rrx=0;
                        rrx+=dp[(i+1)&1][lcu][c1][c2];
                        rrx+=dp[(i+1)&1][(lcu+1)%3][c2][i-1];
                        rrx+=dp[(i+1)&1][(lcu+2)%3][i-1][c1];
                        dp[i&1][lcu][c1][c2]=(int)(rrx%mod);
                    }
            }
        }
        out.println(dp[1][0][0][0]);
        out.close();

    }
    static int mod=1000000007;
//    static int sol(int i, int lcu, int c1,int c2){
//        if(i!=n+1 && dp[i][lcu][c1][c2]!=-1)
//            return dp[i][lcu][c1][c2];
//        for(int ct=1;ct<=3;ct++){
//            for(int x:g[i-1][ct]){
//                int vv=1;
//                if(c1>=x)
//                    vv++;
//                if(c2>=x)
//                    vv++;
//                if(vv!=ct)
//                    if(i==n+1)
//                        return 0;
//                    else
//                        return dp[i][lcu][c1][c2]=0;
//            }
//
//
//        }
//        if(i==n+1)
//            return 1;
//        long rrx=sol(i+1,lcu,c1,c2);
//        rrx+=sol(i+1, (lcu+1)%3, c2, i-1);
//        rrx+=sol(i+1, (lcu+2)%3, i-1, c1);
//        return (dp[i][lcu][c1][c2]=(int)(rrx%mod));
//    }
}

Score : 800 points

Problem Statement

There are N squares arranged in a row.
The squares are numbered 1, 2, ..., N, from left to right.

Snuke is painting each square in red, green or blue.
According to his aesthetic sense, the following M conditions must all be satisfied.
The i-th condition is:

There are exactly x_i different colors among squares l_i, l_i + 1, ..., r_i.

In how many ways can the squares be painted to satisfy all the conditions?
Find the count modulo 10^9+7.

Constraints

1 ≤ N ≤ 300

1 ≤ M ≤ 300

1 ≤ l_i ≤ r_i ≤ N

1 ≤ x_i ≤ 3

Input

Input is given from Standard Input in the following format:

N M
l_1 r_1 x_1
l_2 r_2 x_2
:
l_M r_M x_M

Output

Print the number of ways to paint the squares to satisfy all the conditions, modulo 10^9+7.

Sample Input 1

3 1
1 3 3

Sample Output 1

6

The six ways are:

RGB

RBG

GRB

GBR

BRG

BGR

where R, G and B correspond to red, green and blue squares, respectively.

Sample Input 2

4 2
1 3 1
2 4 2

Sample Output 2

6

The six ways are:

RRRG

RRRB

GGGR

GGGB

BBBR

BBBG

Sample Input 3

1 3
1 1 1
1 1 2
1 1 3

Sample Output 3

0

There are zero ways.

Sample Input 4

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

Sample Output 4

108


import java.util.*;

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

		if(c>=a && c<=b) System.out.println("Yes");
		else System.out.println("No");
	}
}

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

Score : 100 points

Problem Statement

You are given three integers A, B and C.
Determine whether C is not less than A and not greater than B.

Constraints

-100≤A,B,C≤100

A, B and C are all integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

If the condition is satisfied, print Yes; otherwise, print No.

Sample Input 1

1 3 2

Sample Output 1

Yes

C=2 is not less than A=1 and not greater than B=3, and thus the output should be Yes.

Sample Input 2

6 5 4

Sample Output 2

No

C=4 is less than A=6, and thus the output should be No.

Sample Input 3

2 2 2

Sample Output 3

Yes

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;

public class Main {

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

}

Score : 200 points

Problem Statement

There are N cities and M roads.
The i-th road (1≤i≤M) connects two cities a_i and b_i (1≤a_i,b_i≤N) bidirectionally.
There may be more than one road that connects the same pair of two cities.
For each city, how many roads are connected to the city?

Constraints

2≤N,M≤50

1≤a_i,b_i≤N

a_i ≠ b_i

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

Print the answer in N lines.
In the i-th line (1≤i≤N), print the number of roads connected to city i.

Sample Input 1

4 3
1 2
2 3
1 4

Sample Output 1

2
2
1
1

City 1 is connected to the 1-st and 3-rd roads.

City 2 is connected to the 1-st and 2-nd roads.

City 3 is connected to the 2-nd road.

City 4 is connected to the 3-rd road.

Sample Input 2

2 5
1 2
2 1
1 2
2 1
1 2

Sample Output 2

5
5

Sample Input 3

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

Sample Output 3

3
3
2
2
2
1
1
2


import java.util.Scanner;

public class Main {

  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    int n = Integer.parseInt(sc.next());
    long k = Long.parseLong(sc.next());
    long[] a = new long[100010];

    for (int i = 0; i < n; i++) {
      int x = Integer.parseInt(sc.next());
      int y = Integer.parseInt(sc.next());
      a[x] += (long) y;
    }

    long sum = 0;
    for (int i = 1; i < a.length; i++) {

      sum += (long) a[i];
      if (sum >= k) {
        System.out.println(i);
        break;
      }
    }

    sc.close();
  }
}

Score : 300 points

Problem Statement

There is an empty array.
The following N operations will be performed to insert integers into the array.
In the i-th operation (1≤i≤N), b_i copies of an integer a_i are inserted into the array.
Find the K-th smallest integer in the array after the N operations.
For example, the 4-th smallest integer in the array \{1,2,2,3,3,3\} is 3.

Constraints

1≤N≤10^5

1≤a_i,b_i≤10^5

1≤K≤b_1…+…b_n

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
a_1 b_1
:
a_N b_N

Output

Print the K-th smallest integer in the array after the N operations.

Sample Input 1

3 4
1 1
2 2
3 3

Sample Output 1

3

The resulting array is the same as the one in the problem statement.

Sample Input 2

10 500000
1 100000
1 100000
1 100000
1 100000
1 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000

Sample Output 2

1


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

public class Main {

	public static void main(String[] args) {
		new Main().solve();
	}
	int n,k;
	void solve(){
		Scanner sc=new Scanner(System.in);
		n=sc.nextInt();
		k=sc.nextInt();
		int[]a=new int[n];
		int[]b=new int[n];
		Pair[] p=new Pair[n];
		for(int i=0;i<n;i++){
			a[i]=sc.nextInt();
			b[i]=sc.nextInt();
			p[i]=new Pair(a[i],b[i]);
		}
		Arrays.sort(p);
		for(int i=0;i<n;i++){
			k-=p[i].b;
			if(k>0)continue;
			else{
				System.out.println(p[i].a);
				return;
			}
		}
	}
	class Pair implements Comparable<Pair>{
		int a;
		int b;
		Pair(int a,int b){
			this.a=a;
			this.b=b;
		}

		public int compareTo(Pair o){
			return this.a-o.a;
		}
	}
}


import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();
        if (a == b && b == c) {
            System.out.println(-1);
            return;
        }

        int count = 0;
        while (a % 2 == 0 && b % 2 == 0 && c % 2 == 0) {
            int disA = a / 2;
            int disB = b / 2;
            int disC = c / 2;
            a = a/2 + disB + disC;
            b = b/2 + disA + disC;
            b = b/2 + disB + disA;
            count++;
        }

        System.out.println(count);
    }
}

Score : 300 points

Problem Statement

Takahashi, Aoki and Snuke love cookies. They have A, B and C cookies, respectively. Now, they will exchange those cookies by repeating the action below:

Each person simultaneously divides his cookies in half and gives one half to each of the other two persons.

This action will be repeated until there is a person with odd number of cookies in hand.

How many times will they repeat this action?
Note that the answer may not be finite.

Constraints

1 ≤ A,B,C ≤ 10^9

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the number of times the action will be performed by the three people, if this number is finite.
If it is infinite, print -1 instead.

Sample Input 1

4 12 20

Sample Output 1

3

Initially, Takahashi, Aoki and Snuke have 4, 12 and 20 cookies. Then,

After the first action, they have 16, 12 and 8.

After the second action, they have 10, 12 and 14.

After the third action, they have 13, 12 and 11.

Now, Takahashi and Snuke have odd number of cookies, and therefore the answer is 3.

Sample Input 2

14 14 14

Sample Output 2

-1

Sample Input 3

454 414 444

Sample Output 3

1


import java.util.*;
public class Main{
	public static void main(String[] args){
    	Scanner sc = new Scanner(System.in);
      long a = sc.nextLong();
      long b = sc.nextLong();
      long c = sc.nextLong();
      int cnt = 0;
      long s = a+b+c;
      while(a%2==0&&b%2==0&&c%2==0){
      	a = -a/2+s;
        b = -b/2+s;
        c = -c/2+s;
        cnt++;
      }
      System.out.println(cnt);
    }
}


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

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

    static class B {
        public void solve(int testNumber, MyScanner in, PrintWriter out) {
            int N = in.nextInt();
            int M = in.nextInt();

            int[] count = new int[N + 1];
            for (int i = 0; i < M; i++) {
                int a = in.nextInt();
                int b = in.nextInt();
                count[a]++;
                count[b]++;
            }

            for (int n : count) {
                if (n % 2 != 0) {
                    out.println("NO");
                    return;
                }
            }
            out.println("YES");
        }

    }

    static class MyScanner {
        private BufferedReader in;
        private StringTokenizer st;

        public MyScanner(InputStream stream) {
            in = new BufferedReader(new InputStreamReader(stream));
        }

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

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

    }
}

Score : 500 points

Problem Statement

Takahashi is not good at problems about trees in programming contests, and Aoki is helping him practice.

First, Takahashi created a tree with N vertices numbered 1 through N, and wrote 0 at each edge.

Then, Aoki gave him M queries. The i-th of them is as follows:

Increment the number written at each edge along the path connecting vertices a_i and b_i, by one.

After Takahashi executed all of the queries, he told Aoki that, for every edge, the written number became an even number.
However, Aoki forgot to confirm that the graph Takahashi created was actually a tree, and it is possible that Takahashi made a mistake in creating a tree or executing queries.

Determine whether there exists a tree that has the property mentioned by Takahashi.

Constraints

2 ≤ N ≤ 10^5

1 ≤ M ≤ 10^5

1 ≤ a_i,b_i ≤ N

a_i ≠ b_i

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

Print YES if there exists a tree that has the property mentioned by Takahashi; print NO otherwise.

Sample Input 1

4 4
1 2
2 4
1 3
3 4

Sample Output 1

YES

For example, Takahashi's graph has the property mentioned by him if it has the following edges: 1-2, 1-3 and 1-4.
In this case, the number written at every edge will become 2.

Sample Input 2

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

Sample Output 2

NO


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

public class Main {
  public static void main(String[] args) {
    FastScanner sc = new FastScanner();
    int N = sc.nextInt();
    int M = sc.nextInt();

    int[] count = new int[N];
    for (int i = 0; i < M; i ++) {
      int a = sc.nextInt() - 1;
      int b = sc.nextInt() - 1;
      count[a] ++;
      count[b] ++;
    }

    boolean flg = true;
    for (int v : count) {
      if (v % 2 == 1) {
        flg = false;
        break;
      }
    }
    System.out.println(flg ? "YES" : "NO");

  }

}

class FastScanner {
	public static String debug = null;

	private final InputStream in = System.in;
	private int ptr = 0;
	private int buflen = 0;
	private byte[] buffer = new byte[1024];
	private boolean eos = false;

	private boolean hasNextByte() {
		if (ptr < buflen) {
			return true;
		} else {
			ptr = 0;
			try {
				if (debug != null) {
					buflen = debug.length();
					buffer = debug.getBytes();
					debug = "";
					eos = true;
				} else {
					buflen = in.read(buffer);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (buflen < 0) {
				eos = true;
				return false;
			} else 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;
	}

	private void skipUnprintable() {
		while (hasNextByte() && !isPrintableChar(buffer[ptr]))
			ptr++;
	}

	public boolean isEOS() {
		return this.eos;
	}

	public boolean hasNext() {
		skipUnprintable();
		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() {
		return (int) nextLong();
	}

	public long[] nextLongList(int n) {
		return nextLongTable(1, n)[0];
	}

	public int[] nextIntList(int n) {
		return nextIntTable(1, n)[0];
	}

	public long[][] nextLongTable(int n, int m) {
		long[][] ret = new long[n][m];
		for (int i = 0; i < n; i ++) {
			for (int j = 0; j < m; j ++) {
				ret[i][j] = nextLong();
			}
		}
		return ret;
	}

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


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

public class Main {
    static InputStream is;
    static PrintWriter out;
    static String INPUT = "";

    void solve() {
        int n = ni();
        Set<Integer> edge[] = new Set[n];
        for (int i = 0; i < n; ++i) {
            edge[i] = new HashSet<>();
        }
        Map<Long, Integer> edges = new HashMap<>();
        Queue<Long> pair = new ArrayDeque<>();
        for (int i = 0; i < (n - 1) * 2; ++i) {
            int a = ni() - 1;
            int b = ni() - 1;
            edge[a].add(b);
            edge[b].add(a);
            long key = getKey(a, b);
            int c = inc(edges, key);
            if (c == 2) {
                pair.add(key);
            }
        }
        boolean used[] = new boolean[n];
        for (int m = 1; m < n; ++m) {
            Integer x = -1, y = -1;
            while (!pair.isEmpty()) {
                long key = pair.poll();
                int a = (int) (key >>> 32);
                int b = (int) (key & ((1L << 32) - 1L));
                if (!used[a] && !used[b]) {
                    x = a;
                    y = b;
                    break;
                }
            }
            if (x.equals(-1)) {
                out.println("NO");
                return;
            }
            for (Integer t : edge[y]) {
                edge[t].remove(y);
                if (!t.equals(x)) {
                    edge[t].add(x);
                    edge[x].add(t);
                    long key = getKey(t, x);
                    int c = inc(edges, key);
                    if (c == 2) {
                        pair.add(key);
                    }
                }
            }
            used[y] = true;
        }
        out.println("YES");
    }

    long getKey(int a, int b) {
        if (a > b) {
            int t = a;
            a = b;
            b = t;
        }
        return (((long) a) << 32) | (long) b;
    }

    int inc(Map<Long, Integer> map, long key) {
        Integer x = map.get(key);
        if (x == null) {
            x = 1;
        } else {
            x += 1;
        }
        map.put(key, x);
        return x;
    }

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

        new Main().solve();
        out.flush();
        long G = System.currentTimeMillis();
        // tr(G - S + "ms");
    }

    private static boolean eof() {
        if (lenbuf == -1) return true;
        int lptr = ptrbuf;
        while (lptr < lenbuf)
            if (!isSpaceChar(inbuf[lptr++])) return false;

        try {
            is.mark(1000);
            while (true) {
                int b = is.read();
                if (b == -1) {
                    is.reset();
                    return true;
                } else if (!isSpaceChar(b)) {
                    is.reset();
                    return false;
                }
            }
        } catch (IOException e) {
            return true;
        }
    }

    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;
    }

    private static double nd() {
        return Double.parseDouble(ns());
    }

    private static char nc() {
        return (char) skip();
    }

    private static String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && 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);
    }

    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;
    }

    private static int[] na(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++)
            a[i] = ni();
        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();
        }
    }

    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();
        }
    }

    private static void tr(Object... o) {
        System.err.println(Arrays.deepToString(o));
    }
}

Score : 1400 points

Problem Statement

There is a tree with N vertices numbered 1 through N.
The i-th of the N-1 edges connects vertices a_i and b_i.

Initially, each edge is painted blue.
Takahashi will convert this blue tree into a red tree, by performing the following operation N-1 times:

Select a simple path that consists of only blue edges, and remove one of those edges.

Then, span a new red edge between the two endpoints of the selected path.

His objective is to obtain a tree that has a red edge connecting vertices c_i and d_i, for each i.

Determine whether this is achievable.

Constraints

2 ≤ N ≤ 10^5

1 ≤ a_i,b_i,c_i,d_i ≤ N

a_i ≠ b_i

c_i ≠ d_i

Both input graphs are trees.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 d_1
:
c_{N-1} d_{N-1}

Output

Print YES if the objective is achievable; print NO otherwise.

Sample Input 1

3
1 2
2 3
1 3
3 2

Sample Output 1

YES

The objective is achievable, as below:

First, select the path connecting vertices 1 and 3, and remove a blue edge 1-2. Then, span a new red edge 1-3.

Next, select the path connecting vertices 2 and 3, and remove a blue edge 2-3. Then, span a new red edge 2-3.

Sample Input 2

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

Sample Output 2

YES

Sample Input 3

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

Sample Output 3

NO


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int a = scan.nextInt();
		int b = scan.nextInt();
		int c = scan.nextInt();
		String message = "NO";
		int n = 0;
		int i = 0;
		for(i = 0; i < b; i++) {
			n = n + a;
			if(n % b == c) {
				message = "YES";
				break;
			}
		}
		System.out.println(message);
	}
}

Score : 200 points

Problem Statement

We ask you to select some number of positive integers, and calculate the sum of them.

It is allowed to select as many integers as you like, and as large integers as you wish.
You have to follow these, however: each selected integer needs to be a multiple of A, and you need to select at least one integer.

Your objective is to make the sum congruent to C modulo B.
Determine whether this is possible.

If the objective is achievable, print YES. Otherwise, print NO.

Constraints

1 ≤ A ≤ 100

1 ≤ B ≤ 100

0 ≤ C < B

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

7 5 1

Sample Output 1

YES

For example, if you select 7 and 14, the sum 21 is congruent to 1 modulo 5.

Sample Input 2

2 2 1

Sample Output 2

NO

The sum of even numbers, no matter how many, is never odd.

Sample Input 3

1 100 97

Sample Output 3

YES

You can select 97, since you may select multiples of 1, that is, all integers.

Sample Input 4

40 98 58

Sample Output 4

YES

Sample Input 5

77 42 36

Sample Output 5

NO


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.InputMismatchException;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;

public class Main {

	public static void main(String[] args) throws IOException {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskX solver = new TaskX();
		solver.solve(1, in, out);
		out.close();
	}

	static class TaskX {
		public void solve(int testNumber, InputReader in, PrintWriter out) {

			int n = in.nextInt();
			int time = in.nextInt();
			int[] t = in.nextIntArray(n);
			long sum = 0;
			Deque<Time> st = new ArrayDeque<Time>();

			for (int i = 0; i < n; i++) {
				int from = t[i];
				int to =  t[i] + time;
				if (st.isEmpty()) {
					st.push(new Time(from, to));
				} else {
					Time timez = st.peek();
					if (timez.to >= from) {
						st.remove();
						st.push(new Time(timez.from, to));
					} else {
						st.push(new Time(from, to));
					}
				}
			}

			while (!st.isEmpty()) {
				Time timez = st.pop();
				sum += timez.calcTime();
			}

			out.println(sum);
		}
	}
	static class Time {
		int from;
		int to;

		Time(int from, int to) {
			this.from = from;
			this.to = to;
		}

		long calcTime() {
			return this.to - this.from;
		}
	}

	static class ArrayUtils {
		public static Map<Integer, Integer> getCountMap(int[] array) {
			Map<Integer, Integer> map = new TreeMap<>();
			for (int x : array)
				map.merge(x, 1, Integer::sum);
			return map;
		}
	}

	static class InputReader {
		BufferedReader in;
		StringTokenizer tok;

		public String nextString() {
			while (!tok.hasMoreTokens()) {
				try {
					tok = new StringTokenizer(in.readLine(), " ");
				} catch (IOException e) {
					throw new InputMismatchException();
				}
			}
			return tok.nextToken();
		}

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

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

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

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

		public InputReader(InputStream inputStream) {
			in = new BufferedReader(new InputStreamReader(inputStream));
			tok = new StringTokenizer("");
		}

	}

}

Score : 300 points

Problem Statement

In a public bath, there is a shower which emits water for T seconds when the switch is pushed.

If the switch is pushed when the shower is already emitting water, from that moment it will be emitting water for T seconds.
Note that it does not mean that the shower emits water for T additional seconds.

N people will push the switch while passing by the shower.
The i-th person will push the switch t_i seconds after the first person pushes it.

How long will the shower emit water in total?

Constraints

1 ≤ N ≤ 200,000

1 ≤ T ≤ 10^9

0 = t_1 < t_2 < t_3 < , ..., < t_{N-1} < t_N ≤ 10^9

T and each t_i are integers.

Input

Input is given from Standard Input in the following format:

N T
t_1 t_2 ... t_N

Output

Assume that the shower will emit water for a total of X seconds. Print X.

Sample Input 1

2 4
0 3

Sample Output 1

7

Three seconds after the first person pushes the water, the switch is pushed again and the shower emits water for four more seconds, for a total of seven seconds.

Sample Input 2

2 4
0 5

Sample Output 2

8

One second after the shower stops emission of water triggered by the first person, the switch is pushed again.

Sample Input 3

4 1000000000
0 1000 1000000 1000000000

Sample Output 3

2000000000

Sample Input 4

1 1
0

Sample Output 4

1

Sample Input 5

9 10
0 3 5 7 100 110 200 300 311

Sample Output 5

67


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

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

	static class TaskC {
		public void solve(int testNumber, FastScanner in, PrintWriter out) {
			int n = in.nextInt();
			long T = in.nextInt();
			long ans = 0;
			long prev = -1;
			for (int i = 0; i < n; i++) {
				int t = in.nextInt();
				if (prev >= 0) {
					if (prev + T < t) {
						ans += T;
					} else {
						ans += t - prev;
					}
				}
				prev = t;
			}
			ans += T;
			out.println(ans);
		}

	}

	static class FastScanner {
		private BufferedReader in;
		private StringTokenizer st;

		public FastScanner(InputStream stream) {
			in = new BufferedReader(new InputStreamReader(stream));
		}

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

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

	}
}


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

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String a = sc.next();
    String b = sc.next();
    int stack_a;
    int stack_b;
    int judge = -1;

    if(a.equals(b)) judge = 0;
    else if(a.length() > b.length()) judge = 1;
    else if(a.length() < b.length()) judge = 2;
   	else if(a.length() == b.length()){
      for(int i = 0; i < a.length() && judge == -1; i++){
        stack_a = (int)a.charAt(i) - 48;
        stack_b = (int)b.charAt(i) - 48;
        if(stack_a > stack_b) judge = 1;
        else if(stack_a < stack_b) judge = 2;
      }
    }

    if(judge == 0) System.out.println("EQUAL");
    else if(judge == 1) System.out.println("GREATER");
    else if(judge == 2) System.out.println("LESS");
  }
}

Score : 200 points

Problem Statement

You are given two positive integers A and B. Compare the magnitudes of these numbers.

Constraints

1 ≤ A, B ≤ 10^{100}

Neither A nor B begins with a 0.

Input

Input is given from Standard Input in the following format:

A
B

Output

Print GREATER if A>B, LESS if A<B and EQUAL if A=B.

Sample Input 1

36
24

Sample Output 1

GREATER

Since 36>24, print GREATER.

Sample Input 2

850
3777

Sample Output 2

LESS

Sample Input 3

9720246
22516266

Sample Output 3

LESS

Sample Input 4

123456789012345678901234567890
234567890123456789012345678901

Sample Output 4

LESS


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

public class Main {
    public static void main(String[] args){
        FastScanner sc = new FastScanner();
        String A = sc.next();
        String B = sc.next();
        String result = "EQUAL";
        if (A.length() > B.length()) {
            result = "GREATER";
        } else if (A.length() < B.length()) {
            result = "LESS";
        } else {
            for (int i = 0; i < A.length(); i++) {
                int a = Character.getNumericValue(A.charAt(i));
                int b = Character.getNumericValue(B.charAt(i));
                if (a < b) {
                    result = "LESS";
                    break;
                } else if (a > b) {
                    result = "GREATER";
                    break;
                }
            }

        }
        System.out.println(result);
    }

    static class FastScanner {
        private final InputStream in = System.in;
        private final byte[] buffer = new byte[1024];
        private int ptr = 0;
        private int buflen = 0;
        private boolean hasNextByte() {
            if (ptr < buflen) {
                return true;
            }else{
                ptr = 0;
                try {
                    buflen = in.read(buffer);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (buflen <= 0) {
                    return false;
                }
            }
            return true;
        }
        private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
        private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
        public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
        public String next() {
            if (!hasNext()) throw new NoSuchElementException();
            StringBuilder sb = new StringBuilder();
            int b = readByte();
            while(isPrintableChar(b)) {
                sb.appendCodePoint(b);
                b = readByte();
            }
            return sb.toString();
        }
        public long nextLong() {
            if (!hasNext()) throw new NoSuchElementException();
            long n = 0;
            boolean minus = false;
            int b = readByte();
            if (b == '-') {
                minus = true;
                b = readByte();
            }
            if (b < '0' || '9' < b) {
                throw new NumberFormatException();
            }
            while(true){
                if ('0' <= b && b <= '9') {
                    n *= 10;
                    n += b - '0';
                }else if(b == -1 || !isPrintableChar(b)){
                    return minus ? -n : n;
                }else{
                    throw new NumberFormatException();
                }
                b = readByte();
            }
        }
        public int nextInt() {
            long nl = nextLong();
            if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
            return (int) nl;
        }
        public double nextDouble() { return Double.parseDouble(next());}
    }
}


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

public class Main {
	 public static void main(String args[]){
			Scanner sc = new Scanner(System.in);
			// 整数の入力
			int n = sc.nextInt();
			int a[] = new int[n];
			for(int i = 0;i<a.length;i++)
			{
				a[i] = sc.nextInt();
			}
			int b[] = new int[n];
			b[0] = a[0];
			int count = 0;
			for(int i = 0;i<a.length-1;i++)
			{
				b[i+1] = b[i] + a[i+1];
				if(b[i+1]*b[i]>0)
				{
					count += Math.abs(b[i+1])+1;
					if(b[i+1]>0) b[i+1]=-1;
					else b[i+1] = 1;
				}
				else if(b[i+1] == 0)
				{
					if(b[i]>0) b[i+1]=-1;
					else b[i+1] = 1;
					count++;
				}
			}
			System.out.println(count);

		  }

}

Score : 300 points

Problem Statement

You are given an integer sequence of length N. The i-th term in the sequence is a_i.
In one operation, you can select a term and either increment or decrement it by one.

At least how many operations are necessary to satisfy the following conditions?

For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.

For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Constraints

2 ≤ n ≤ 10^5

|a_i| ≤ 10^9

Each a_i is an integer.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print the minimum necessary count of operations.

Sample Input 1

4
1 -3 1 0

Sample Output 1

4

For example, the given sequence can be transformed into 1, -2, 2, -2 by four operations. The sums of the first one, two, three and four terms are 1, -1, 1 and -1, respectively, which satisfy the conditions.

Sample Input 2

5
3 -6 4 -5 7

Sample Output 2

0

The given sequence already satisfies the conditions.

Sample Input 3

6
-1 4 3 2 -5 4

Sample Output 3

8


import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

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

		Scanner sc = new Scanner(System.in);
		// 整数の入力
		int n = sc.nextInt();
		int l = sc.nextInt();
		int t = sc.nextInt();

		int[] x = new int[n];
		int[] w = new int[n];

		for(int i=0;i<n;i++) {
			x[i] =  sc.nextInt();
			w[i] =  sc.nextInt();
		}

		int[] y = new int[n];

		ArrayList<Integer> list = new ArrayList<>();
		for(int i = 0;i<n;i++) {
			if(w[i]==1) {
				y[i] = location(l,x[i]+t);
			}else {
				y[i] = location(l,x[i]-t);
			}
			list.add(y[i]);
		}
		int firstIndex = y[0];
		Collections.sort(list);

		int counter =0;

		if(w[0]==1) {
			for(int i = 1;i<n;i++) {
				if(w[i]==2) {
					if(t*2-(x[i]-x[0])<0) {

					}else {
						counter+=(t*2-(x[i]-x[0]))/l+1;
					}
				}
			}
			counter = (counter+1)%n;
			if(counter ==0)counter =n;

		}else {
			for(int i = n-1;i>0;i--) {
				if(w[i]==1) {
					if(t*2-(x[0]+l-x[i])<0) {

					}else {
						counter+=(t*2-(x[0]+l-x[i]))/l+1;
					}
				}
			}
			counter = (1-counter);
			while(counter<1) {
				counter+=n;
			}
			counter = counter%n;
			if(counter ==0)counter =n;
		}

		for(int i =1;i<n+1;i++) {
			int listindex = list.indexOf(firstIndex)-counter+i;
			if(listindex<0) {
				listindex+=n;
			}
			if(listindex>=n) {
				listindex-=n;
			}
			System.out.println(list.get(listindex));
		}

		/*
		TreeMap<Integer,Integer> treeMap = new TreeMap<>();//sorted no duplication
		treeMap.put(b[n], n);
		*/

	}

	static int location(int length,long value) {

		int loc = (int) (value%length);
		if(loc<0)loc+=length;

		return loc;
	}

}
/*
class City{
	int order;
	int prefecture;
	int year;
	int number;
	City(int order,int prefecture, int year){
		this.order = order;
		this.prefecture = prefecture;
		this.year = year;
	}
}
*/

Score : 700 points

Problem Statement

There is a circle with a circumference of L.
Each point on the circumference has a coordinate value, which represents the arc length from a certain reference point clockwise to the point.
On this circumference, there are N ants.
These ants are numbered 1 through N in order of increasing coordinate, and ant i is at coordinate X_i.

The N ants have just started walking.
For each ant i, you are given the initial direction W_i. Ant i is initially walking clockwise if W_i is 1; counterclockwise if W_i is 2.
Every ant walks at a constant speed of 1 per second.
Sometimes, two ants bump into each other.
Each of these two ants will then turn around and start walking in the opposite direction.

For each ant, find its position after T seconds.

Constraints

All input values are integers.

1 \leq N \leq 10^5

1 \leq L \leq 10^9

1 \leq T \leq 10^9

0 \leq X_1 < X_2 < ... < X_N \leq L - 1

1 \leq W_i \leq 2

Input

The input is given from Standard Input in the following format:

N L T
X_1 W_1
X_2 W_2
:
X_N W_N

Output

Print N lines.
The i-th line should contain the coordinate of ant i after T seconds. Here, each coordinate must be between 0 and L-1, inclusive.

Sample Input 1

3 8 3
0 1
3 2
6 1

Sample Output 1

1
3
0

1.5 seconds after the ants start walking, ant 1 and 2 bump into each other at coordinate 1.5.
1 second after that, ant 1 and 3 bump into each other at coordinate 0.5.
0.5 seconds after that, that is, 3 seconds after the ants start walking, ants 1, 2 and 3 are at coordinates 1, 3 and 0, respectively.

Sample Input 2

4 20 9
7 2
9 1
12 1
18 1

Sample Output 2

7
18
18
1


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

/**
 * @author Pavel Mavrin
 */
public class Main {

    private void solve() throws IOException {
        int n = nextInt();
        long l = nextInt();
        long t = nextInt();
        long[] x = new long[n];
        int[] w = new int[n];
        for (int i = 0; i < n; i++) {
            x[i] = nextInt();
            w[i] = nextInt() == 1 ? 1 : -1;
        }
        long[] y = new long[n];
        long q = 0;
        for (int i = 0; i < n; i++) {
            int ww = w[i] - w[0];
            y[i] = x[i] + t * ww;
            if (y[i] >= l) {
                q -= y[i] / l;
                y[i] %= l;
            }
            if (y[i] < 0) {
                q += ((-y[i]) / l) + 1;
                y[i] %= l;
                if (y[i] < 0) y[i] += l;
            }
        }
        q %= n;
        if (q < 0) q += n;
        Arrays.sort(y);

        long[] res = new long[n];
        for (int i = 0; i < n; i++) {
            int k = (int) ((i + q) % n);
            res[k] = y[i] + w[0] * t;
            res[k] %= l;
            if (res[k] < 0) res[k] += l;
        }
        for (int i = 0; i < n; i++) {
            out.println(res[i]);
        }
    }

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

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer st;
    PrintWriter out = new PrintWriter(System.out);

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

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

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

    private void run() throws IOException {
        solve();
        out.close();
    }

}


import java.util.Scanner;

public class Main {
    static final long MOD = 1000000007;
    public static void main(String[] args) {
        int n = 0, m = 0;
        long[] xs, ys;
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        sc.nextLine();
        xs = new long[n];
        ys = new long[m];
        for (int i = 0; i < n; i++) {
            xs[i] = sc.nextLong();
        }
        sc.nextLine();
        for (int i = 0; i < m; i++) {
            ys[i] = sc.nextLong();
        }
        long ans1 = 0l;
        long ans2 = 0l;
        long tmp;
        for (int i = 0; i < n; i++) {
            tmp = (i * xs[i]) % MOD;
            tmp -= ((n - 1 - i) * xs[i]) % MOD;
            ans1 = (ans1 + tmp) % MOD;
        }
        for (int j = 0; j < m; j++) {
            tmp = (j * ys[j]) % MOD;
            tmp -= ((m - 1 - j) * ys[j]) % MOD;
            ans2 = (ans2 + tmp) % MOD;
        }
        System.out.println((ans1 *ans2) % MOD);
    }
}

Score : 500 points

Problem Statement

On a two-dimensional plane, there are m lines drawn parallel to the x axis, and n lines drawn parallel to the y axis.
Among the lines parallel to the x axis, the i-th from the bottom is represented by y = y_i.
Similarly, among the lines parallel to the y axis, the i-th from the left is represented by x = x_i.

For every rectangle that is formed by these lines, find its area, and print the total area modulo 10^9+7.

That is, for every quadruple (i,j,k,l) satisfying 1\leq i < j\leq n and 1\leq k < l\leq m, find the area of the rectangle formed by the lines x=x_i, x=x_j, y=y_k and y=y_l, and print the sum of these areas modulo 10^9+7.

Constraints

2 \leq n,m \leq 10^5

-10^9 \leq x_1 < ... < x_n \leq 10^9

-10^9 \leq y_1 < ... < y_m \leq 10^9

x_i and y_i are integers.

Input

Input is given from Standard Input in the following format:

n m
x_1 x_2 ... x_n
y_1 y_2 ... y_m

Output

Print the total area of the rectangles, modulo 10^9+7.

Sample Input 1

3 3
1 3 4
1 3 6

Sample Output 1

60

The following figure illustrates this input:

The total area of the nine rectangles A, B, ..., I shown in the following figure, is 60.

Sample Input 2

6 5
-790013317 -192321079 95834122 418379342 586260100 802780784
-253230108 193944314 363756450 712662868 735867677

Sample Output 2

835067060


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

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

    int N = scanner.nextInt();
    int[] A = new int[N * 3];
    for (int i = 0; i < N * 3; i++) A[i] = scanner.nextInt();
    Arrays.sort(A);
    reverse(A);

    long res = 0;
    for (int i = 1; i < N * 2; i += 2) res += A[i];
    System.out.println(res);
  }

  private static void reverse(int[] a) {
    int i = 0;
    int j = a.length - 1;
    while (i < j) {
      int tmp = a[i];
      a[i] = a[j];
      a[j] = tmp;
      i++;
      j--;
    }
  }
}

Score : 300 points

Problem Statement

There are 3N participants in AtCoder Group Contest.
The strength of the i-th participant is represented by an integer a_i.
They will form N teams, each consisting of three participants.
No participant may belong to multiple teams.

The strength of a team is defined as the second largest strength among its members.
For example, a team of participants of strength 1, 5, 2 has a strength 2, and a team of three participants of strength 3, 2, 3 has a strength 3.

Find the maximum possible sum of the strengths of N teams.

Constraints

1 ≤ N ≤ 10^5

1 ≤ a_i ≤ 10^{9}

a_i are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{3N}

Output

Print the answer.

Sample Input 1

2
5 2 8 5 1 5

Sample Output 1

10

The following is one formation of teams that maximizes the sum of the strengths of teams:

Team 1: consists of the first, fourth and fifth participants.

Team 2: consists of the second, third and sixth participants.

Sample Input 2

10
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 2

10000000000

The sum of the strengths can be quite large.


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

public class Main {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ
		Scanner sc = new Scanner(System.in);
		// 整数の入力
		int M = sc.nextInt();
		int N = sc.nextInt();

		ArrayList<Integer> data[] = new ArrayList[M];
		for (int i = 0; i < N; i++) {
			data[i] = new ArrayList();
		}

		for (int i = 0; i < N; i++) {
			int a = sc.nextInt();
			int b = sc.nextInt();
			data[a - 1].add(b);
			data[b - 1].add(a);
			System.out.println("i=" + i);
		}

		int Q = sc.nextInt();
		int iro[] = new int[M];
		Arrays.fill(iro, 0);

		for (int i = 0; i < Q; i++) {
			int v = sc.nextInt();
			int d = sc.nextInt();
			int c = sc.nextInt();

			saiki(data, iro, v, d, c);
		}

		// 出力
		for (int i = 0; i < iro.length; i++) {
			System.out.println(iro[i]);
		}
	}

	public static void saiki(ArrayList<Integer> data[], int iro[], int v, int d, int c) {
		iro[v - 1] = c;
		for (int j = 0; j < data[v - 1].size(); j++) {
			int target = data[v - 1].get(j);
			iro[target - 1] = c;

			if (d != 1) {
				d -= 1;
				saiki(data, iro, target, d, c);
				d += 1;
			}
		}
	}
}


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

public class Main {

    static void solve(FastScanner sc, PrintWriter out) {
        int N = sc.ni();
        for (int n = (int) Math.sqrt(N); n <= N; n++) {
            if (N % n != 0) continue;
            out.println((int) Math.log10(n) + 1);
            break;
        }
    }

    public static void main(String[] args) {
        FastScanner sc = new FastScanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        solve(sc, out);
        out.flush();
    }

    static class FastScanner {
        private final InputStream is;
        private byte[] inbuf = new byte[1024];
        private int lenbuf = 0, ptrbuf = 0;

        FastScanner(InputStream is) {
            this.is = is;
        }

        char nc() {
            return (char) skip();
        }

        char[] nca(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);
        }

        char[][] nca2(int n, int m) {
            char[][] buf = new char[m][n];
            for (int i = 0; i < m; i++) {
                buf[i] = nca(n);
            }
            return buf;
        }

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

        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();
            }
        }

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

        long nl() {
            long 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();
            }
        }

        double nd() {
            return Double.parseDouble(ns());
        }

        private 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 int skip() {
            int b;
            while ((b = readByte()) != -1 && isSpaceChar(b)) ;
            return b;
        }

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

}

Score : 300 points

Problem Statement

You are given an integer N.

For two positive integers A and B, we will define F(A,B) as the larger of the following: the number of digits in the decimal notation of A, and the number of digits in the decimal notation of B.

For example, F(3,11) = 2 since 3 has one digit and 11 has two digits.

Find the minimum value of F(A,B) as (A,B) ranges over all pairs of positive integers such that N = A \times B.

Constraints

1 \leq N \leq 10^{10}

N is an integer.

Input

The input is given from Standard Input in the following format:

N

Output

Print the minimum value of F(A,B) as (A,B) ranges over all pairs of positive integers such that N = A \times B.

Sample Input 1

10000

Sample Output 1

3

F(A,B) has a minimum value of 3 at (A,B)=(100,100).

Sample Input 2

1000003

Sample Output 2

7

There are two pairs (A,B) that satisfy the condition: (1,1000003) and (1000003,1). For these pairs, F(1,1000003)=F(1000003,1)=7.

Sample Input 3

9876543210

Sample Output 3

6


import java.util.*;

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

Score : 100 points

Problem Statement

Two deer, AtCoDeer and TopCoDeer, are playing a game called Honest or Dishonest.
In this game, an honest player always tells the truth, and an dishonest player always tell lies.
You are given two characters a and b as the input. Each of them is either H or D, and carries the following information:

If a=H, AtCoDeer is honest; if a=D, AtCoDeer is dishonest.
If b=H, AtCoDeer is saying that TopCoDeer is honest; if b=D, AtCoDeer is saying that TopCoDeer is dishonest.

Given this information, determine whether TopCoDeer is honest.

Constraints

a=H or a=D.

b=H or b=D.

Input

The input is given from Standard Input in the following format:

a b

Output

If TopCoDeer is honest, print H. If he is dishonest, print D.

Sample Input 1

H H

Sample Output 1

H

In this input, AtCoDeer is honest. Hence, as he says, TopCoDeer is honest.

Sample Input 2

D H

Sample Output 2

D

In this input, AtCoDeer is dishonest. Hence, contrary to what he says, TopCoDeer is dishonest.

Sample Input 3

D D

Sample Output 3

H


import java.util.Scanner;

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

		int W = Integer.parseInt(sc.next());
		int a = Integer.parseInt(sc.next());
		int b = Integer.parseInt(sc.next());

//		if (b - (a+W) > 0) {
//			System.out.println(b - (a+W));
//		}else if (a-(b+W) > 0) {
//			System.out.println(a-(b+W));
//		}else {
//			System.out.println(0);
//		}

		System.out.println(Math.max(Math.abs(a-b)-W, 0));
	}
}

Score : 200 points

Problem Statement

AtCoDeer the deer found two rectangles lying on the table, each with height 1 and width W.
If we consider the surface of the desk as a two-dimensional plane, the first rectangle covers the vertical range of [0,1] and the horizontal range of [a,a+W], and the second rectangle covers the vertical range of [1,2] and the horizontal range of [b,b+W], as shown in the following figure:

AtCoDeer will move the second rectangle horizontally so that it connects with the first rectangle.
Find the minimum distance it needs to be moved.

Constraints

All input values are integers.

1≤W≤10^5

1≤a,b≤10^5

Input

The input is given from Standard Input in the following format:

W a b

Output

Print the minimum distance the second rectangle needs to be moved.

Sample Input 1

3 2 6

Sample Output 1

1

This input corresponds to the figure in the statement. In this case, the second rectangle should be moved to the left by a distance of 1.

Sample Input 2

3 1 3

Sample Output 2

0

The rectangles are already connected, and thus no move is needed.

Sample Input 3

5 10 1

Sample Output 3

4


import java.io.*;
import java.util.*;
import java.util.function.IntPredicate;

public class Main{
	int N;
	int[] L;
	int[] R;
	public void solve(){
		N = nextInt();
		L = new int[N];
		R = new int[N];
		for(int i = 0; i < N; i++){
			L[i] = nextInt();
			R[i] = nextInt();
		}
		int ans = Integer.MAX_VALUE;
		for(int i = 1; i <= 400; i++){
			int sum = 0;
			for(int j = 0; j < N; j++){
				if(L[j] <= i && i <= R[j]) continue;
				if(i < L[j]) sum += L[j] - i;
				else sum += i - R[j];
			}
			ans = Math.min(sum, ans);
		}
		out.println(ans);
	}

	int sum(int[] bit, int i) {
		i++;
		int s = 0;
		while(i > 0){
			s += bit[i];
			i -= i & -i;
		}
		return s;
	}
	void add(int[] bit, int i, int x){
		i++;
		while(i <= (1<<13)){
			bit[i] += x;
			i += i & -i;
		}
	}

	private static PrintWriter out;
	public static void main(String[] args){
		out = new PrintWriter(System.out);
		new Main().solve();
		out.flush();
	}

	public static int nextInt(){
		int num = 0;
		String str = next();
		boolean minus = false;
		int i = 0;
		if(str.charAt(0) == '-'){
			minus = true;
			i++;
		}
		int len = str.length();
		for(;i < len; i++){
			char c = str.charAt(i);
			if(!('0' <= c && c <= '9')) throw new RuntimeException();
			num = num * 10 + (c - '0');
		}
		return minus ? -num : num;
	}

	public static long nextLong(){
		long num = 0;
		String str = next();
		boolean minus = false;
		int i = 0;
		if(str.charAt(0) == '-'){
			minus = true;
			i++;
		}
		int len = str.length();
		for(;i < len; i++){
			char c = str.charAt(i);
			if(!('0' <= c && c <= '9')) throw new RuntimeException();
			num = num * 10l + (c - '0');
		}
		return minus ? -num : num;
	}
	public static String next(){
		int c;
		while(!isAlNum(c = read())){}
		StringBuilder build = new StringBuilder();
		build.append((char)c);
		while(isAlNum(c = read())){
			build.append((char)c);
		}
		return build.toString();
	}

	private static byte[] inputBuffer = new byte[1024];
	private static int bufferLength = 0;
	private static int bufferIndex = 0;
	private static int read(){
		if(bufferLength < 0) throw new RuntimeException();
		if(bufferIndex >= bufferLength){
			try{
				bufferLength = System.in.read(inputBuffer);
				bufferIndex = 0;
			}catch(IOException e){
				throw new RuntimeException(e);
			}
			if(bufferLength <= 0) return (bufferLength = -1);
		}
		return inputBuffer[bufferIndex++];
	}

	private static boolean isAlNum(int c){
		return '!' <= c && c <= '~';
	}
}

Score : 1000 points

Problem Statement

AtCoDeer the deer found N rectangle lying on the table, each with height 1.
If we consider the surface of the desk as a two-dimensional plane, the i-th rectangle i(1≤i≤N) covers the vertical range of [i-1,i] and the horizontal range of [l_i,r_i], as shown in the following figure:

AtCoDeer will move these rectangles horizontally so that all the rectangles are connected.
For each rectangle, the cost to move it horizontally by a distance of x, is x.
Find the minimum cost to achieve connectivity.
It can be proved that this value is always an integer under the constraints of the problem.

Constraints

All input values are integers.

1≤N≤10^5

1≤l_i<r_i≤10^9

Partial Score

300 points will be awarded for passing the test set satisfying 1≤N≤400 and 1≤l_i<r_i≤400.

Input

The input is given from Standard Input in the following format:

N
l_1 r_1
l_2 r_2
:
l_N r_N

Output

Print the minimum cost to achieve connectivity.

Sample Input 1

3
1 3
5 7
1 3

Sample Output 1

2

The second rectangle should be moved to the left by a distance of 2.

Sample Input 2

3
2 5
4 6
1 4

Sample Output 2

0

The rectangles are already connected, and thus no move is needed.

Sample Input 3

5
999999999 1000000000
1 2
314 315
500000 500001
999999999 1000000000

Sample Output 3

1999999680

Sample Input 4

5
123456 789012
123 456
12 345678901
123456 789012
1 23

Sample Output 4

246433

Sample Input 5

1
1 400

Sample Output 5

0


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

public class Main {
  private static int N;
  private static Deque<Integer> queue = new ArrayDeque<Integer>();
  public static void main(String[] args) {
    FastScanner sc = new FastScanner();
    N = sc.nextInt();
    long K = sc.nextLong();
    String s = sc.next();

    for (int i = 0; i < N; i ++) {
      int v = s.charAt(i) - 'A';
      if (i % 2 == 1) {
        v = v == 0 ? 1 : 0;
      }
      queue.add(v);
    }

    if (2 * N < K) {
      for (int i = 0; i < 2 * N; i ++) {
        next();
      }
      String s1 = build();
      next();
      String s2 = build();

      System.out.println(K % 2 == 0 ? s1 : s2);
    } else {
      for (int i = 0; i < K; i ++) {
        next();
      }
      System.out.println(build());
    }

  }

  private static void next() {
    if (queue.pollFirst() == 0) {
      queue.addFirst(1);
    } else {
      queue.addLast(N % 2 == 0 ? 1 : 0);
    }
  }

  private static String build() {
    StringBuilder sb = new StringBuilder();
    int ptr = 0;
    for (int v : queue) {
      if (ptr % 2 == 1) {
        v = v == 0 ? 1 : 0;
      }
      sb.append((char)('A' + v));
      ptr ++;
    }
    return sb.toString();
  }
}

class FastScanner {
	public static String debug = null;

	private final InputStream in = System.in;
	private int ptr = 0;
	private int buflen = 0;
	private byte[] buffer = new byte[1024];
	private boolean eos = false;

	private boolean hasNextByte() {
		if (ptr < buflen) {
			return true;
		} else {
			ptr = 0;
			try {
				if (debug != null) {
					buflen = debug.length();
					buffer = debug.getBytes();
					debug = "";
					eos = true;
				} else {
					buflen = in.read(buffer);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (buflen < 0) {
				eos = true;
				return false;
			} else 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;
	}

	private void skipUnprintable() {
		while (hasNextByte() && !isPrintableChar(buffer[ptr]))
			ptr++;
	}

	public boolean isEOS() {
		return this.eos;
	}

	public boolean hasNext() {
		skipUnprintable();
		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() {
		return (int) nextLong();
	}

	public long[] nextLongList(int n) {
		return nextLongTable(1, n)[0];
	}

	public int[] nextIntList(int n) {
		return nextIntTable(1, n)[0];
	}

	public long[][] nextLongTable(int n, int m) {
		long[][] ret = new long[n][m];
		for (int i = 0; i < n; i ++) {
			for (int j = 0; j < m; j ++) {
				ret[i][j] = nextLong();
			}
		}
		return ret;
	}

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

Score : 900 points

Problem Statement

Takahashi has a lot of peculiar devices.
These cylindrical devices receive balls from left and right.
Each device is in one of the two states A and B, and for each state, the device operates as follows:

When a device in state A receives a ball from either side (left or right), the device throws out the ball from the same side, then immediately goes into state B.

When a device in state B receives a ball from either side, the device throws out the ball from the other side, then immediately goes into state A.

The transition of the state of a device happens momentarily and always completes before it receives another ball.

Takahashi built a contraption by concatenating N of these devices. In this contraption,

A ball that was thrown out from the right side of the i-th device from the left (1 \leq i \leq N-1) immediately enters the (i+1)-th device from the left side.

A ball that was thrown out from the left side of the i-th device from the left (2 \leq i \leq N) immediately enters the (i-1)-th device from the right side.

The initial state of the i-th device from the left is represented by the i-th character in a string S.
From this situation, Takahashi performed the following K times: put a ball into the leftmost device from the left side, then wait until the ball comes out of the contraption from either end.
Here, it can be proved that the ball always comes out of the contraption after a finite time.
Find the state of each device after K balls are processed.

Constraints

1 \leq N \leq 200,000

1 \leq K \leq 10^9

|S|=N

Each character in S is either A or B.

Input

The input is given from Standard Input in the following format:

N K
S

Output

Print a string that represents the state of each device after K balls are processed.
The string must be N characters long, and the i-th character must correspond to the state of the i-th device from the left.

Sample Input 1

5 1
ABAAA

Sample Output 1

BBAAA

In this input, we put a ball into the leftmost device from the left side, then it is returned from the same place.

Sample Input 2

5 2
ABAAA

Sample Output 2

ABBBA

Sample Input 3

4 123456789
AABB

Sample Output 3

BABA


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class Main {
	static InputStream is;
	static PrintWriter out;
	static String INPUT = "";

	static void solve()
	{
		char[] s = ns().toCharArray();
		int n = s.length;
		int[] o = new int[n];
		for(int i = 0;i < n;i++)o[i] = s[i]-'0';
		int low = 0, high = 500003*10/9;
		while(high - low > 1){
			int h = high+low>>1;
			if(ok(h, Arrays.copyOf(o, n))){
				high = h;
			}else{
				low = h;
			}
		}
		out.println(high);
	}

	static boolean ok(int h, int[] s)
	{
		int lim = h*9;
		int n = s.length;
		int nz = 0;
		for(int i = n-1;i >= 0;i--){
			int u = 0;
			if(nz <= i-8){
				u = 99999999;
			}
			if(u == 0){
				for(int j = Math.max(0, i-7);j <= i;j++){
					u = u * 10 + s[j];
				}
			}
			lim = Math.min(u, lim);
			if(lim < s[i])return false;
			lim = (lim-s[i])/10*10;
			s[i] -= lim;
			for(int j = i;j >= 0 && s[j] < 0;j--){
				int q = (-s[j]+9)/10;
				s[j] += q*10;
				s[j-1] -= q;
			}
			while(nz < i && s[nz] == 0)nz++;
		}
		return true;
	}

	public static void main(String[] args) throws Exception
	{
//		int n = 500000, m = 99999;
//		Random gen = new Random();
//		StringBuilder sb = new StringBuilder();
//		for (int i = 0; i < n; i++) {
//			sb.append(gen.nextInt(10));
//		}
//		INPUT = sb.toString();

		long S = System.currentTimeMillis();
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		solve();
		out.flush();
		long G = System.currentTimeMillis();
		tr(G-S+"ms");
	}

	private static boolean eof()
	{
		if(lenbuf == -1)return true;
		int lptr = ptrbuf;
		while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false;

		try {
			is.mark(1000);
			while(true){
				int b = is.read();
				if(b == -1){
					is.reset();
					return true;
				}else if(!isSpaceChar(b)){
					is.reset();
					return false;
				}
			}
		} catch (IOException e) {
			return true;
		}
	}

	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 boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); }
	private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

	private static double nd() { return Double.parseDouble(ns()); }
	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);
	}

	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;
	}

	private static int[] na(int n)
	{
		int[] a = new int[n];
		for(int i = 0;i < n;i++)a[i] = ni();
		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();
		}
	}

	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();
		}
	}

	private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}

Score : 1300 points

Problem Statement

We will call a non-negative integer increasing if, for any two adjacent digits in its decimal representation, the digit to the right is greater than or equal to the digit to the left.
For example, 1558, 11, 3 and 0 are all increasing; 10 and 20170312 are not.

Snuke has an integer N. Find the minimum number of increasing integers that can represent N as their sum.

Constraints

1 \leq N \leq 10^{500000}

Input

The input is given from Standard Input in the following format:

N

Output

Print the minimum number of increasing integers that can represent N as their sum.

Sample Input 1

80

Sample Output 1

2

One possible representation is 80 = 77 + 3.

Sample Input 2

123456789

Sample Output 2

1

123456789 in itself is increasing, and thus it can be represented as the sum of one increasing integer.

Sample Input 3

20170312

Sample Output 3

4

Sample Input 4

7204647845201772120166980358816078279571541735614841625060678056933503

Sample Output 4

31


import java.util.Scanner;
public class Main {

	public static void main(String[] args) {
		Scanner s=new Scanner(System.in);
		int n=s.nextInt();
		System.out.println((n*800)-(n/15*200));
	}
}

Score : 100 points

Problem Statement

Snuke has a favorite restaurant.

The price of any meal served at the restaurant is 800 yen (the currency of Japan), and each time a customer orders 15 meals, the restaurant pays 200 yen back to the customer.

So far, Snuke has ordered N meals at the restaurant.
Let the amount of money Snuke has paid to the restaurant be x yen, and let the amount of money the restaurant has paid back to Snuke be y yen.
Find x-y.

Constraints

1 ≤ N ≤ 100

Input

The input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

20

Sample Output 1

15800

So far, Snuke has paid 16000 yen, and the restaurant has paid back 200 yen. Thus, the answer is 15800.

Sample Input 2

60

Sample Output 2

47200

Snuke has paid 48000 yen for 60 meals, and the restaurant has paid back 800 yen.


import java.util.Scanner;
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int pw = 1;
		for(int i=1;i<=N;i++) {
			pw = pw * i;
		}
		System.out.println(pw % (Math.pow(10,9)+7));
	}

}

Score : 200 points

Problem Statement

Snuke loves working out. He is now exercising N times.

Before he starts exercising, his power is 1. After he exercises for the i-th time, his power gets multiplied by i.

Find Snuke's power after he exercises N times. Since the answer can be extremely large, print the answer modulo 10^{9}+7.

Constraints

1 ≤ N ≤ 10^{5}

Input

The input is given from Standard Input in the following format:

N

Output

Print the answer modulo 10^{9}+7.

Sample Input 1

3

Sample Output 1

6

After Snuke exercises for the first time, his power gets multiplied by 1 and becomes 1.

After Snuke exercises for the second time, his power gets multiplied by 2 and becomes 2.

After Snuke exercises for the third time, his power gets multiplied by 3 and becomes 6.

Sample Input 2

10

Sample Output 2

3628800

Sample Input 3

100000

Sample Output 3

457992974

Print the answer modulo 10^{9}+7.


import java.util.Scanner;

public class Main {

	public static void main(String args[]){

		Scanner cin = new Scanner(System.in);
		long target = cin.nextLong();
		long tmp = 1L;

		for(long i=1L;i<=target;i++){
			tmp *=i;
			tmp %= (Math.pow(10, 9)+7);
		}

		System.out.println(tmp);
	}
}


import java.util.Scanner;

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

			long N = scan.nextLong();//s
			long M = scan.nextLong();//c

			if(2*N>M) {//sを全部使い切るためのcの個数がない
				System.out.println(M/2);
			}else {
				long kosuu = N;
				M-=2*N;
				kosuu+=M/4;
				System.out.println(kosuu);
			}

		}

	}

}

Score : 300 points

Problem Statement

Snuke loves puzzles.

Today, he is working on a puzzle using S- and c-shaped pieces.
In this puzzle, you can combine two c-shaped pieces into one S-shaped piece, as shown in the figure below:

Snuke decided to create as many Scc groups as possible by putting together one S-shaped piece and two c-shaped pieces.

Find the maximum number of Scc groups that can be created when Snuke has N S-shaped pieces and M c-shaped pieces.

Constraints

1 ≤ N,M ≤ 10^{12}

Input

The input is given from Standard Input in the following format:

N M

Output

Print the answer.

Sample Input 1

1 6

Sample Output 1

2

Two Scc groups can be created as follows:

Combine two c-shaped pieces into one S-shaped piece

Create two Scc groups, each from one S-shaped piece and two c-shaped pieces

Sample Input 2

12345 678901

Sample Output 2

175897


import java.util.*;

import static java.lang.System.*;

// https://atcoder.jp/contests/abc055/tasks/arc069_b
// 12:30-  ２つを固定すると4パターンしかないので全探索。O(n)
public class Main {

    static final char sheep = 'S';
    static final char wolf = 'W';

    static final char same = 'o';
    static final char diff = 'x';

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

        solver(N, statements);
    }

    public static void solver(int N, char[] statements) {

        char[] animals = new char[]{sheep, wolf};
        for (char a1 : animals) {
            for (char a2 : animals) {
                char[] ans = existPattern(a1, a2, N, statements);
                if (ans != null) {
                    out.println(String.valueOf(ans));
                    return;
                }
            }
        }
        out.println("-1");
    }

    // 与えれれた条件（1番目・2番目の動物、発言）から動物のパターンが存在するかチェックする
    // 存在する場合は、存在するパターンを返却する。なければNullを返却する
    public static char[] existPattern(char first_animal, char second_animal, int N, char[] statements){

        char[] ans = new char[N];
        ans[0] = first_animal;
        ans[1] = second_animal;

        char left_ani = first_animal;
        char center_ani = second_animal;
        char right_ani;

        // パターンを列挙
        for(int n=2; n<N; n++){
            char center_statement = statements[n-1];
            right_ani = rightAnimal(left_ani, center_ani, center_statement);
            ans[n] = right_ani;
            left_ani = center_ani;
            center_ani = right_ani;
        }

        //out.println(ans);

        // 1週回ったところで矛盾するかチェック
        // まだチェックしていない1番目と最後の動物の発言をチェック

        char last_before_animal = ans[N-2];
        char last_animal = ans[N-1];

        char first_statement = statements[0];
        char last_statement = statements[N-1];

        if (rightAnimal(last_animal, first_animal, first_statement) == second_animal &&
                rightAnimal(last_before_animal, last_animal, last_statement) == first_animal){
            return ans;
        }

        return null;
    }

    public static char rightAnimal(char left_ani, char center_ani, char center_statement){
        char right_ani;
        switch (center_ani) {
            case (sheep):
                switch (center_statement){
                    case (same):
                        right_ani = left_ani;
                        break;
                    default:
                        right_ani = diffAnimal(left_ani);
                }
                break;

            default:    // wolf
                switch (center_statement){
                    case(same):
                        right_ani = diffAnimal(left_ani);
                        break;
                    default:
                        right_ani = left_ani;
                }
        }
       return right_ani;
    }

    public static char diffAnimal(char animal){
        if(animal == sheep){
            return wolf;
        }
        return sheep;
    }
}

Score : 500 points

Problem Statement

Snuke, who loves animals, built a zoo.

There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle.
The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.

There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.

Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is o, the animal said that the two neighboring animals are of the same species, and if s_i is x, the animal said that the two neighboring animals are of different species.

More formally, a sheep answered o if the two neighboring animals are both sheep or both wolves, and answered x otherwise.
Similarly, a wolf answered x if the two neighboring animals are both sheep or both wolves, and answered o otherwise.

Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print -1.

Constraints

3 ≤ N ≤ 10^{5}

s is a string of length N consisting of o and x.

Input

The input is given from Standard Input in the following format:

N
s

Output

If there does not exist an valid assignment that is consistent with s, print -1.
Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.

t is a string of length N consisting of S and W.

If t_i is S, it indicates that the animal numbered i is a sheep. If t_i is W, it indicates that the animal numbered i is a wolf.

Sample Input 1

6
ooxoox

Sample Output 1

SSSWWS

For example, if the animals numbered 1, 2, 3, 4, 5 and 6 are respectively a sheep, sheep, sheep, wolf, wolf, and sheep, it is consistent with their responses. Besides, there is another valid assignment of species: a wolf, sheep, wolf, sheep, wolf and wolf.

Let us remind you: if the neiboring animals are of the same species, a sheep answers o and a wolf answers x. If the neiboring animals are of different species, a sheep answers x and a wolf answers o.

Sample Input 2

3
oox

Sample Output 2

-1

Print -1 if there is no valid assignment of species.

Sample Input 3

10
oxooxoxoox

Sample Output 3

SSWWSSSWWS


import java.util.Scanner;

public class Main {

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

		String s = sc.next();
		boolean[] o = new boolean[n];

		for(int i = 0; i < n; i++)
		{
			o[i] = s.charAt(i) == 'o';
		}

		int[] fill = new int[n]; //1 sheep 2 wolf
		for(int a = 1; a <= 2; a++)
		{
			for(int b = 1; b <= 2; b++)
			{
				fill[0] = a;
				fill[1] = b;
				//0: a, 1: b
//				System.out.println(a + " " + b);

				//assign last fill
				boolean same;
				if(fill[0]==2)same = !o[0];
				else same = o[0];
				if(same)fill[n-1] = b;
				else fill[n-1] = 3-b;
//				System.out.println("Assign last with " + fill[n-1]);

				for(int i = 2; i < n-1; i++)
				{ //fill spot i
					if(fill[i-1]==2)same = !o[i-1];
					else same = o[i-1];
					if(same)fill[i] = fill[i-2];

					else fill[i] = 3-fill[i-2];

//						System.out.println("Fill " + i + " with: " + fill[i]);
//						System.out.println("Deb " + a + " " + b);
//						System.out.println("Fill " + i + " with: " + (fill[i]==1?'S':'W'));
//						System.out.println("Reason: " + (fill[i-1]==2) + " xor " + o[i-1] + " makes " + same);
				}

				//check last claim to 0
				int mustbe;
				if(fill[n-1]==2)same = !o[n-1];
				else same = o[n-1];
				if(same)mustbe = fill[n-2];
				else mustbe = 3-(fill[n-2]);

				if(fill[0] != mustbe)
				{
//					System.out.println("LS ERROR: " + fill[n-2] + " and " + fill[0] + ", mustbe " + mustbe);
//					System.out.println("Cause " + fill[n-1] + ", " + o[n-1]);
					continue;
				}

				//reassign last fill with n-2
				if(fill[n-2]==2)same = !o[n-2];
				else same = o[n-2];
				if(same)mustbe = fill[n-3];
				else mustbe = 3-(fill[n-3]);

				if(fill[n-1] != mustbe)
				{
					continue;
				}
				else
				{
					StringBuilder sb = new StringBuilder();
					for(int i = 0; i < n; i++)
					{
						if(fill[i] == 1)sb.append('S');
						else if(fill[i] == 2 )sb.append('W');
						else System.out.println("ERRROR!");
					}
					System.out.println(sb);
					return;
				}

			}

		}
		System.out.println(-1);

	}

}


import java.util.Scanner;

class Solver {
	static final Solver INSTANCE = new Solver();

	void solve(Scanner sc) {
		int N = sc.nextInt();
		int M = sc.nextInt();
		String[] A = new String[N];
		String[] B = new String[M];
		for (int i = 0; i < N; i++) {
			A[i] = sc.next();
		}
		for (int i = 0; i < M; i++) {
			B[i] = sc.next();
		}
		for (int i = 0; i < N - M + 1; i++) {
			block:
			for (int index = A[i].indexOf(B[0]); index < N && index > 0; index = A[i].indexOf(B[0], index + 1)) {
				for (int j = 1; j < M; j++) {
					if (!A[i + j].substring(index).startsWith(B[j])) continue block;
				}
				System.out.println("Yes");
				return;
			}
		}
		System.out.println("No");
	}
}

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

		Solver.INSTANCE.solve(in);

		in.close();
	}
}

Score : 200 points

Problem Statement

You are given an image A composed of N rows and N columns of pixels, and a template image B composed of M rows and M columns of pixels.

A pixel is the smallest element of an image, and in this problem it is a square of size 1×1.

Also, the given images are binary images, and the color of each pixel is either white or black.

In the input, every pixel is represented by a character: . corresponds to a white pixel, and # corresponds to a black pixel.

The image A is given as N strings A_1,...,A_N.

The j-th character in the string A_i corresponds to the pixel at the i-th row and j-th column of the image A (1≦i,j≦N).

Similarly, the template image B is given as M strings B_1,...,B_M.

The j-th character in the string B_i corresponds to the pixel at the i-th row and j-th column of the template image B (1≦i,j≦M).

Determine whether the template image B is contained in the image A when only parallel shifts can be applied to the images.

Constraints

1≦M≦N≦50

A_i is a string of length N consisting of # and ..

B_i is a string of length M consisting of # and ..

Input

The input is given from Standard Input in the following format:

N M
A_1
A_2
:
A_N
B_1
B_2
:
B_M

Output

Print Yes if the template image B is contained in the image A. Print No otherwise.

Sample Input 1

3 2
#.#
.#.
#.#
#.
.#

Sample Output 1

Yes

The template image B is identical to the upper-left 2 × 2 subimage and the lower-right 2 × 2 subimage of A. Thus, the output should be Yes.

Sample Input 2

4 1
....
....
....
....
#

Sample Output 2

No

The template image B, composed of a black pixel, is not contained in the image A composed of white pixels.


import java.util.*;

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

        int n = sc.nextInt();
        int m = sc.nextInt();

        String[] stA = new String[n];
        String[] stB = new String[m];

        for (int i = 0; i < n; i++) {
            stA[i] = sc.next();
        }

        for (int i = 0; i < m; i++) {
            stB[i] = sc.next();
        }

        String ans = "No";

        loop1: for (int i = 0; i <= n - m; i++) {

            int index = -1;

            for (int j = 0; j < m; j++) {
                int mIndex = stA[i + j].indexOf(stB[j]);
                if (mIndex == -1) {
                    break;
                } else if (j == 0) {
                    index = mIndex;
                } else if (index == mIndex) {
                    if (j == m - 1) {
                        ans = "Yes";
                        break loop1;
                    }
                } else {
                    break;
                }
            }
        }
        System.out.println(ans);
    }
}


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

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

    private static void solve(Scanner in) {
        int N = in.nextInt(), M = in.nextInt();
        char[][] A = new char[N][N], B = new char[M][M];
        for (int i = 0; i < N; i++) {
            A[i] = in.next().toCharArray();
        }
        for (int j = 0; j < M; j++) {
            B[j] = in.next().toCharArray();
        }
        for (int h = 0; h < N - M + 1; h++) {
            for (int w = 0; w < N - M + 1; w++) {
                boolean ok = true;
                for (int i = 0; i < M; i++) {
                    for (int j = 0; j < M; j++) {
                        ok &= A[h + i][w + j] == B[i][j];
                    }
                }
                if (ok) {
                    System.out.println("Yes");
                    return;
                }
            }
        }
        System.out.println("No");
    }
}

class Scanner implements Closeable {
    private final InputStream stream;
    private final byte[] buf = new byte[1024];
    private int cur;
    private int num;

    Scanner(InputStream stream) {
        this.stream = stream;
    }

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

    int nextInt() {
        return (int) nextLong();
    }

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

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

    String next() {
        int c = read();
        while (isdel(c))
            c = read();
        StringBuilder s = new StringBuilder();
        do {
            s.appendCodePoint(c);
            c = read();
        } while (!isdel(c));
        return s.toString();
    }

    private int read() {
        if (num == -1)
            throw new InputMismatchException();
        if (cur >= num) {
            cur = 0;
            try {
                num = stream.read(buf);
            } catch (Exception e) {
                throw new InputMismatchException();
            }
            if (num <= 0)
                return -1;
        }
        return buf[cur++];
    }

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

    @Override
    public void close() {
        try {
            stream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}


import java.util.*;

public class Main {

    public static void main(String[] args) {
        // write your code here
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();
        int m = sc.nextInt();

        boolean[][] meiro = new boolean[n][n];

        for (int i = 0; i < m; i++) {
            int left = sc.nextInt() - 1;
            int right = sc.nextInt() - 1;
            meiro[left][right] = true;
            meiro[right][left] = true;
        }

        StringBuilder builder = new StringBuilder();

        for (int i = 1; i < n; i++) {
            builder.append(i);
        }

        String base = builder.toString();
        permutation(base, "");

        int count = 0;

        top : for (String target: list
             ) {
            String[] values = target.split("");
            int lastValue = 0;
            for (String value : values) {
                int start = lastValue;
                int end = Integer.parseInt(value);
                if (!meiro[start][end]) {
                    continue top;
                }
                lastValue = end;
            }
            count++;
        }

        System.out.println(count);
    }

    private static ArrayList<String> list = new ArrayList<>();

    private static void permutation(String q, String ans){
        // Base Case
        if(q.length() <= 1) {
            list.add(ans + q);
        }
        // General Case
        else {
            for (int i = 0; i < q.length(); i++) {
                permutation(q.substring(0, i) + q.substring(i + 1),
                        ans + q.charAt(i));
            }
        }
    }
}

Score : 300 points

Problem Statement

You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges.

Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).

How many different paths start from vertex 1 and visit all the vertices exactly once?

Here, the endpoints of a path are considered visited.

For example, let us assume that the following undirected graph shown in Figure 1 is given.

Figure 1: an example of an undirected graph

The following path shown in Figure 2 satisfies the condition.

Figure 2: an example of a path that satisfies the condition

However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices.

Figure 3: an example of a path that does not satisfy the condition

Neither the following path shown in Figure 4, because it does not start from vertex 1.

Figure 4: another example of a path that does not satisfy the condition

Constraints

2≦N≦8

0≦M≦N(N-1)/2

1≦a_i<b_i≦N

The given graph contains neither self-loops nor double edges.

Input

The input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once.

Sample Input 1

3 3
1 2
1 3
2 3

Sample Output 1

2

The given graph is shown in the following figure:

The following two paths satisfy the condition:

Sample Input 2

7 7
1 3
2 7
3 4
4 5
4 6
5 6
6 7

Sample Output 2

1

This test case is the same as the one described in the problem statement.


/*
* @Author Silviase(@silviasetitech)
* For ProCon
*/

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

class Main{

    static int n;
    static int m;
    static int ans;
    static int[] w;
    static int[] ww;
    static boolean[] visit;
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);

        n = sc.nextInt();
        m = sc.nextInt();
        w = new int[m];
        ww = new int[m];

        for (int i = 0; i < m; i++) {
            int tmp = sc.nextInt();
            int tmpp = sc.nextInt();
            w[i] = tmp-1;
            ww[i] = tmpp-1;
        }

        visit  = new boolean[n];
        Arrays.fill(visit, false);
        dfs(0);
        System.out.println(ans);
        sc.close();
    }

    public static void dfs(int placenow) {
        visit[placenow] = true;
        boolean success = true;
        for (int i = 0; i < n; i++) {
            if (visit[i] == false) { // not go all place
                success = false;
                break;
            }
        }
        if (success) {
            ans++;
            visit[placenow] = false;
            return;
        }

        for (int i = 0; i < m; i++) {
            if (w[i] == placenow && visit[ww[i]] == false ) {
                dfs(ww[i]);
            }else if(ww[i] == placenow && visit[w[i]] == false){
                dfs(w[i]);
            }else{
                continue;
            }
        }
        visit[placenow] = false;
        return;
    }

}