import java.util.HashMap;
import java.util.Scanner;

public class Main {

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

		int n = s.nextInt();

		int[] num = new int[n];
		int[] dp = new int[n];
		int st = 0, dr = 0;
		for (int i = 0; i < n; i++) {
			num[i] = s.nextInt();
		}
		int l = s.nextInt();
		int q = s.nextInt();

		while (dr != dp.length) {
			if (num[dr] - num[st] <= l) {
				dp[st] = dr;
				dr++;
			} else {
				if (dp[st] == 0 && st != 0)
					dp[st] = dp[st - 1];
				st++;
			}

		}
		HashMap<Integer, Integer> h = new HashMap<>();
		HashMap<Integer, Integer> h1 = new HashMap<>();
		while (st < dp.length) {
			dp[st] = dp.length - 1;
			st++;
		}
		int par = 0;
		int index = 1;
		int[] rau = new int[dp.length];
		int[] freq = new int[dp.length];
		rau[rau.length - 1] = 1;
		int apar;
		for (int i = 0; i < dp.length; i++) {
			if (rau[i] == 0) {
				par = i;
				apar = 1;
				while (par < dp.length && rau[par] == 0||par==dp.length-1 &&freq[par]==0) {
					rau[par] = index;
					if (freq[par] == 0)
						freq[par] = apar;
					par = dp[par];

					apar++;
					if (par == dp.length - 1 && freq[par] != 0) break;
				}
				h.put(index, apar);
				h1.put(index, par);
				index++;
			}
		}
	/*	for (int i : rau) {
			System.out.print(i);
		}
		System.out.println();
		for (int i : freq) {
			System.out.print(i);
		}*/
		for (int i = 0; i < q; i++) {
			int a = s.nextInt() - 1;
			int b = s.nextInt() - 1;
			if (a > b) {
				a = a ^ b;
				b = a ^ b;
				a = a ^ b;
			}
			//System.out.println(f(dp, a - 1, b - 1));
			int cur = rau[a];
			int res = 0;
			int dest = rau[b];
			//System.out.println(rau[b]+" "+rau[a]);
			res -= freq[a];
			int last = 0;

			while (cur != dest) {
				res += h.get(cur) - last;
				last = freq[h1.get(cur)];
				cur = rau[h1.get(cur)];

				//System.out.println(last);

			}
			//System.out.println(last);
			res += freq[b] - last;
			System.out.println(res);
		}

	}

	public static int f(int[] dp, int a, int b) {

		int cost = 0;
		if (a > b) {
			a = a ^ b;
			b = a ^ b;
			a = a ^ b;

		}
		int current = a;
		while (current < b) {
			current = dp[current];
			cost++;
		}
		return cost;

	}
}

Score : 700 points

Problem Statement

N hotels are located on a straight line. The coordinate of the i-th hotel (1 \leq i \leq N) is x_i.

Tak the traveler has the following two personal principles:

He never travels a distance of more than L in a single day.

He never sleeps in the open. That is, he must stay at a hotel at the end of a day.

You are given Q queries. The j-th (1 \leq j \leq Q) query is described by two distinct integers a_j and b_j.
For each query, find the minimum number of days that Tak needs to travel from the a_j-th hotel to the b_j-th hotel following his principles.
It is guaranteed that he can always travel from the a_j-th hotel to the b_j-th hotel, in any given input.

Constraints

2 \leq N \leq 10^5

1 \leq L \leq 10^9

1 \leq Q \leq 10^5

1 \leq x_i < x_2 < ... < x_N \leq 10^9

x_{i+1} - x_i \leq L

1 \leq a_j,b_j \leq N

a_j \neq b_j

N,\,L,\,Q,\,x_i,\,a_j,\,b_j are integers.

Partial Score

200 points will be awarded for passing the test set satisfying N \leq 10^3 and Q \leq 10^3.

Input

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

N
x_1 x_2 ... x_N
L
Q
a_1 b_1
a_2 b_2
:
a_Q b_Q

Output

Print Q lines.
The j-th line (1 \leq j \leq Q) should contain the minimum number of days that Tak needs to travel from the a_j-th hotel to the b_j-th hotel.

Sample Input 1

9
1 3 6 13 15 18 19 29 31
10
4
1 8
7 3
6 7
8 5

Sample Output 1

4
2
1
2

For the 1-st query, he can travel from the 1-st hotel to the 8-th hotel in 4 days, as follows:

Day 1: Travel from the 1-st hotel to the 2-nd hotel. The distance traveled is 2.

Day 2: Travel from the 2-nd hotel to the 4-th hotel. The distance traveled is 10.

Day 3: Travel from the 4-th hotel to the 7-th hotel. The distance traveled is 6.

Day 4: Travel from the 7-th hotel to the 8-th hotel. The distance traveled is 10.


import java.util.*;

public class Main{
    void solve(){
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int[] a = new int[n];
        for(int i = 0; i < n; i++) a[i] = scan.nextInt();
        int out = Integer.MAX_VALUE;
        for(int i = -100; i <= 100; i++){
            int r = 0;
            for(int j = 0; j < n; j++) r += (int)(Math.pow(a[j] - i, 2));
            out = Math.min(out, r);
        }
        System.out.println(out);
    }

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

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

Score : 200 points

Problem Statement

Evi has N integers a_1,a_2,..,a_N. His objective is to have N equal integers by transforming some of them.

He may transform each integer at most once. Transforming an integer x into another integer y costs him (x-y)^2 dollars. Even if a_i=a_j (i≠j), he has to pay the cost separately for transforming each of them (See Sample 2).

Find the minimum total cost to achieve his objective.

Constraints

1≦N≦100

-100≦a_i≦100

Input

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

N
a_1 a_2 ... a_N

Output

Print the minimum total cost to achieve Evi's objective.

Sample Input 1

2
4 8

Sample Output 1

8

Transforming the both into 6s will cost (4-6)^2+(8-6)^2=8 dollars, which is the minimum.

Sample Input 2

3
1 1 3

Sample Output 2

3

Transforming the all into 2s will cost (1-2)^2+(1-2)^2+(3-2)^2=3 dollars. Note that Evi has to pay (1-2)^2 dollar separately for transforming each of the two 1s.

Sample Input 3

3
4 2 5

Sample Output 3

5

Leaving the 4 as it is and transforming the 2 and the 5 into 4s will achieve the total cost of (2-4)^2+(5-4)^2=5 dollars, which is the minimum.

Sample Input 4

4
-100 -100 -100 -100

Sample Output 4

0

Without transforming anything, Evi's objective is already achieved. Thus, the necessary cost is 0.

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.io.*;
import java.util.*;

public class Main {
    public static final long mod = (long)1e9+7;
    public static final long INF = Long.MAX_VALUE/2;
    public static final int inf = Integer.MAX_VALUE/2;
    //arc59 d
    static void solve(InputReader in, PrintWriter out){
        char[] s = in.ns().toCharArray();
        int ans = -1;
        boolean flag = false;
        for (int i = 0; i < s.length-1; i++) {
            if(i<s.length-2){
                if(s[i]==s[i+1]||s[i]==s[i+2]){
                    out.printf("%d %d\n",i+1, i+3);
                    flag = true;
                    break;
                }
            }else{
                if(s[i]==s[i+1]){
                    out.printf("%d %d\n",i+1, i+2);
                    flag = true;
                    break;
                }
            }
        }
        if(!flag) out.println("-1 -1");
    }

    public static void main(String[] args){
        InputReader in = new InputReader(System.in);
        PrintWriter out = new PrintWriter(System.out);
        solve(in, out);
        out.close();
    }
    public static class InputReader{
        private BufferedReader br;
        private StringTokenizer st;
        public InputReader(InputStream is){
            br = new BufferedReader(new InputStreamReader(is));
            st = null;
        }
        public String ns(){
            if(st == null || !st.hasMoreTokens()){
                try{
                    st = new StringTokenizer(br.readLine());
                }catch (Exception e){
                    throw new RuntimeException(e);
                }
            }
            return st.nextToken();
        }
        public int ni(){
            return Integer.parseInt(ns());
        }
        public long nl(){
            return Long.parseLong(ns());
        }
        public double nd(){
            return Double.parseDouble(ns());
        }
        public char nc(){
            return ns().toCharArray()[0];
        }
        public int[] ni(int n){
            int[] a = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = ni();
            }
            return a;
        }
        public long[] nl(int n){
            long[] a = new long[n];
            for (int i = 0; i < n; i++) {
                a[i] = nl();
            }
            return a;
        }
        public double[] nd(int n){
            double[] a = new double[n];
            for (int i = 0; i < n; i++) {
                a[i] = nd();
            }
            return a;
        }
    }
}

Score : 400 points

Problem Statement

Given a string t, we will call it unbalanced if and only if the length of t is at least 2, and more than half of the letters in t are the same. For example, both voodoo and melee are unbalanced, while neither noon nor a is.

You are given a string s consisting of lowercase letters. Determine if there exists a (contiguous) substring of s that is unbalanced. If the answer is positive, show a position where such a substring occurs in s.

Constraints

2 ≦ |s| ≦ 10^5

s consists of lowercase letters.

Partial Score

200 points will be awarded for passing the test set satisfying 2 ≦ N ≦ 100.

Input

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

s

Output

If there exists no unbalanced substring of s, print -1 -1.

If there exists an unbalanced substring of s, let one such substring be s_a s_{a+1} ... s_{b} (1 ≦ a < b ≦ |s|), and print a b. If there exists more than one such substring, any of them will be accepted.

Sample Input 1

needed

Sample Output 1

2 5

The string s_2 s_3 s_4 s_5 = eede is unbalanced. There are also other unbalanced substrings. For example, the output 2 6 will also be accepted.

Sample Input 2

atcoder

Sample Output 2

-1 -1

The string atcoder contains no unbalanced substring.


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

public class Main {

    public static void main(String[] args) {
        Solver solver = new Solver();
    }

    static class Solver {
        IO io;

        public Solver() {
            this.io = new IO();
            try {
                io.println(solve());
            } finally {
                io.close();
            }
        }

        /****************************** START READING HERE ********************************/

        String solve() {
            String s = io.next();
            for (int i=1; i<s.length(); i++) {
                if (s.charAt(i) == s.charAt(i-1)) return i + " " + (i+1);
            }
            int[] count = new int[1000];
            int left = 0;
            int right = 0;
            while (right < s.length()) {
                char c = s.charAt(right++);
                count[c]++;
                if (right - left > 3) {
                    char other = s.charAt(left++);
                    count[other]--;
                }
                if (count[c] >= 2) return (left+1) + " " + right;
            }

            return "-1 -1";
        }

        /************************** UTILITY CODE BELOW THIS LINE **************************/

        class Point {
            int y;
            int x;

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

        class IDval implements Comparable<IDval> {
            int id;
            long val;

            public IDval(int id, long val) {
                this.val = val;
                this.id = id;
            }

            @Override
            public int compareTo(IDval o) {
                if (this.val < o.val) return -1;
                if (this.val > o.val) return 1;
                return this.id - o.id;
            }
        }

        private List<Integer>[] toGraph(IO io, int n) {
            List<Integer>[] g = new ArrayList[n+1];
            for (int i=1; i<=n; i++) g[i] = new ArrayList<>();
            for (int i=1; i<=n-1; i++) {
                int a = io.nextInt();
                int b = io.nextInt();
                g[a].add(b);
                g[b].add(a);
            }
            return g;
        }

        private class IO extends PrintWriter {
            private InputStreamReader r;
            private static final int BUFSIZE = 1 << 15;
            private char[] buf;
            private int bufc;
            private int bufi;
            private StringBuilder sb;

            public IO() {
                super(new BufferedOutputStream(System.out));
                r = new InputStreamReader(System.in);

                buf = new char[BUFSIZE];
                bufc = 0;
                bufi = 0;
                sb = new StringBuilder();
            }

            private void fillBuf() throws IOException {
                bufi = 0;
                bufc = 0;
                while(bufc == 0) {
                    bufc = r.read(buf, 0, BUFSIZE);
                    if(bufc == -1) {
                        bufc = 0;
                        return;
                    }
                }
            }

            private boolean pumpBuf() throws IOException {
                if(bufi == bufc) {
                    fillBuf();
                }
                return bufc != 0;
            }

            private boolean isDelimiter(char c) {
                return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
            }

            private void eatDelimiters() throws IOException {
                while(true) {
                    if(bufi == bufc) {
                        fillBuf();
                        if(bufc == 0) throw new RuntimeException("IO: Out of input.");
                    }

                    if(!isDelimiter(buf[bufi])) break;
                    ++bufi;
                }
            }

            public String next() {
                try {
                    sb.setLength(0);

                    eatDelimiters();
                    int start = bufi;

                    while(true) {
                        if(bufi == bufc) {
                            sb.append(buf, start, bufi - start);
                            fillBuf();
                            start = 0;
                            if(bufc == 0) break;
                        }

                        if(isDelimiter(buf[bufi])) break;
                        ++bufi;
                    }

                    sb.append(buf, start, bufi - start);

                    return sb.toString();
                } catch(IOException e) {
                    throw new RuntimeException("IO.next: Caught IOException.");
                }
            }

            public int nextInt() {
                try {
                    int ret = 0;

                    eatDelimiters();

                    boolean positive = true;
                    if(buf[bufi] == '-') {
                        ++bufi;
                        if(!pumpBuf()) throw new RuntimeException("IO.nextInt: Invalid int.");
                        positive = false;
                    }

                    boolean first = true;
                    while(true) {
                        if(!pumpBuf()) break;
                        if(isDelimiter(buf[bufi])) {
                            if(first) throw new RuntimeException("IO.nextInt: Invalid int.");
                            break;
                        }
                        first = false;

                        if(buf[bufi] >= '0' && buf[bufi] <= '9') {
                            if(ret < -214748364) throw new RuntimeException("IO.nextInt: Invalid int.");
                            ret *= 10;
                            ret -= (int)(buf[bufi] - '0');
                            if(ret > 0) throw new RuntimeException("IO.nextInt: Invalid int.");
                        } else {
                            throw new RuntimeException("IO.nextInt: Invalid int.");
                        }

                        ++bufi;
                    }

                    if(positive) {
                        if(ret == -2147483648) throw new RuntimeException("IO.nextInt: Invalid int.");
                        ret = -ret;
                    }

                    return ret;
                } catch(IOException e) {
                    throw new RuntimeException("IO.nextInt: Caught IOException.");
                }
            }

            public long nextLong() {
                try {
                    long ret = 0;

                    eatDelimiters();

                    boolean positive = true;
                    if(buf[bufi] == '-') {
                        ++bufi;
                        if(!pumpBuf()) throw new RuntimeException("IO.nextLong: Invalid long.");
                        positive = false;
                    }

                    boolean first = true;
                    while(true) {
                        if(!pumpBuf()) break;
                        if(isDelimiter(buf[bufi])) {
                            if(first) throw new RuntimeException("IO.nextLong: Invalid long.");
                            break;
                        }
                        first = false;

                        if(buf[bufi] >= '0' && buf[bufi] <= '9') {
                            if(ret < -922337203685477580L) throw new RuntimeException("IO.nextLong: Invalid long.");
                            ret *= 10;
                            ret -= (long)(buf[bufi] - '0');
                            if(ret > 0) throw new RuntimeException("IO.nextLong: Invalid long.");
                        } else {
                            throw new RuntimeException("IO.nextLong: Invalid long.");
                        }

                        ++bufi;
                    }

                    if(positive) {
                        if(ret == -9223372036854775808L) throw new RuntimeException("IO.nextLong: Invalid long.");
                        ret = -ret;
                    }

                    return ret;
                } catch(IOException e) {
                    throw new RuntimeException("IO.nextLong: Caught IOException.");
                }
            }

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

        }
    }

}


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

   int N=sc.nextInt();
   int sum=0;
   for(int i=1; i<=N; i++){
     sum+=i;
   }
   System.out.println(sum);
 }
}

Score : 100 points

Problem Statement

There are N children in AtCoder Kindergarten. Mr. Evi will arrange the children in a line, then give 1 candy to the first child in the line, 2 candies to the second child, ..., N candies to the N-th child. How many candies will be necessary in total?

Constraints

1≦N≦100

Input

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

N

Output

Print the necessary number of candies in total.

Sample Input 1

3

Sample Output 1

6

The answer is 1+2+3=6.

Sample Input 2

10

Sample Output 2

55

The sum of the integers from 1 to 10 is 55.

Sample Input 3

1

Sample Output 3

1

Only one child. The answer is 1 in this case.


import java.util.Scanner;

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

		System.out.println(N*(N+1)/2);

		scanner.close();
	}
}


import java.util.*;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Set;

public class Main{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        int N=sc.nextInt();
        int sum=0;
        for(int i=0;i<=N;i++){
            sum+=i;
        }
        System.out.println(sum);

}

    }


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

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

class AC043C {}

class Main {
    public static void main(String[] args) throws IOException {
        int n = ri(), a[] = ria(n);
        long min = LMAX;
        for(int i = -101; i < 101; ++i) {
            int x = 0;
            for(int aa : a) x += (long) (i - aa) * (i - aa);
            min = min(min, x);
        }
        prln(min);
        close();
    }

    static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
    static StringTokenizer input;

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


import java.util.*;

public class Main {

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

        int a = sc.nextInt();
        int b = sc.nextInt();

        if (a == 0 || b == 0) {
            System.out.println("Zero");
            return;
        }

        if (a > 0) {
            System.out.println(b > 0 ? "Positive" : "Zero");
        } else {
            if (b > 0) {
                System.out.println( "Zero");
            } else {
                System.out.println(Math.abs(a - b) % 2 == 1 ? "Positive" : "Negative");
            }
        }
    }
}

Problem Statement

You are given two integers a and b (a≤b). Determine if the product of the integers a, a+1, …, b is positive, negative or zero.

Constraints

a and b are integers.

-10^9≤a≤b≤10^9

Partial Score

In test cases worth 100 points, -10≤a≤b≤10.

Input

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

a b

Output

If the product is positive, print Positive. If it is negative, print Negative. If it is zero, print Zero.

Sample Input 1

1 3

Sample Output 1

Positive

1×2×3=6 is positive.

Sample Input 2

-3 -1

Sample Output 2

Negative

(-3)×(-2)×(-1)=-6 is negative.

Sample Input 3

-1 1

Sample Output 3

Zero

(-1)×0×1=0.


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;

public class Main {
	InputStream is;

	int __t__ = 1;
	int __f__ = 0;
	int __FILE_DEBUG_FLAG__ = __f__;
	String __DEBUG_FILE_NAME__ = "src/D1";

	FastScanner in;
	PrintWriter out;

	public void solve() {
		int a = in.nextInt();
		int b = in.nextInt();

		if (a == 0 || b == 0 || (a < 0 && b > 0)) {
			System.out.println("Zero");
			return;
		} else if (a > 0 || (b - a + 1) % 2 == 0) {
			System.out.println("Positive");
			return;
		} else {
			System.out.println("Negative");
		}

	}

	public void run() {
		if (__FILE_DEBUG_FLAG__ == __t__) {
			try {
				is = new FileInputStream(__DEBUG_FILE_NAME__);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			System.out.println("FILE_INPUT!");
		} else {
			is = System.in;
		}
		in = new FastScanner(is);
		out = new PrintWriter(System.out);

		solve();
	}

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

	public void mapDebug(int[][] a) {
		System.out.println("--------map display---------");

		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < a[i].length; j++) {
				System.out.printf("%3d ", a[i][j]);
			}
			System.out.println();
		}

		System.out.println("----------------------------");
		System.out.println();
	}

	public void debug(Object... obj) {
		System.out.println(Arrays.deepToString(obj));
	}

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

		public FastScanner(InputStream stream) {
			this.stream = stream;
			//stream = new FileInputStream(new File("dec.in"));

		}

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

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

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

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

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

			return array;
		}

		int[][] nextIntMap(int n, int m) {
			int[][] map = new int[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextIntArray(m);
			}
			return map;
		}

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

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

			return array;
		}

		long[][] nextLongMap(int n, int m) {
			long[][] map = new long[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextLongArray(m);
			}
			return map;
		}

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

		double[] nextDoubleArray(int n) {
			double[] array = new double[n];
			for (int i = 0; i < n; i++)
				array[i] = nextDouble();

			return array;
		}

		double[][] nextDoubleMap(int n, int m) {
			double[][] map = new double[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextDoubleArray(m);
			}
			return map;
		}

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

		String[] nextStringArray(int n) {
			String[] array = new String[n];
			for (int i = 0; i < n; i++)
				array[i] = next();

			return array;
		}

		String nextLine() {
			int c = read();
			while (isEndline(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndline(c));
			return res.toString();
		}
	}
}


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 x = 0;
		int y = 0;

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

		boolean[] red = new boolean[n];
		red[0] = true;

		for (int i = 0; i < m; i++) {
			x = Integer.parseInt(sc.next()) - 1;
			y = Integer.parseInt(sc.next()) - 1;

			if (red[x]) {
				red[y] = true;
			}
			balls[x]--;
			balls[y]++;

			if (balls[x] == 0) {
				red[x] = false;
			}
		}
		int ans = 0;

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

		System.out.println(ans);
	}

}

Problem Statement

We have N boxes, numbered 1 through N. At first, box 1 contains one red ball, and each of the other boxes contains one white ball.

Snuke will perform the following M operations, one by one. In the i-th operation, he randomly picks one ball from box x_i, then he puts it into box y_i.

Find the number of boxes that may contain the red ball after all operations are performed.

Constraints

2≤N≤10^5

1≤M≤10^5

1≤x_i,y_i≤N

x_i≠y_i

Just before the i-th operation is performed, box x_i contains at least 1 ball.

Input

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

N M
x_1 y_1
:
x_M y_M

Output

Print the number of boxes that may contain the red ball after all operations are performed.

Sample Input 1

3 2
1 2
2 3

Sample Output 1

2

Just after the first operation, box 1 is empty, box 2 contains one red ball and one white ball, and box 3 contains one white ball.

Now, consider the second operation. If Snuke picks the red ball from box 2, the red ball will go into box 3. If he picks the white ball instead, the red ball will stay in box 2.
Thus, the number of boxes that may contain the red ball after all operations, is 2.

Sample Input 2

3 3
1 2
2 3
2 3

Sample Output 2

1

All balls will go into box 3.

Sample Input 3

4 4
1 2
2 3
4 1
3 4

Sample Output 3

3


import java.util.Scanner;

class Main {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int m = in.nextInt();
		int[] box = new int[n];
		boolean[] boxred = new boolean[n];

		boxred[0] = true;
		for (int i = 1; i < n; i++) {
			boxred[i] = false;
		}
		for (int i = 0; i < n; i++) {
			box[i] = 1;
		}

		for (int i = 0; i < m; i++) {
			int x = in.nextInt()-1;
			int y = in.nextInt()-1;
			if(boxred[x] == true){
				if(box[x] == 1){
					boxred[x] = false;
					boxred[y] = true;
				}else{
					boxred[y] = true;
				}
			}
			box[x]--;
			box[y]++;
		}
		int ans = 0;
		for (int i = 0; i < n; i++) {
			if(boxred[i] == true){
				ans++;
			}
		}
		System.out.println(ans);
		in.close();
	}

}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.TreeMap;

public class Main {
	public static void main(String[] args) throws Exception{
		String answerText = "Possible";
		ArrayList<Integer> answerList = new ArrayList<Integer>();
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] array;
		array = br.readLine().split(" ");
		int n = Integer.parseInt(array[0]);//ロープの本数
		int l = Integer.parseInt(array[1]);//長さL
		TreeMap<Integer,Integer> map = new TreeMap<Integer,Integer>();

		int cnt = 0;
		for(String str:br.readLine().split(" ")){
			map.put(cnt, Integer.parseInt(str));
			cnt++;
		}

		int total = getLength(map);

		while(true){
			if(map.size() == 1){
				break;
			}
			if(total >= l){
				int first = map.firstKey();
				int last = map.lastKey();
				if(map.get(first) < map.get(last)){
					total -= map.get(first);
					answerList.add(first+1);
					map.remove(first);
				}else{
					total -= map.get(last);
					answerList.add(last);
					map.remove(last);
				}
			}else{
				answerText = "Impossible";
				break;
			}
		}
		System.out.println(answerText);
		for(Integer i:answerList){
			System.out.println(String.valueOf(i));
		}
	}

	private static Integer getLength(TreeMap<Integer,Integer> map){
		int ret = 0;

		for(int i:map.values()){
			ret += i;
		}
		return ret;
	}
}

Problem Statement

We have N pieces of ropes, numbered 1 through N. The length of piece i is a_i.

At first, for each i (1≤i≤N-1), piece i and piece i+1 are tied at the ends, forming one long rope with N-1 knots. Snuke will try to untie all of the knots by performing the following operation repeatedly:

Choose a (connected) rope with a total length of at least L, then untie one of its knots.

Is it possible to untie all of the N-1 knots by properly applying this operation? If the answer is positive, find one possible order to untie the knots.

Constraints

2≤N≤10^5

1≤L≤10^9

1≤a_i≤10^9

All input values are integers.

Input

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

N L
a_1 a_2 ... a_n

Output

If it is not possible to untie all of the N-1 knots, print Impossible.

If it is possible to untie all of the knots, print Possible, then print another N-1 lines that describe a possible order to untie the knots. The j-th of those N-1 lines should contain the index of the knot that is untied in the j-th operation. Here, the index of the knot connecting piece i and piece i+1 is i.

If there is more than one solution, output any.

Sample Input 1

3 50
30 20 10

Sample Output 1

Possible
2
1

If the knot 1 is untied first, the knot 2 will become impossible to untie.

Sample Input 2

2 21
10 10

Sample Output 2

Impossible

Sample Input 3

5 50
10 20 30 40 50

Sample Output 3

Possible
1
2
3
4

Another example of a possible solution is 3, 4, 1, 2.


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

public class Main {

	public static void main(String[] args) {
		new Main().solve();
	}
	int MAX=1000002;

	void solve(){
		Scanner sc=new Scanner(System.in);
		int N=sc.nextInt();
		int L=sc.nextInt();
		int[]a=new int[N];
		for(int i=0;i<N;i++) {
			a[i]=sc.nextInt();
		}
		int last=-1;
		for(int i=0;i<N-1;i++) {
			if(a[i]+a[i+1]>=L) {
				last=i;
				break;
			}
		}
		if(last==-1) {
			System.out.println("Impossible");
			return;
		}else {
			System.out.println("Possible");
			for(int i=0;i<last;i++) {
				System.out.println(i+1);
			}
			for(int i=N-1;i>last+1;i--) {
				System.out.println(i);
			}
			System.out.println(last+1);
		}
	}
}


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import java.util.StringTokenizer;

public class Main {
	static int x, y, z;
	static Stack<Integer> stack = new Stack<Integer>();
	static ArrayList<String> list = new ArrayList<String>();
	static ArrayList<String> seq = new ArrayList<String>();

	static void rec() {
		list = new ArrayList<String>();
		go(0, x);
		ArrayList<String> fives = new ArrayList<String>();
		for (String s : list)
			fives.add(s);
		list = new ArrayList<String>();
		go(0, y);
		ArrayList<String> sevens = new ArrayList<String>();
		for (String s : list)
			sevens.add(s);
		list = new ArrayList<String>();
		go(0, z);
		for (String s : fives) {
			for (String s2 : sevens) {
				for (String s3 : list) {
					seq.add(s + s2 + s3);
				}
			}
		}
	}

	static void go(int curr, int limit) {
		if (curr > limit)
			return;
		if (curr == limit) {
			String s = "";
			for (int x : stack) {
				s += x;
			}
			list.add(s);
			return;
		}
		for (int i = 1; i <= limit; i++) {
			stack.push(i);
			go(curr + i, limit);
			stack.pop();
		}
	}

	static class Node {
		int id;
		Node fail;
		Node[] child;
		boolean isTerminal;
		boolean[] chars;

		public Node() {
			child = new Node[10];
			chars = new boolean[10];
			id = -1;
		}

		void insert(String str, int index, int charIndex) {
			if (charIndex == str.length())
				isTerminal = true;
			else {
				if (child[str.charAt(charIndex) - '0'] == null) {
					child[str.charAt(charIndex) - '0'] = new Node();
					chars[str.charAt(charIndex) - '0'] = true;
				}
				child[str.charAt(charIndex) - '0'].insert(str, index,
						charIndex + 1);
			}
		}
	}

	static Node build(ArrayList<String> words) {
		Node root = new Node();
		for (int i = 0; i < words.size(); i++)
			root.insert(words.get(i), i, 0);
		Queue<Node> q = new LinkedList<Node>();
		for (int i = 0; i < 10; i++) {
			if (root.child[i] == null)
				root.child[i] = root;
			else {
				q.add(root.child[i]);
				root.child[i].fail = root;
			}
		}
		while (!q.isEmpty()) {
			Node front = q.remove();
			for (int i = 0; i < 10; i++) {
				if (!front.chars[i])
					continue;
				q.add(front.child[i]);
				Node temp = front.fail;
				while (temp.child[i] == null)
					temp = temp.fail;
				temp = temp.child[i];
				front.child[i].fail = temp;
				front.child[i].isTerminal |= temp.isTerminal;
			}
		}
		return root;
	}

	public static void dfs(Node n) {
		if (n.id != -1)
			return;
		n.id = id;
		nodes[id++] = n;
		for (int i = 0; i < 10; i++)
			if (n.chars[i]) {
				dfs(n.child[i]);
			}
	}

	static int id, n;
	static Node[] nodes = new Node[50000];
	static Integer[][][] dp = new Integer[40][50000][2];
	static int mod = 1000000007;

	public static int go(int index, int nodeId, int flag) {
		if (index == n) {
			return flag == 1 ? 1 : 0;
		}
		if (dp[index][nodeId][flag] != null)
			return dp[index][nodeId][flag];
		int res = 0;
		for (char c = '0'; c <= '9'; c++) {
			Node n = nodes[nodeId];
			while (n.child[c-'0'] == null)
				n = n.fail;
			n = n.child[c-'0'];
			res += go(index + 1, n.id, flag | (n.isTerminal ? 1 : 0));
			res %= mod;
		}
		return dp[index][nodeId][flag] = res;
	}

	public static void main(String[] args) {
		InputReader r = new InputReader(System.in);
		n = r.nextInt();
		x = r.nextInt();
		y = r.nextInt();
		z = r.nextInt();
		rec();
		Node root = build(seq);
		dfs(root);
		System.out.println(go(0, 0, 0));
	}

	static class InputReader {
		private BufferedReader reader;
		private StringTokenizer tokenizer;

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

		public InputReader(FileReader stream) {
			reader = new BufferedReader(stream);
			tokenizer = null;
		}

		public String nextLine() {
			try {
				return reader.readLine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}

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

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

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

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

Score : 700 points

Problem Statement

Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order.

Iroha is looking for X,Y,Z-Haiku (defined below) in integer sequences.

Consider all integer sequences of length N whose elements are between 1 and 10, inclusive. Out of those 10^N sequences, how many contain an X,Y,Z-Haiku?

Here, an integer sequence a_0, a_1, ..., a_{N-1} is said to contain an X,Y,Z-Haiku if and only if there exist four indices x, y, z, w (0 ≦ x < y < z < w ≦ N) such that all of the following are satisfied:

a_x + a_{x+1} + ... + a_{y-1} = X

a_y + a_{y+1} + ... + a_{z-1} = Y

a_z + a_{z+1} + ... + a_{w-1} = Z

Since the answer can be extremely large, print the number modulo 10^9+7.

Constraints

3 ≦ N ≦ 40

1 ≦ X ≦ 5

1 ≦ Y ≦ 7

1 ≦ Z ≦ 5

Input

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

N X Y Z

Output

Print the number of the sequences that contain an X,Y,Z-Haiku, modulo 10^9+7.

Sample Input 1

3 5 7 5

Sample Output 1

1

Here, the only sequence that contains a 5,7,5-Haiku is [5, 7, 5].

Sample Input 2

4 5 7 5

Sample Output 2

34

Sample Input 3

37 4 2 3

Sample Output 3

863912418

Sample Input 4

40 5 7 5

Sample Output 4

562805100


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        // Your code here!
       Scanner sc = new Scanner(System.in);
       int a = sc.nextInt();
       int b = sc.nextInt();
       int c = sc.nextInt();
       if((a == 5 && b == 7 && c == 5) || (a == 7 && b == 5 && c == 5) || (a == 5 && b == 5 && c == 7)){
           System.out.println("YES");
       }else{
           System.out.println("NG");
       }
    }
}

Score : 100 points

Problem Statement

Iroha loves Haiku. Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order.

To create a Haiku, Iroha has come up with three different phrases. These phrases have A, B and C syllables, respectively. Determine whether she can construct a Haiku by using each of the phrases once, in some order.

Constraints

1≦A,B,C≦10

Input

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

A B C

Output

If it is possible to construct a Haiku by using each of the phrases once, print YES (case-sensitive). Otherwise, print NO.

Sample Input 1

5 5 7

Sample Output 1

YES

Using three phrases of length 5, 5 and 7, it is possible to construct a Haiku.

Sample Input 2

7 7 5

Sample Output 2

NO


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.nio.charset.Charset;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;

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

    static class CIrohasObsession {
        public void solve(int testNumber, LightScanner in, LightWriter out) {
            // out.setBoolLabel(LightWriter.BoolLabel.YES_NO_FIRST_UP);
            int n = in.ints();
            int k = in.ints();
            boolean[] d = new boolean[10];
            for (int i = 0; i < k; i++) {
                d[in.ints()] = true;
            }

            outer:
            for (int i = n; ; i++) {
                int t = i;
                while (t > 0) {
                    if (d[t % 10]) {
                        continue outer;
                    }
                    t /= 10;
                }
                out.ansln(i);
                return;
            }
        }

    }

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

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

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

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

    }

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

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

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

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

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

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

        public LightWriter ans(int i) {
            return ans(Integer.toString(i));
        }

        public LightWriter ansln(int... n) {
            for (int n1 : n) {
                ans(n1).ln();
            }
            return this;
        }

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

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

    }
}

Score : 300 points

Problem Statement

Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K.

She is shopping, and now paying at the cashier.
Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change).

However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money.

Find the amount of money that she will hand to the cashier.

Constraints

1 ≦ N < 10000

1 ≦ K < 10

0 ≦ D_1 < D_2 < … < D_K≦9

\{D_1,D_2,...,D_K\} ≠ \{1,2,3,4,5,6,7,8,9\}

Input

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

N K
D_1 D_2 … D_K

Output

Print the amount of money that Iroha will hand to the cashier.

Sample Input 1

1000 8
1 3 4 5 6 7 8 9

Sample Output 1

2000

She dislikes all digits except 0 and 2.

The smallest integer equal to or greater than N=1000 whose decimal notation contains only 0 and 2, is 2000.

Sample Input 2

9999 1
0

Sample Output 2

9999


import java.util.*;
public class Main{
public static void main(String[] args){
Scanner in=new Scanner(System.in);
long n=in.nextLong();
long x=in.nextLong();
long a,b,ans;
a=x;b=n-x;
ans=a+b;
if(a<b){
long temp;
temp=b;
b=a;
a=temp;
}
while(b!=0){
ans+=(a/b)*2*b;
a=a%b;
if(a<b){
long temp;
temp=b;
b=a;
a=temp;
}}
ans-=a;
System.out.println(ans);
}
}

Score : 500 points

Problem Statement

Snuke is conducting an optical experiment using mirrors and his new invention, the rifle of Mysterious Light.

Three mirrors of length N are set so that they form an equilateral triangle.
Let the vertices of the triangle be a, b and c.

Inside the triangle, the rifle is placed at the point p on segment ab such that ap = X.
(The size of the rifle is negligible.)
Now, the rifle is about to fire a ray of Mysterious Light in the direction of bc.

The ray of Mysterious Light will travel in a straight line, and will be reflected by mirrors, in the same ways as "ordinary" light.
There is one major difference, though: it will be also reflected by its own trajectory as if it is a mirror!
When the ray comes back to the rifle, the ray will be absorbed.

The following image shows the ray's trajectory where N = 5 and X = 2.

It can be shown that the ray eventually comes back to the rifle and is absorbed, regardless of the values of N and X.
Find the total length of the ray's trajectory.

Constraints

2≦N≦10^{12}

1≦X≦N-1

N and X are integers.

Partial Points

300 points will be awarded for passing the test set satisfying N≦1000.

Another 200 points will be awarded for passing the test set without additional constraints.

Input

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

N X

Output

Print the total length of the ray's trajectory.

Sample Input 1

5 2

Sample Output 1

12

Refer to the image in the Problem Statement section.
The total length of the trajectory is 2+3+2+2+1+1+1 = 12.


import java.io.*;
import java.math.*;
import java.util.*;
import java.util.Map.Entry;

class Main {
	static Node[] node;
	public static void main(String[] args) {
		//FastScanner sc = new FastScanner();
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int K = sc.nextInt();
		int[] A = new int[N-1];
		int[] B = new int[N-1];
		for(int i = 0; i < N-1; i++) {
			A[i] = sc.nextInt();
			B[i] = sc.nextInt();
		}
		node = new Node[N];
		for(int i = 0; i < N; i++) {
			node[i] = new Node();
		}
		for(int i = 0; i < N-1; i++) {
			node[A[i] - 1].dst.add(B[i] - 1);
			node[B[i] - 1].dst.add(A[i] - 1);
		}
		int count = 0;
		while(true) {
			Data tmp = diameter();
			if(tmp.length <= K) break;
			node[tmp.maxID].rem = true;
			count++;
		}
		System.out.println(count);
	}

	static Data diameter() {
		int[] min = new int[node.length];
		boolean[] cantRemove = new boolean[node.length];
		for(int i = 0; i < node.length; i++) {
			if(node[i].rem) cantRemove[i] = true;
			ArrayList<Integer> next = node[i].dst;
			int count = 0;
			for(int j = 0; j < next.size(); j++) {
				if(!node[next.get(j)].rem) count++;
			}
			if(count >= 2) cantRemove[i] = true;
		}
		Arrays.fill(min, 2 << 28);
		ArrayDeque<P> q = new ArrayDeque<>();
		for(int i = 0; i < node.length; i++) {
			if(!node[i].rem) {
				q.addFirst(new P(i,0));
				break;
			}
		}
		int maxP = 0;
		int maxL = 0;
		while(!q.isEmpty()) {
			P p = q.pollLast();
			if(min[p.now] <= p.cost) continue;
			min[p.now] = p.cost;
			if(maxL < p.cost) {
				maxL = p.cost;
				maxP = p.now;
			}
			for(int i = 0; i < node[p.now].dst.size(); i++) {
				if(!node[node[p.now].dst.get(i)].rem) q.addFirst(new P(node[p.now].dst.get(i),p.cost+1));
			}
		}
		Arrays.fill(min, 2 << 28);
		q.addFirst(new P(maxP,0));
		maxP = 0;
		maxL = 0;
		int maxLL = 0;
		while(!q.isEmpty()) {
			P p = q.pollLast();
			if(min[p.now] <= p.cost) continue;
			min[p.now] = p.cost;
			if(maxLL < p.cost) {
				maxLL = p.cost;

			}
			if(maxL < p.cost && !cantRemove[p.now]) {
				maxL = p.cost;
				maxP = p.now;
			}
			for(int i = 0; i < node[p.now].dst.size(); i++) {
				if(!node[node[p.now].dst.get(i)].rem) q.addFirst(new P(node[p.now].dst.get(i),p.cost+1));
			}
		}
		return new Data(maxP,maxLL);
	}
	static class P {
		int now;
		int cost;
		P(int a, int b) {
			now = a;
			cost = b;
		}
	}
	static class Data {
		int maxID;
		int length;
		Data(int a, int b) {
			maxID = a;
			length = b;
		}
	}
	static class Node {
		boolean rem = false;
		ArrayList<Integer> dst = new ArrayList<>();
	}

	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;}
	    private void skipUnprintable() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;}
	    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() {
	        if (!hasNext()) throw new NoSuchElementException();
	        int 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();
	        }
	    }
	}
}

Score : 600 points

Problem Statement

Given an undirected tree, let the distance between vertices u and v be the
number of edges on the simple path from u to v.
The diameter of a tree is the maximum among the distances between any two vertices.
We will call a tree good if and only if its diameter is at most K.

You are given an undirected tree with N vertices numbered 1 through N.
For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i.

You want to remove zero or more vertices from the tree, so that the resulting tree is good.
When a vertex is removed, all incident edges will also be removed.
The resulting graph must be connected.

Find the minimum number of vertices that you need to remove in order to produce a good tree.

Constraints

2≦N≦2000

1≦K≦N-1

1≦A_i≦N, 1≦B_i≦N

The graph defined by A_i and B_i is a tree.

Input

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

N K
A_1 B_1
A_2 B_2
:
A_{N-1} B_{N-1}

Output

Print the minimum number of vertices that you need to remove in order to produce a good tree.

Sample Input 1

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

Sample Output 1

2

The tree is shown below. Removing vertices 5 and 6 will result in a good tree with the diameter of 2.

Sample Input 2

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

Sample Output 2

0

Since the given tree is already good, you do not need to remove any vertex.