import java.util.*;
public class Main{
  static boolean palin(String s)
  {char c[]=s.toCharArray();
   int n=c.length;
   for(int i=0;i<n;i++)
   {
     if(c[i]!=c[n-1-i])
       return false;
   }
   return true;
  }
 public static void main(String args[])
   { Scanner sc=new Scanner(System.in);
     String s=sc.next();
    int n=s.length();
     boolean palindrome=palin(s);
     if(palindrome==true)
     { String x=s.substring(0,(n-1)/2);
       String y=s.substring(((n+3)/2)-1,n);
       if(palin(x) && palin(y))
         System.out.println("Yes");
     }
    else
      System.out.println("No");
   }
}

Score : 200 points

Problem Statement

A string S of an odd length is said to be a strong palindrome if and only if all of the following conditions are satisfied:

S is a palindrome.

Let N be the length of S. The string formed by the 1-st through ((N-1)/2)-th characters of S is a palindrome.

The string consisting of the (N+3)/2-st through N-th characters of S is a palindrome.

Determine whether S is a strong palindrome.

Constraints

S consists of lowercase English letters.

The length of S is an odd number between 3 and 99 (inclusive).

Input

Input is given from Standard Input in the following format:

S

Output

If S is a strong palindrome, print Yes;
otherwise, print No.

Sample Input 1

akasaka

Sample Output 1

Yes

S is akasaka.

The string formed by the 1-st through the 3-rd characters is aka.

The string formed by the 5-th through the 7-th characters is aka.
All of these are palindromes, so S is a strong palindrome.

Sample Input 2

level

Sample Output 2

No

Sample Input 3

atcoder

Sample Output 3

No


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        boolean ans = isPalind(str, 0, str.length()) &&
                isPalind(str, 0, (str.length() - 1) / 2) &&
                isPalind(str, (str.length() + 3) / 2 - 1, str.length());
        System.out.println(ans ? "Yes" : "No");
    }

    static boolean isPalind(String str, int s, int e) {
        StringBuilder rsb = new StringBuilder();
        char[] C = str.toCharArray();
        for(int i = s; i < e - s; i++) {
            if(C[i] != C[e - i - 1]) return false;
        }
        return true;
    }
}

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

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.


//パターン1：OK(小数点以下切り捨て)
import java.math.BigDecimal;
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int len = sc.nextInt();

		BigDecimal wSide = new BigDecimal((double)len/3);
		BigDecimal tSide = new BigDecimal((double)len/3);
		BigDecimal hSide = new BigDecimal((double)len/3);

		System.out.println(wSide);
		System.out.println(tSide);
		System.out.println(hSide);

		BigDecimal result = wSide.multiply(tSide).multiply(hSide);

		System.out.print(result);
		sc.close();
	}
}

//パターン2：OK(小数点以下6桁以降に桁落ちアリ)
//package ojt.AtCoder;
//import java.util.Scanner;
//public class TestC_159 {
//	public static void main(String[] args) {
//		Scanner sc = new Scanner(System.in);
//		int len = sc.nextInt();
//
//		double wSide = (double)len/3;
//		double tSide = (double)len/3;
//		double hSide = (double)len/3;
//
//		System.out.println(wSide);
//		System.out.println(tSide);
//		System.out.println(hSide);
//
//		double result = wSide*tSide*hSide;
//
//		System.out.print(result);
//		sc.close();
//	}
//}

//パターン3：OK(小数点以下6桁以降に桁落ちアリ)
//package ojt.AtCoder;
//import java.util.Scanner;
//public class TestC_159 {
//	public static void main(String[] args) {
//		Scanner sc = new Scanner(System.in);
//		double len = sc.nextDouble();
//
//		System.out.println(Math.pow(len/3 , 3));
//
//		sc.close();
//	}
//}

Score : 300 points

Problem Statement

Given is a positive integer L.
Find the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L.

Constraints

1 ≤ L ≤ 1000

L is an integer.

Input

Input is given from Standard Input in the following format:

L

Output

Print the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L.
Your output is considered correct if its absolute or relative error from our answer is at most 10^{-6}.

Sample Input 1

3

Sample Output 1

1.000000000000

For example, a rectangular cuboid whose dimensions are 0.8, 1, and 1.2 has a volume of 0.96.

On the other hand, if the dimensions are 1, 1, and 1, the volume of the rectangular cuboid is 1, which is greater.

Sample Input 2

999

Sample Output 2

36926037.000000000000


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ
		Scanner sc = new Scanner(System.in);
	    double l = sc.nextInt();

		double a = l/3.0;

		System.out.println(Math.pow(a,  3));

	}
}


import java.io.PrintStream;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) throws Exception{
		new Main(new Scanner(System.in), System.out, System.err).exec();
	}
	public final Scanner sc;
	public final PrintStream out, err;
	public Main(final Scanner sc, final PrintStream out, final PrintStream err) {
		this.sc = sc;this.out = out;this.err = err;
	}
	static public final long pair(int a, int b) {return (((long)a) << 32) + b;}
	static public final int getPair1(long v) {return (int)(v >> 32);}
	static public final int getPair2(long v) {return (int)(v & 0xFFFFFFFF);}

	static public final long quad(long a, long b, long c, long d) {
		return ((a&0xFFFF)<< 48) + ((b&0xFFFF)<< 32) + ((c&0xFFFF)<< 16) +(d&0xFFFF);}
	static public final int getQuad1(long v) {return (int)( v >> 48          );}
	static public final int getQuad2(long v) {return (int)((v >> 32) & 0xFFFF);}
	static public final int getQuad3(long v) {return (int)((v >> 16) & 0xFFFF);}
	static public final int getQuad4(long v) {return (int)( v        & 0xFFFF);}

	static public final long record(int e, int m, int i) {
		return quad(-1, e, m, i);
	}
	static public final int re(long record) {
		return getQuad2(record);
	}
	static public final int rm(long record) {
		return getQuad3(record);
	}
	static public final int ri(long record) {
		return getQuad4(record);
	}

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

	private int p;
	private int[] inv;
	private int[] fact;
	private int[] finv;
	public final int mod(long v) {
		return mod(v, p);
	}
	static public final int mod(long v, int M) {
		v %= M;
		return (int)(v < 0 ? v+M : v);
	}
	/**
	 * a * b (mod p)
	 * 事前にinitFactを行うこと。
	 */
	public final int mul(long a, long b) {
		return mod(a*b);
	}
	public final void initFact(double limit, double p) {
		initFact((int)limit, (int)p);
	}
	/**
	 * 集合数nの組み合わせ計算を高速化するため、事前に計算を行う。
	 * 組み合わせ数はpで割った余りを算出する。
	 */
	public final void initFact(int n, int p) {
		this.p = p;
		this.inv = new int[n+1];
		this.fact = new int[n+1];
		this.finv = new int[n+1];
		fact[1] = finv[1] = inv[0] = inv[1] = 1;
		for(int i=2;i<=n;i++) {
			int a = p / i;
			int b = p % i;
			inv[i]  = mul(-a, inv[b]);
			fact[i] = mul(fact[i-1], i);
			finv[i] = mul(finv[i-1], inv[i]);
		}
	}
	/**
	 * mCnを計算する。事前にinitFactを実行すること。
	 */
	public final int comb(int m, int n) {
		return mul(mul(fact[m], finv[n]), finv[m-n]);
	}
	/**
	 * a^b (mod M)を計算する。
	 */
	public static long pow(long a, long b, int M) {
		long ret = 1;
		long tmp = a;
		while (b > 0) {
			if ((b & 1) == 1) {
				ret = (ret * tmp) % M;
			}
			tmp = (tmp * tmp) % M;
			b = b >> 1;
		}
		return ret;
	}
	/**
	 * nCk (mod M)を計算する。
	 */
	public static int nCk(int n, int k, int M) {
		long ret = 1;
		int min = Math.min(k, n - k);
		// 分母
		for (int i = 1; i <= min; i++) {
			// a^-1 ≡ a^M-2  ※フェルマーの小定理
			ret = (ret * pow(i, M - 2, M)) % M;
		}
		// 分子
		for (int i = n - min + 1; i <= n; i++) {
			ret = (ret * i) % M;
		}
		return (int) ret;
	}
	//------------------------------------------
	static long lcm (long a, long b) {
		long temp;
		long c = a;
		c *= b;
		while((temp = a%b)!=0) {
			a = b;
			b = temp;
		}
		return (long)(c/b);
	}

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

	static class DisjointSetUnion {
		public int[] parent;
		public int[] weight;
		public int count;

		public DisjointSetUnion(int nodes) {
			count = nodes;
			parent = new int[nodes];
			weight = new int[nodes];
			for (int i = 0; i < nodes; i++) {
				parent[i] = i;
				weight[i] = 1;
			}
		}
		//"find"
		public int root(int p) {
			while (p != parent[p]) {
				p = parent[p];
			}
			return p;
		}

		//"union"
		public void connect(int p, int q) {
			int rootP = root(p);
			int rootQ = root(q);
			if (rootP == rootQ) return;
			if (weight[rootP] < weight[rootQ]) {
				parent[rootP] = rootQ;
				weight[rootQ] += weight[rootP];
			} else {
				parent[rootQ] = rootP;
				weight[rootP] += weight[rootQ];
			}
			count--;
		}

		public boolean connected(int p, int q) {
			return root(p) == root(q);
		}
	}
	static class IntList{
		int tail = 0;
		final int[] element;
		public IntList(int cap) {
			element = new int[cap];
		}
		public int size() {
			return tail;
		}
		public int get(int index) {
			return element[index];
		}
		public void reset() {
			tail = 0;
		}
		public void add(int v) {
			element[tail++] = v;
		}
	}
	static class LongList{
		int tail = 0;
		int head = 0;
		final long[] element;
		public LongList(int cap) {
			element = new long[cap];
		}
		public int size() {
			return (element.length+tail-head)%element.length;
		}
		public long remove() {
			long v = element[head];
			head = (head+1)%element.length;
			return v;
		}
		public long get(int index) {
			return element[index];
		}
		public void reset() {
			head = 0;
			tail = 0;
		}
		public void add(long v) {
			element[tail] = v;
			tail = (tail+1)%element.length;
		}
		public boolean hasElement() {
			return this.size()!=0;
		}
	}

	public void exec() throws Exception{
		final int L = sc.nextInt();
		final double a = ((double)L)/3;
		out.println(String.format("%.12f", a*a*a));
	}
}


import java.util.*;
public class Main{
  public static void main(String[] args){
    Scanner sc =new Scanner(System.in);
    int N=sc.nextInt();
    int A[] =new int[N];
    int B[] =new int[N];
    int C[] =new int[N+1];
    int D[] =new int[N];
    long W[] =new long[N];
    C[0]=0;
    for(int i=0;i<N;i++){
      A[i]=sc.nextInt();
      B[A[i]-1]=B[A[i]-1]+1;}
    int X=0;
    for(int x=0;x<N;x++){
      if(!(B[x]==0)){X=X+1;}}
    for(int j=0;j<N;j++){
      if(!(D[A[j]-1]==0)){C[j+1]=C[j];continue;}
       D[A[j]-1]=B[A[j]-1]*(B[A[j]-1]-1)/2;
       C[j+1]=C[j]+D[A[j]-1];}
        for(int k=0;k<N;k++){
           W[k]=C[N]-D[A[k]-1]+(B[A[k]-1]-1)*(B[A[k]-1]-2)/2;
      System.out.println(W[k]);}
  }
}

Score : 400 points

Problem Statement

We have N balls. The i-th ball has an integer A_i written on it.

For each k=1, 2, ..., N, solve the following problem and print the answer.

Find the number of ways to choose two distinct balls (disregarding order) from the N-1 balls other than the k-th ball so that the integers written on them are equal.

Constraints

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

1 \leq A_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

For each k=1,2,...,N, print a line containing the answer.

Sample Input 1

5
1 1 2 1 2

Sample Output 1

2
2
3
2
3

Consider the case k=1 for example. The numbers written on the remaining balls are 1,2,1,2.

From these balls, there are two ways to choose two distinct balls so that the integers written on them are equal.

Thus, the answer for k=1 is 2.

Sample Input 2

4
1 2 3 4

Sample Output 2

0
0
0
0

No two balls have equal numbers written on them.

Sample Input 3

5
3 3 3 3 3

Sample Output 3

6
6
6
6
6

Any two balls have equal numbers written on them.

Sample Input 4

8
1 2 1 4 2 1 4 1

Sample Output 4

5
7
5
7
7
5
7
5


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

/**
 *  @author Ivan Pryvalov (ivan.pryvalov@gmail.com)
 */
public class Main implements Runnable {

    static EventType eventType = EventType.DEFAULT; //EventType.GOOGLE_CODE_JAM;
    static boolean interactive = false; //use outGlobal.println()   and   outGlobal.flush()
    static int T = 1; // T \in {0,1}. If T=0, it will be read from the input.
    static String inputFilename = null; // if 'null', it reads data from std-in.

    static boolean largeFakeTest = false; // Check if you generate data on fly
    static int largeFakeTest_T = 1;
    //--------------------------------------------------------------------

    public static class Solver extends  SolverAbstract{

        int N;
        int[] A;

        @Override
        public void readInput() throws IOException {
            N = scanner.nextInt();
            A = scanner.loadIntArray(N);
        }

        private long cntPairs(long a){
            return a*(a-1)/2;
        }

        @Override
        protected void solve() throws IOException {
            int[] cnt = new int[N+1];
            for (int i = 0; i < N; i++) {
                cnt[A[i]]++;
            }
            long[] res = new long[N+1];
            for (int i = 0; i < N; i++) {
                res[i] = cntPairs(cnt[i]);
            }
            long cnt_sum = Arrays.stream(res).sum();
            for (int i = 0; i < N; i++) {
                out.println(cnt_sum - res[A[i]] + cntPairs(cnt[A[i]]-1));
            }
        }

    }

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

    private void solveAll() throws IOException {
        long timeStart = System.currentTimeMillis();
        if (T==0) {
            if (largeFakeTest) {
                T = largeFakeTest_T;
            } else {
                T = scanner.nextInt();
            }
        }
        final String[] results = new String[T+1];
        for (int test = 0; test < T; test++) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream outLocal = new PrintStream(baos);
            Solver solver = new Solver(){
                @Override
                public void callback() {
                    results[testNo] = answer;
                }
            };
            solver.out = outLocal;
            solver.testNo = test+1;
            if (largeFakeTest) {
                solver.readFakeInput();
            }else{
                solver.readInput();
            }
            solver.solveWrapped(baos);
        }

        long timeEnd = System.currentTimeMillis();
        if (isInputFromFile())
            System.out.println("All tasks are solved! Elapsed time "+(timeEnd-timeStart)/1000.0+" sec.");

        // write all responses in the proper order
        if (!interactive) {
            for (int i = 1; i <= T; i++) {
                if (eventType == EventType.GOOGLE_CODE_JAM) {
                    outGlobal.printf("Case #%d: %s", i, results[i]);
                } else {
                    outGlobal.print(results[i]);
                }
            }
        }
    }

    enum EventType{
        DEFAULT,
        GOOGLE_CODE_JAM
    }

    static boolean isInputFromFile() {
        return inputFilename != null;
    }

    public static abstract class SolverAbstract {
        PrintStream out;
        int testNo;
        String answer = null;

        public void callback(){};

        public abstract void readInput() throws IOException;

        //generate a randomized test with the maximal input values
        public void readFakeInput() throws  IOException{
            throw new RuntimeException("not implemented");
        }

        protected abstract void solve() throws IOException;

        protected void solveWrapped(ByteArrayOutputStream baos) throws IOException {
            if (isInputFromFile())
                System.out.println("SOLVER: solving task #"+testNo+" out of "+ T+"...");
            solve();
            answer = baos.toString();
            if (isInputFromFile()) {
                System.out.println("\t"+answer);
            }
            callback();
        }
    }

    ////////////////////////////////////////////////////////
    // Link about multithreading: http://stackoverflow.com/questions/4521983/java-executorservice-that-blocks-on-submission-after-a-certain-queue-size

    // ------------- Some stardard tools that are currently not tested.
    //adopt for the lists of adjacent vertices
    static class Graph{

        int[][] G;
        int N;

        int[][] A;
        int[][] F;

        int[] path;
        int pathLen;
        boolean[] visited;
        int target;
        boolean flowFound;

        public Graph(int[][] g) {
            G = g;
            N = G.length;
        }

        public int[][] maxflow(int iSource, int iSink) {
            path = new int[N];
            visited = new boolean[N];

            A = new int[N][];
            for (int i = 0; i < N; i++) {
                A[i] = G[i].clone();
            }
            F = new int[N][N];

            target = iSink;
            //dfs from source to sink
            //increase path
            while(true){
                flowFound = false;
                visited[iSource] = true;
                pathLen = 0;
                path[pathLen++] = iSource;
                dfs(iSource);
                if (!flowFound)
                    break;
            }
            return F;
        }

        private void dfs(int u) {
            if (u==target){
                flowFound = true;
                for (int i = 0; i < pathLen-1; i++) {
                    int from = path[i];
                    int to  = path[i+1];
                    F[from][to]++;
                    F[to][from]--;
                }
            }else {
                for (int i = 0; i < N && !flowFound; i++) {
                    if (!visited[i] && A[u][i] > F[u][i]) {
                        visited[i] = true;
                        path[pathLen] = i;
                        pathLen++;
                        dfs(i);
                        visited[i] = false;
                        pathLen--;
                    }
                }
            }
        }
    }

    public static class Utilities{
        public static List<Integer> getPrimes(int limit) {
            boolean[] primes = new boolean[limit+1];
            Arrays.fill(primes, true);

            primes[1] = false;
            for(int i=2; i<=limit; i++){
                if (primes[i]){
                    for(int j=i+i; j<=limit; j+=i){
                        primes[j] = false;
                    }
                }
            }
            List<Integer> listPrimes = new ArrayList<>();
            for(int i=2; i<=limit; i++){
                if (primes[i]){
                    listPrimes.add(i);
                }
            }
            return listPrimes;
        }
    }

    public static class Modulo{
        long mod = (long)1e9+7;

        public Modulo(long mod) {
            super();
            this.mod = mod;
        }

        public long inv(long a) {
            long res =  pow(a, mod-2);
            return res;
        }

        public long pow(long a, long x) {
            if (x==0)
                return 1;
            long part = 1;
            if ((x&1)!=0)
                part = a;
            return (part * pow((a*a)%mod, x>>1)) % mod;
        }

        public long c(long n, long m){
            long res = 1;
            for(int i=1; i<=m; i++){
                res = (res * (n-m+i)) % mod;
                res = (res * inv(i)) % mod;
            }
            return res;
        }
    }

    /**
     * Added 26.04.2013.
     * See KROK 2013, Round 1, Problem D.
     */
    static class DisjointUnionSet implements Cloneable{
        int[] rank;
        int[] parent;

        protected DisjointUnionSet clone(){
            DisjointUnionSet cloned = new DisjointUnionSet(parent.length);
            for(int i=0; i<parent.length; i++){
                cloned.parent[i] = parent[i];
                cloned.rank[i] = rank[i];
            }
            return cloned;
        }

        public DisjointUnionSet(int n) {
            rank = new int[n];
            parent = new int[n];
            for (int i = 0; i < n; i++) {
                parent[i] = i;
            }
        }

        @Override
        public String toString() {
            return "disj [parents=" + Arrays.toString(parent) + "]";
        }

        /**
         * Problem specific or general?
         * O(N * alpha)
         */
        public void union(DisjointUnionSet set2){
            for(int i=0; i<parent.length; i++){
                parent[find(i)] = parent[find(set2.find(i))];
            }
        }

        /**
         * @param index1 range 0..n-1
         * @param index2
         */
        public void union(int index1, int index2){
            int p1 = find(index1);
            int p2 = find(index2);
            if (rank[p1] > rank[p2]){
                parent[p2] = p1;
            }else if (rank[p2] > rank[p1]){
                parent[p1] = p2;
            }else{
                parent[p2] = p1;
                rank[p1]++;
            }
        }

        // O(alpha(n))
        private int find(int index) {
            if (parent[index] != index)
                parent[index] =  find(parent[index]);
            return parent[index];
        }

        // O(N alpha(N)) ==> see find()
        public int getCountDisjointSets(){
            int[] used = new int[parent.length];
            for(int i=0; i<parent.length; i++){
                used[find(i)] = 1;
            }
            int res = 0;
            for(int i=0; i<parent.length; i++){
                res += used[i];
            }
            return res;
        }
    }

    private static Random rnd = new Random();
    public static class ArrayUtils{
        public static void shuffle(int[] a){
            for(int j=a.length-1; j>=1; j--){
                int i = rnd.nextInt(j+1);
                swap(a, i, j);
            }
        }

        public static void swap(int[] a, int i, int j){
            int tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;
        }
    }

    static class GraphSupport{
        /*
        //Added 20.02.2017.
        //See Codeforces Round 398, Div.2, C.
        // Recoursive call to dfs function may result in either MTL or StackOverflow.
        // Codeforces provide stacksize 64M

        private void dfs_no_recursion(int root, IntConsumer dfs_post){
            int[] stack = new int[N];
            int[] stackInt = new int[N];
            int iStack = 0;
            stack[iStack] = root;
            stackInt[iStack++] = 0;
            while(true){
                Node node = nodes[stack[iStack-1]];
                int childIdx = stackInt[iStack-1];
                if (childIdx < node.children.size()){
                    stack[iStack] = node.children.get(childIdx).idx;
                    stackInt[iStack++] = 0;
                }else{
                    dfs_post.accept(node.idx);

                    iStack--;
                    if (iStack==0){
                        break;
                    }
                    stackInt[iStack-1]++;
                }
            }
        }
        */
    }

    ////////////////////////////////////////////////////////
    /// Typically, you don't want to edit anything below
    ///////////////////////////////////////////////////////
    final int BUF_SIZE = 1024 * 1024 * 8;//important to read long-string tokens properly
    final int INPUT_BUFFER_SIZE = 1024 * 1024 * 8;
    final int BUF_SIZE_INPUT = 1024;

    boolean useClassResourceTopDir = true;
    String outSuffix = ".out";

    static PrintStream outGlobal;
    static ByteScanner scanner;

    public void run() {
        try{
            InputStream bis;
            OutputStream bos;
            if (inputFilename !=null){
                File inputFile;
                File outputFile;
                if (useClassResourceTopDir) {
                    File baseFile = new File(getClass().getResource("/").getFile());
                    inputFile = new File(baseFile, inputFilename);
                    outputFile = new File(baseFile, inputFilename +outSuffix);
                }else{
                    inputFile = new File(inputFilename);
                    outputFile = new File(inputFilename +outSuffix);
                }
                System.out.println("Input file canonical path: "+inputFile.getCanonicalPath());
                bis = new BufferedInputStream(
                        new FileInputStream(inputFile),
                        INPUT_BUFFER_SIZE);
                bos = new BufferedOutputStream(new FileOutputStream(outputFile));
                outGlobal = new PrintStream(bos);
            }else{
                bis = new BufferedInputStream(System.in, INPUT_BUFFER_SIZE);
                bos = new BufferedOutputStream(System.out);
                outGlobal = new PrintStream(bos);
            }
            scanner = new ByteScanner(bis, BUF_SIZE_INPUT, BUF_SIZE);

            solveAll();
            outGlobal.flush();
        }catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public static class EofException extends IOException{
    }

    public static class ByteScanner{
        InputStream is;

        public ByteScanner(InputStream is, int bufSizeInput, int bufSize){
            this.is = is;
            this.bufSizeInput = bufSizeInput;
            this.bufSize = bufSize;

            byteBufInput = new byte[this.bufSizeInput];
            byteBuf = new byte[this.bufSize];
        }

        public ByteScanner(byte[] data){
            byteBufInput = data;
            bufSizeInput = data.length;
            bufSize = data.length;
            byteBuf = new byte[bufSize];
            byteRead = data.length;
            bytePos = 0;
        }

        private int bufSizeInput;
        private int bufSize;

        byte[] byteBufInput;
        byte by=-1;
        int byteRead=-1;
        int bytePos=-1;

        byte[] byteBuf;
        int totalBytes;

        boolean eofMet = false;

        private byte nextByte() throws IOException{
            if (bytePos<0 || bytePos>=byteRead){
                byteRead = is==null? -1: is.read(byteBufInput);
                bytePos=0;
                if (byteRead<0){
                    byteBufInput[bytePos]=-1;//!!!
                    if (eofMet)
                        throw new EofException();
                    eofMet = true;
                }
            }
            return byteBufInput[bytePos++];
        }

        public byte nextVisibleChar() throws IOException{
            while ((by=nextByte())<=0x20);
            return by;
        }

        public String nextLine() throws IOException {
            readToken((byte)0x20);
            return new String(byteBuf,0,totalBytes);
        }

        // Reads token. Spacebar is separator char.
        public String nextToken() throws IOException {
            readToken((byte)0x21);
            return new String(byteBuf,0,totalBytes);
        }

        // Spacebar is included as separator char
        private void readToken() throws IOException {
            readToken((byte)0x21);
        }

        private void readToken(byte acceptFrom) throws IOException {
            totalBytes = 0;
            while ((by=nextByte())<acceptFrom);
            byteBuf[totalBytes++] = by;
            while ((by=nextByte())>=acceptFrom){
                byteBuf[totalBytes++] = by;
            }
        }

        public int nextInt() throws IOException{
            readToken();
            int num=0, i=0;
            boolean sign=false;
            if (byteBuf[i]=='-'){
                sign = true;
                i++;
            }
            for (; i<totalBytes; i++){
                num*=10;
                num+=byteBuf[i]-'0';
            }
            return sign?-num:num;
        }

        public long nextLong() throws IOException{
            readToken();
            long num=0;
            int i=0;
            boolean sign=false;
            if (byteBuf[i]=='-'){
                sign = true;
                i++;
            }
            for (; i<totalBytes; i++){
                num*=10;
                num+=byteBuf[i]-'0';
            }
            return sign?-num:num;
        }

        public double nextDouble() throws IOException{
            readToken();
            char[] token = new char[totalBytes];
            for (int i = 0; i < totalBytes; i++) {
                token[i] = (char)byteBuf[i];
            }
            return Double.parseDouble(new String(token));
        }

        public int[] loadIntArray(int size) throws IOException{
            int[] a = new int[size];
            for (int i = 0; i < a.length; i++) {
                a[i] = nextInt();
            }
            return a;
        }

        public long[] loadLongArray(int size) throws IOException{
            long[] a = new long[size];
            for (int i = 0; i < a.length; i++) {
                a[i] = nextLong();
            }
            return a;
        }
    }

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


import java.util.HashMap;
import java.util.Map;
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());
        int[] a = new int[n];
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < n; i++){
            a[i] = Integer.parseInt(sc.next());
            map.put(a[i], map.getOrDefault(a[i], 0) +1);
        }

        long c = 0;
        for (Integer i : map.keySet()) {
            long j = map.get(i);
            if(j >= 2){
                c += (j * (j-1)) /2;
            }
        }

        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < n; i++){
            sb.append(c - (map.get(a[i]) -1)).append(System.lineSeparator());
        }
        System.out.print(sb);
    }
}


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

//多項式を利用した考察による解法
public class Main {
	static final int mod = 998244353;
	static final int DX[] = { -1, 0, 1, 0 }, DY[] = { 0, -1, 0, 1 };
	static final int[] DX8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, DY8 = { -1, 0, 1, -1, 1, -1, 0, 1 };
	static final int INF = Integer.MAX_VALUE / 3;
	static final long LINF = Long.MAX_VALUE / 3;
	static final String nextLine = "\n";

	public static void main(String[] args) {
		FastScanner fs = new FastScanner(System.in);
		int n = fs.nextInt(), s = fs.nextInt();
		int a[] = fs.nextIntArray(n);

		int F[] = new int[s+1];
		long ans = 0;
		for(int i=0;i<n;i++) {
			F[0] += 1;
			int F2[] = new int[s+1];
			for(int j=0;j<s+1;j++) {//このループがF3=f3(F2+1)のf3をかける事に値する
				F2[j] += F[j];
				F2[j] %= mod;
				if(j+a[i]<s+1) {
					F2[j+a[i]] += F[j];
					F2[j+a[i]] %= mod;
				}
			}
			F = F2;
			ans += F[s];
			ans %= mod;
		}
		System.out.println(ans);
	}

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

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

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

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

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

//高速なScanner
class FastScanner {
	private BufferedReader reader = null;
	private StringTokenizer tokenizer = null;

	public FastScanner(InputStream in) {
		reader = new BufferedReader(new InputStreamReader(in));
		tokenizer = null;
	}

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

	public String nextLine() {
		if (tokenizer == null || !tokenizer.hasMoreTokens()) {
			try {
				return reader.readLine();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		return tokenizer.nextToken("\n");
	}

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

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

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

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

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

Score : 600 points

Problem Statement

Given are a sequence of N integers A_1, A_2, \ldots, A_N and a positive integer S.

For a pair of integers (L, R) such that 1\leq L \leq R \leq N, let us define f(L, R) as follows:

f(L, R) is the number of sequences of integers (x_1, x_2, \ldots , x_k) such that L \leq x_1 < x_2 < \cdots < x_k \leq R and A_{x_1}+A_{x_2}+\cdots +A_{x_k} = S.

Find the sum of f(L, R) over all pairs of integers (L, R) such that 1\leq L \leq R\leq N. Since this sum can be enormous, print it modulo 998244353.

Constraints

All values in input are integers.

1 \leq N \leq 3000

1 \leq S \leq 3000

1 \leq A_i \leq 3000

Input

Input is given from Standard Input in the following format:

N S
A_1 A_2 ... A_N

Output

Print the sum of f(L, R), modulo 998244353.

Sample Input 1

3 4
2 2 4

Sample Output 1

5

The value of f(L, R) for each pair is as follows, for a total of 5.

f(1,1) = 0

f(1,2) = 1 (for the sequence (1, 2))

f(1,3) = 2 (for (1, 2) and (3))

f(2,2) = 0

f(2,3) = 1 (for (3))

f(3,3) = 1 (for (3))

Sample Input 2

5 8
9 9 9 9 9

Sample Output 2

0

Sample Input 3

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

Sample Output 3

152


//--- pA ---//
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
	public static void main (String[] args) throws java.lang.Exception {
		new Solution();
	}
}
class Solution {
	Reader reader;
	public Solution () {
		reader = new Reader();
		while (reader.hasNext()) {
			run_case();
		}
	}

	int[] dir_row = new int[]{1, 0};
	int[] dir_col = new int[]{0, 1};
	int inf = (int)1e9;
	int row, col;
	int res;
	char[][] grid;
	private void run_case() {
		row = reader.ni();
		col = reader.ni();
		grid = new char[row][col];
		for (int i=0; i<row; i++) grid[i] = reader.ns().toCharArray();

		res = inf;
		dfs(0, 0, grid[0][0] == '.' ? 0 : 1);

		// Queue<State> q = new LinkedList<>();
		// q.offer(new State(0, 0, grid[0][0] == '#' ? 1 : 0));
		//
		// int[][] mem = new int[row][col];
		// for (int i=0; i<row; i++) {
		// 	Arrays.fill(mem[i], inf);
		// }
		//
		// int res = inf;
		//
		// while (!q.isEmpty()) {
		// 	State cur = q.poll();
		// 	if (cur.r == row-1 && cur.c == col-1) {
		// 		res = Math.min(res, cur.brk);
		// 		continue;
		// 	}
		//
		// 	for (int i=0; i<dir_row.length; i++) {
		// 		int tr = cur.r + dir_row[i];
		// 		int tc = cur.c + dir_col[i];
		// 		if (tr < 0 || tc < 0 || tr >= row || tc >= col) continue;
		// 		int tbrk = cur.brk + (grid[tr][tc] == '#' ? 1 : 0);
		// 		if (tbrk >= mem[tr][tc]) continue;
		// 		mem[tr][tc] = tbrk;
		// 		q.offer(new State(tr, tc, tbrk));
		// 	}
		// }

		System.out.println(res);
		return;
	}

	private void dfs(int r, int c, int brk) {
		if (r == row-1 && c == col-1) {
			res = Math.min(res, brk);
		}
		for (int i=0; i<dir_row.length; i++) {
			int tr = r + dir_row[i];
			int tc = c + dir_col[i];
			if (tr < 0 || tc < 0 || tr >= row || tc >= col) continue;
			char hold = grid[tr][tc];
			int cost = grid[tr][tc] == '#' ? 1 : 0;
			grid[tr][tc] = '.';
			dfs(tr, tc, brk + cost);
			grid[tr][tc] = hold;
		}
		return;
	}
}

class State {
	int r, c, brk;
	public State(int r, int c, int brk) {
		this.r = r;
		this.c = c;
		this.brk = brk;
	}
}

class Reader {
	BufferedReader br;
	StringTokenizer st;
	public Reader(){
		try {
			br = new BufferedReader(new InputStreamReader(System.in));
			st = new StringTokenizer(br.readLine());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public String next() {
		if (st.hasMoreTokens()) return st.nextToken();
		try {
			st = new StringTokenizer(br.readLine());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return st.nextToken();
	}
	public boolean hasNext() {
		try {
			if (!st.hasMoreTokens() && !br.ready()) return false;
			else return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	public int ni() {return Integer.parseInt(this.next());}
	public String ns() {return this.next();}
}

Score : 400 points

Problem Statement

Consider a grid with H rows and W columns of squares. Let (r, c) denote the square at the r-th row from the top and the c-th column from the left.
Each square is painted black or white.

The grid is said to be good if and only if the following condition is satisfied:

From (1, 1), we can reach (H, W) by moving one square right or down repeatedly, while always being on a white square.

Note that (1, 1) and (H, W) must be white if the grid is good.

Your task is to make the grid good by repeating the operation below. Find the minimum number of operations needed to complete the task. It can be proved that you can always complete the task in a finite number of operations.

Choose four integers r_0, c_0, r_1, c_1(1 \leq r_0 \leq r_1 \leq H, 1 \leq c_0 \leq c_1 \leq W). For each pair r, c (r_0 \leq r \leq r_1, c_0 \leq c \leq c_1), invert the color of (r, c) - that is, from white to black and vice versa.

Constraints

2 \leq H, W \leq 100

Input

Input is given from Standard Input in the following format:

H W
s_{11} s_{12} \cdots s_{1W}
s_{21} s_{22} \cdots s_{2W}
\vdots
s_{H1} s_{H2} \cdots s_{HW}

Here s_{rc} represents the color of (r, c) - # stands for black, and . stands for white.

Output

Print the minimum number of operations needed.

Sample Input 1

3 3
.##
.#.
##.

Sample Output 1

1

Do the operation with (r_0, c_0, r_1, c_1) = (2, 2, 2, 2) to change just the color of (2, 2), and we are done.

Sample Input 2

2 2
#.
.#

Sample Output 2

2

Sample Input 3

4 4
..##
#...
###.
###.

Sample Output 3

0

No operation may be needed.

Sample Input 4

5 5
.#.#.
#.#.#
.#.#.
#.#.#
.#.#.

Sample Output 4

4


import java.util.*;

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

        Scanner sc = new Scanner(System.in);
        int H = sc.nextInt();
        int W = sc.nextInt();
        int S= H*W;
        if(S%2==0){
            System.out.println(S/2);
        }else{
            System.out.println((S+1)/2);
        }

    }
}

Score : 200 points

Problem Statement

We have a board with H horizontal rows and W vertical columns of squares.
There is a bishop at the top-left square on this board.
How many squares can this bishop reach by zero or more movements?

Here the bishop can only move diagonally.
More formally, the bishop can move from the square at the r_1-th row (from the top) and the c_1-th column (from the left) to the square at the r_2-th row and the c_2-th column if and only if exactly one of the following holds:

r_1 + c_1 = r_2 + c_2

r_1 - c_1 = r_2 - c_2

For example, in the following figure, the bishop can move to any of the red squares in one move:

Constraints

1 \leq H, W \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H \ W

Output

Print the number of squares the bishop can reach.

Sample Input 1

4 5

Sample Output 1

10

The bishop can reach the cyan squares in the following figure:

Sample Input 2

7 3

Sample Output 2

11

The bishop can reach the cyan squares in the following figure:

Sample Input 3

1000000000 1000000000

Sample Output 3

500000000000000000


import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Long H = sc.nextLong();
        Long W = sc.nextLong();
        if(H*W%2==0)
          System.out.println(H*W/2);
        else
          System.out.println(H*W/2+1);
    }

}


import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long h=sc.nextLong();
        long w=sc.nextLong();
        if(h%2==0||w%2==0){
            System.out.println(h*w/2);
        }else{
            System.out.println((h*w+1)/2);
        }

    }

}


import java.io.*;
import java.util.*;
class Main{
	static final long MOD = 1_000_000_007; // 10^9+7
    static final int MAX = 2_147_483_646; // intMax
	static final int INF = 1_000_000_000; // 10^9
	static int n;
    public static void main(String[] args) throws Exception {
		hayami saori = new hayami();
		n = saori.saori_hayami();
		dfs(0,"");

		saori.close();
	}
	public static void dfs(int num, String str){
		if(str.length() == n){
			System.out.println(str);
			return;
		}
		String str2;
		for(char i = 0;i <= num;i++){
			str2 = str +  String.valueOf((char)('a' + i));
			dfs(Math.max(num, i+1), str2);
		}
	}
}

class hayami implements Closeable {
	private final InputStream in = System.in;
	private final byte[] hayami = new byte[1024];
	private int Hayami = 0;
	private int saori = 0;
	private boolean HayamiSaori() {
		if (Hayami < saori) {
			return true;
		}else{
			Hayami = 0;
			try {
				saori = in.read(hayami);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (saori <= 0) {
				return false;
			}
		}
		return true;
	}
	private int SaoriHayami() {
		if (HayamiSaori()) {
            return hayami[Hayami++];
         }else{
             return -1;
         }
	}
	private static boolean hayami_saori(int hayami) {
		return 33 <= hayami && hayami <= 126;
	}
	public boolean hayamisaori() {
		while(HayamiSaori() && !hayami_saori(hayami[Hayami])) Hayami++; return HayamiSaori();
	}
	public String nextHayami() {
		if (!hayamisaori()) throw new NoSuchElementException();
		StringBuilder hayamin = new StringBuilder();
		int saori = SaoriHayami();
		while(hayami_saori(saori)) {
			hayamin.appendCodePoint(saori);
			saori = SaoriHayami();
		}
		return hayamin.toString();
	}
	public long saorihayami() {//nextLong
		if (!hayamisaori()) throw new NoSuchElementException();
		long hayami = 0;
		boolean misao = false;
		int saori = SaoriHayami();
		if (saori == '-') {
			misao = true;
			saori = SaoriHayami();
		}
		if (saori < '0' || '9' < saori) {
			throw new NumberFormatException();
		}
		while(true){
			if ('0' <= saori && saori <= '9') {
				hayami *= 10;
				hayami += saori - '0';
			}else if(saori == -1 || !hayami_saori(saori)){
				return misao ? -hayami : hayami;
			}else{
				throw new NumberFormatException();
			}
			saori = SaoriHayami();
		}
	}
	public int saori_hayami() {//nextInt
		long hayami = saorihayami();
		if (hayami < Integer.MIN_VALUE || hayami > Integer.MAX_VALUE) throw new NumberFormatException();
		return (int) hayami;
	}
	public double Hayamin() { //nextDouble
		return Double.parseDouble(nextHayami());
	}
	public void close() {
		try {
			in.close();
		} catch (IOException e) {
		}
    }

}

Score : 400 points

Problem Statement

In this problem, we only consider strings consisting of lowercase English letters.

Strings s and t are said to be isomorphic when the following conditions are satisfied:

|s| = |t| holds.

For every pair i, j, one of the following holds:

s_i = s_j and t_i = t_j.

s_i \neq s_j and t_i \neq t_j.

For example, abcac and zyxzx are isomorphic, while abcac and ppppp are not.

A string s is said to be in normal form when the following condition is satisfied:

For every string t that is isomorphic to s, s \leq t holds. Here \leq denotes lexicographic comparison.

For example, abcac is in normal form, but zyxzx is not since it is isomorphic to abcac, which is lexicographically smaller than zyxzx.

You are given an integer N.
Print all strings of length N that are in normal form, in lexicographically ascending order.

Constraints

1 \leq N \leq 10

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Assume that there are K strings of length N that are in normal form: w_1, \ldots, w_K in lexicographical order.
Output should be in the following format:

w_1
:
w_K

Sample Input 1

1

Sample Output 1

a

Sample Input 2

2

Sample Output 2

aa
ab


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

public class Main {
	static int mod = (int) 1e9 + 7;
	static int DX[] = { -1, 0, 1, 0 }, DY[] = { 0, -1, 0, 1 };
	static final int INF = Integer.MAX_VALUE / 3;
	static final long LINF = Long.MAX_VALUE / 3;

	static char as[] = {'b','c','d','e','f','g','h','i','j','k','l','m','n'};
	static List<String> ls;
	static int n;
	public static void main(String[] args) {
		FastScanner fs = new FastScanner(System.in);
		n = fs.nextInt();
		ls = new ArrayList<>();
		dfs("", 0, 0);
		Collections.sort(ls);
		for(String tmp:ls) System.out.println(tmp);

	}
	static void dfs(String s, int cnt, int p) {
		String ns = "";
		if(p == 0)ns = s + "a";
		else ns = s + as[cnt++];
		if(ns.length()==n) {
			ls.add(ns);
			return;
		}
		dfs(ns, cnt, 0);
		dfs(ns, cnt, 1);
	}

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

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

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

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

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

//高速なScanner
class FastScanner {
	private BufferedReader reader = null;
	private StringTokenizer tokenizer = null;

	public FastScanner(InputStream in) {
		reader = new BufferedReader(new InputStreamReader(in));
		tokenizer = null;
	}

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

	public String nextLine() {
		if (tokenizer == null || !tokenizer.hasMoreTokens()) {
			try {
				return reader.readLine();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		return tokenizer.nextToken("\n");
	}

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

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

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

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

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


import java.util.Scanner;
public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String S = sc.next();
        //System.out.print(S);
        if(S.equals("hi")||S.equals("hihi")||S.equals("hihihi")||S.equals("hihihihi")||S.equals("hihihihihi")){
            System.out.print("Yes");
        }else{
            System.out.print("No");
        }
    }
}

Score : 100 points

Problem Statement

A Hitachi string is a concatenation of one or more copies of the string hi.

For example, hi and hihi are Hitachi strings, while ha and hii are not.

Given a string S, determine whether S is a Hitachi string.

Constraints

The length of S is between 1 and 10 (inclusive).

S is a string consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S is a Hitachi string, print Yes; otherwise, print No.

Sample Input 1

hihi

Sample Output 1

Yes

hihi is the concatenation of two copies of hi, so it is a Hitachi string.

Sample Input 2

hi

Sample Output 2

Yes

Sample Input 3

ha

Sample Output 3

No


import javax.sound.midi.Soundbank;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Long N, A, B;
        Scanner sc = new Scanner(System.in);
        N = sc.nextLong();
        A = sc.nextLong();
        B = sc.nextLong();
        Long N2 = N%(A+B);
        Long N1 = N/(A+B);
        System.out.println(A*N1 + (N2 >= A ? A : N2) );
    }
}

Score : 200 points

Problem Statement

Takahashi has many red balls and blue balls. Now, he will place them in a row.

Initially, there is no ball placed.

Takahashi, who is very patient, will do the following operation 10^{100} times:

Place A blue balls at the end of the row of balls already placed. Then, place B red balls at the end of the row.

How many blue balls will be there among the first N balls in the row of balls made this way?

Constraints

1 \leq N \leq 10^{18}

A, B \geq 0

0 < A + B \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the number of blue balls that will be there among the first N balls in the row of balls.

Sample Input 1

8 3 4

Sample Output 1

4

Let b denote a blue ball, and r denote a red ball. The first eight balls in the row will be bbbrrrrb, among which there are four blue balls.

Sample Input 2

8 0 4

Sample Output 2

0

He placed only red balls from the beginning.

Sample Input 3

6 2 4

Sample Output 3

2

Among bbrrrr, there are two blue balls.


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int a = sc.nextInt(); // 青のボール
        int b = sc.nextInt();
        String balls = "";
        String flg = "a";

        while(balls.length() <= n){
            if(flg.equals("a")){
                for(int i=0; i<a; i++){
                    balls += "a";
                }
                flg = "b";
            }
            else{
                for(int i=0; i<b; i++){
                    balls += "b";
                }
                flg = "a";
            }
        }

        balls = balls.substring(0, n+1);

        int ans = 0;
        for(int i=0; i<n; i++){
            if(balls.charAt(i) == 'a'){
                ans++;
            }
        }

        System.out.println(ans);
    }
}


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Scanner;

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

		ArrayList<BigDecimal> arrayA = new ArrayList<>(10);
		ArrayList<BigDecimal> arrayB = new ArrayList<>(10);
		for(BigDecimal i = BigDecimal.ZERO; i.compareTo(BigDecimal.ONE) < 0; i = i.add(BigDecimal.valueOf(0.1))) {
			arrayA.add(BigDecimal.valueOf(A).add(i).divide(BigDecimal.valueOf(0.08)));
			arrayB.add(BigDecimal.valueOf(B).add(i).divide(BigDecimal.valueOf(0.10)));
		}

		boolean isNotExists = true;
		start : for(BigDecimal a : arrayA) {
			if(a.compareTo(a.setScale(0)) != 0) {
				continue;
			}
			for(BigDecimal b : arrayB) {
				if(b.compareTo(b.setScale(0)) != 0) {
					continue;
				}
				if(a.compareTo(b) == 0) {
					isNotExists = false;
					System.out.println(a.intValue());
					break start;
				}
			}
		}
		if(isNotExists) {
			System.out.println(-1);
		}

	}
}

Score : 300 points

Problem Statement

Find the price of a product before tax such that, when the consumption tax rate is 8 percent and 10 percent, the amount of consumption tax levied on it is A yen and B yen, respectively. (Yen is the currency of Japan.)

Here, the price before tax must be a positive integer, and the amount of consumption tax is rounded down to the nearest integer.

If multiple prices satisfy the condition, print the lowest such price; if no price satisfies the condition, print -1.

Constraints

1 \leq A \leq B \leq 100

A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

If there is a price that satisfies the condition, print an integer representing the lowest such price; otherwise, print -1.

Sample Input 1

2 2

Sample Output 1

25

If the price of a product before tax is 25 yen, the amount of consumption tax levied on it is:

When the consumption tax rate is 8 percent: \lfloor 25 \times 0.08 \rfloor = \lfloor 2 \rfloor = 2 yen.

When the consumption tax rate is 10 percent: \lfloor 25 \times 0.1 \rfloor = \lfloor 2.5 \rfloor = 2 yen.

Thus, the price of 25 yen satisfies the condition. There are other possible prices, such as 26 yen, but print the minimum such price, 25.

Sample Input 2

8 10

Sample Output 2

100

If the price of a product before tax is 100 yen, the amount of consumption tax levied on it is:

When the consumption tax rate is 8 percent: \lfloor 100 \times 0.08 \rfloor = 8 yen.

When the consumption tax rate is 10 percent: \lfloor 100 \times 0.1 \rfloor = 10 yen.

Sample Input 3

19 99

Sample Output 3

-1

There is no price before tax satisfying this condition, so print -1.


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

public class Main {
	public static void main(String[] args) {
		FastScanner sc = new FastScanner(System.in);
		String s = sc.next();
		char[] a = s.toCharArray();
		int q = sc.nextInt();
		int check = 0;
		ArrayList<String> front = new ArrayList<>(),
							back = new ArrayList<>();
		if(s.length() == 1) {
			front.add(s);
		}else {
			front.add(String.valueOf(a[0]));
			for(int i = 1; i < a.length; i++) {
				back.add(String.valueOf(a[i]));
			}
		}
		for(int i = 0; i < q; i++) {
			int t = sc.nextInt();
			if(t == 1) {
				check++;
			}else{
				int f = sc.nextInt();
				String x = sc.next();
				if((f== 1 && check % 2 == 0) || (f == 2 && check % 2 != 0)) {
					front.add(x);
				}else {
					back.add(x);
				}
			}
		}
		if(check % 2 == 0) {
			for(int i = front.size()-1; i >= 0; i--) {
				System.out.print(front.get(i));
			}
			for(String st : back) {
				System.out.print(st);
			}
		}else {
			for(int i = back.size()-1; i >= 0; i--) {
				System.out.print(back.get(i));
			}
			for(String st : front) {
				System.out.print(st);
			}
		}
	}

	static class FastScanner {
		private BufferedReader reader = null;
	    private StringTokenizer tokenizer = null;
	    public FastScanner(InputStream in) {
	        reader = new BufferedReader(new InputStreamReader(in));
	        tokenizer = null;
	    }

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

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

	        return tokenizer.nextToken("\n");
	    }

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

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

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

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

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

Score : 400 points

Problem Statement

Takahashi has a string S consisting of lowercase English letters.

Starting with this string, he will produce a new one in the procedure given as follows.

The procedure consists of Q operations. In Operation i (1 \leq i \leq Q), an integer T_i is provided, which means the following:

If T_i = 1: reverse the string S.

If T_i = 2: An integer F_i and a lowercase English letter C_i are additionally provided.

If F_i = 1 : Add C_i to the beginning of the string S.

If F_i = 2 : Add C_i to the end of the string S.

Help Takahashi by finding the final string that results from the procedure.

Constraints

1 \leq |S| \leq 10^5

S consists of lowercase English letters.

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

T_i = 1 or 2.

F_i = 1 or 2, if provided.

C_i is a lowercase English letter, if provided.

Input

Input is given from Standard Input in the following format:

S
Q
Query_1
:
Query_Q

In the 3-rd through the (Q+2)-th lines, Query_i is one of the following:

1

which means T_i = 1, and:

2 F_i C_i

which means T_i = 2.

Output

Print the resulting string.

Sample Input 1

a
4
2 1 p
1
2 2 c
1

Sample Output 1

cpa

There will be Q = 4 operations. Initially, S is a.

Operation 1: Add p at the beginning of S. S becomes pa.

Operation 2: Reverse S. S becomes ap.

Operation 3: Add c at the end of S. S becomes apc.

Operation 4: Reverse S. S becomes cpa.

Thus, the resulting string is cpa.

Sample Input 2

a
6
2 2 a
2 1 b
1
2 2 c
1
1

Sample Output 2

aabc

There will be Q = 6 operations. Initially, S is a.

Operation 1: S becomes aa.

Operation 2: S becomes baa.

Operation 3: S becomes aab.

Operation 4: S becomes aabc.

Operation 5: S becomes cbaa.

Operation 6: S becomes aabc.

Thus, the resulting string is aabc.

Sample Input 3

y
1
2 1 x

Sample Output 3

xy


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

public class Main {

	public static void main(String[] args) {
//		executeCountBalls();
//		executeTaxIncrease();
		executeStringFormation();
	}

	private static void execute() {

		Scanner in = new Scanner(System.in);

		try {
			String s1 = in.nextLine();
			String s2 = in.nextLine();
			String s3 = in.nextLine();

			int  a = Integer.parseInt(s1);
			String[] s2Array = s2.split(" ");
			int b = Integer.parseInt(s2Array[0]);
			int c = Integer.parseInt(s2Array[1]);

			int sum  = a + b + c;

//			System.out.println(a + "," + b + "," + c );

			System.out.println(sum + " " + s3);
		} catch (NumberFormatException e) {
			// TODO 自動生成された catch ブロック
			System.out.println("");
//			e.printStackTrace();
		}

	}

	public static void execute_product() {

		Scanner in = new Scanner(System.in);

		try {
			int a  = in.nextInt();
			int b  = in.nextInt();

			if( (a*b)%2 == 0 ) {
				System.out.println("Even");
			} else {
				System.out.println("Odd");
			}
		} catch (Exception e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}
	}

	public static void executeCountBalls() {
		Scanner in = new Scanner(System.in);

		try {
			long N = in.nextLong();
			long A = in.nextLong();
			long B = in.nextLong();

			long surplus = N%(A+B);
			long surplusA = surplus >= A ? A : surplus;

			 long countA = N/(A+B) * A + surplusA;

			System.out.println(countA);
		} catch (Exception e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}
	}

	public static final int TAX_RATE_8 = 8;
	public static final int TAX_TATE_10 = 10;

	public static void executeTaxIncrease(){

		Scanner in = new Scanner(System.in);

		double tax8 = (double)in.nextInt();
		double tax10 = (double)in.nextInt();

		int taxExclude_min = (int)Math.ceil((tax8 * 100)/TAX_RATE_8);

		int taxExclude_max = 0;
		if( ((tax8 + 1)*100)%8 == 0 ) {
			taxExclude_max = (int)(((tax8 + 1) * 100)/TAX_RATE_8 - 1);
		}	else {
			taxExclude_max = (int)Math.floor(((tax8 + 1) * 100)/TAX_RATE_8);
		}

//		System.out.println(taxExclude_min + " " + taxExclude_max);

		int taxExclude_fix = -1;
		for( int val = taxExclude_min; val <= taxExclude_max; val++) {
			if ( (int)Math.ceil(val/TAX_TATE_10) == tax10 ) {
				taxExclude_fix = val;
				break;
			}
		}
		System.out.println(taxExclude_fix);
	}

	private static final int ENTRY_HEAD = 0x0;
	private static final int ENTRY_TAIL = 0xFFFFFFFF;
	private static int headFlag = ENTRY_HEAD;

	public static void executeStringFormation() {

//long start = System.currentTimeMillis();

		String s1 = null;
		String s2 = null;
		int num = 0;
		List<String> queryList = new ArrayList<String>();

		if( false ) {
			Scanner in = new Scanner(System.in);

			s1 = in.nextLine();
			s2 = in.nextLine();
			num =Integer.parseInt(s2);

			for(  int i=0; i<num; i++ ) {
				queryList.add(in.nextLine());
			}

		} else {

			try {

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

				s1 = stdin.readLine();
				s2 = stdin.readLine();
				num = Integer.parseInt(s2);

				for(int i = 0;i<num;i++) {
					queryList.add(stdin.readLine());
				}
			} catch (NumberFormatException e) {
				// TODO 自動生成された catch ブロック
				e.printStackTrace();
			} catch (IOException e) {
				// TODO 自動生成された catch ブロック
				e.printStackTrace();
			}
		}
//long p1 = System.currentTimeMillis();

		StringBuilder sbHeader = new StringBuilder();
		StringBuilder sbTail = new StringBuilder();
		StringBuilder sbMiddle = new StringBuilder();
		sbMiddle.append(s1);

		StringBuilder sbMerged = new StringBuilder();

		for( int i=0; i<num; i++ ) {
			String query = queryList.get(i);

			String[] queryArray = query.split(" ");
			if( "1".equals(queryArray[0]) ) {
				// 反転
				exchange(~headFlag);

			} else if( "2".equals(queryArray[0]) ) {
				// 追加

				if( "1".equals(queryArray[1] )) {
					// 先頭追加
					if(  headFlag == ENTRY_HEAD) {
						addString(sbHeader, queryArray[2]);
					} else {
						addString(sbTail, queryArray[2]);
					}

				} else if( "2".equals(queryArray[1])) {
					// 末尾追加
					if( headFlag == ENTRY_HEAD ) {
						addString(sbTail, queryArray[2]);
					} else {
						addString(sbHeader, queryArray[2]);
					}
				} else {
					;
				}
			} else {
				;
			}
		}

//long p2 = System.currentTimeMillis();
		// 結合処理
		if( headFlag == ENTRY_HEAD ) {
		    sbMerged.append(sbHeader.reverse());
		    sbMerged.append(sbMiddle);
		    sbMerged.append(sbTail);
		} else {
			sbMerged.append(sbTail.reverse());
			sbMerged.append(sbMiddle.reverse());
			sbMerged.append(sbHeader);
		}

//		System.out.println(sb.toString());
		try {
			PrintWriter pw = new PrintWriter(System.out);
//			PrintWriter pw = new PrintWriter("output.txt");
			String str = sbMerged.toString();
			pw.println(str);

//			long end = System.currentTimeMillis();

//			pw.println("start-end " + (end-start) + "ms");
//			pw.println("start-p1 " + (p1-start) + "ms");
//			pw.println("p1-p2 " + (p2-p1) + "ms");
//			pw.println("p2-end " + (end-p2) + "ms");

			pw.flush();
			pw.close();

		} catch (Exception e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}

	}

	private static void exchange(int entry){
		headFlag = entry;
	}

	private static void addString(StringBuilder sbuilder, String c) {
		sbuilder.append(c);
	}

}


import java.util.*;

class Main{
    public static void main(String[] args){
        final Scanner sc = new Scanner(System.in);
        char[] s = sc.next().toCharArray();
        LinkedList<Character> list = new LinkedList<>();
        for(int i = 0; i < s.length; i++){
            list.add(s[i]);
        }
        int q = sc.nextInt();
        int dir = 0;
        for(int i = 0; i < q; i++){
            int op = sc.nextInt();
            if(op == 1){
                dir++;
            }else{
                int end = sc.nextInt();
                char let = sc.next().charAt(0);
                if((dir + end) % 2 == 0){
                    list.add(let);
                }else{
                    list.add(0, let);
                }
            }
        }
        if(dir % 2 == 0){
            for(int i = 0; i < list.size(); i++){
                System.out.print(list.toArray()[i]);
            }
        }else{
            for(int i = 0; i < list.size(); i++){
                System.out.print(list.toArray()[list.size() - 1 - i]);
            }
        }
    }
}


import java.io.*;
import java.util.*;
class Main{
	static final long MOD = 1_000_000_007; // 10^9+7
    static final int MAX = 2_147_483_646; // intMax
    static final int INF = 1_000_000_000; // 10^9
    public static void main(String[] args) throws Exception {
		hayami saori = new hayami();
		String s = saori.nextHayami();
		String[] s2 = s.split("");
		int q = saori.saori_hayami();
		String[][] sousa = new String[q][3];
		int t = 0;
		int f = 0;
		String str ="";
		String ans = s;
		String ans2 = s;
		int rev = 0;
		int[] flg = new int[q];
		for(int i = 0;i < q;i++){
			t = saori.saori_hayami();
			if(t == 1){
				sousa[i][0] = "hayami";
			} else {
				f = saori.saori_hayami();
				str = saori.nextHayami();
				sousa[i][f] = str;
				sousa[i][0] = "";
				flg[i] = f;
			}
			if(sousa[i][0].equals("hayami")){
				rev++;
			} else {
				if(flg[i] == 2){

					ans2 = sousa[i][2] + ans2;
					if(rev%2 == 0){
						ans = ans + sousa[i][2];
						ans2 = sousa[i][2] + ans2;
					} else {
						ans = sousa[i][2] + ans;
						ans2 = ans2 + sousa[i][2];
					}
				} else {
					ans2 = sousa[i][1] + ans;
					if(rev%2 == 0){
						ans = sousa[i][1] + ans;
						ans2 =ans2 + sousa[i][1];
					} else {
						ans =ans + sousa[i][1];
						ans2 = sousa[i][1] + ans2;
					}
				}
			}
		}
		if(rev%2 == 0){
			System.out.println(ans);
		} else {
			System.out.println(ans2);
		}
		saori.close();
    }
}

class hayami implements Closeable {
	private final InputStream in = System.in;
	private final byte[] hayami = new byte[1024];
	private int Hayami = 0;
	private int saori = 0;
	private boolean HayamiSaori() {
		if (Hayami < saori) {
			return true;
		}else{
			Hayami = 0;
			try {
				saori = in.read(hayami);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (saori <= 0) {
				return false;
			}
		}
		return true;
	}
	private int SaoriHayami() {
		if (HayamiSaori()) {
            return hayami[Hayami++];
         }else{
             return -1;
         }
	}
	private static boolean hayami_saori(int hayami) {
		return 33 <= hayami && hayami <= 126;
	}
	public boolean hayamisaori() {
		while(HayamiSaori() && !hayami_saori(hayami[Hayami])) Hayami++; return HayamiSaori();
	}
	public String nextHayami() {
		if (!hayamisaori()) throw new NoSuchElementException();
		StringBuilder hayamin = new StringBuilder();
		int saori = SaoriHayami();
		while(hayami_saori(saori)) {
			hayamin.appendCodePoint(saori);
			saori = SaoriHayami();
		}
		return hayamin.toString();
	}
	public long saorihayami() {//nextLong
		if (!hayamisaori()) throw new NoSuchElementException();
		long hayami = 0;
		boolean misao = false;
		int saori = SaoriHayami();
		if (saori == '-') {
			misao = true;
			saori = SaoriHayami();
		}
		if (saori < '0' || '9' < saori) {
			throw new NumberFormatException();
		}
		while(true){
			if ('0' <= saori && saori <= '9') {
				hayami *= 10;
				hayami += saori - '0';
			}else if(saori == -1 || !hayami_saori(saori)){
				return misao ? -hayami : hayami;
			}else{
				throw new NumberFormatException();
			}
			saori = SaoriHayami();
		}
	}
	public int saori_hayami() {//nextInt
		long hayami = saorihayami();
		if (hayami < Integer.MIN_VALUE || hayami > Integer.MAX_VALUE) throw new NumberFormatException();
		return (int) hayami;
	}
	public double Hayamin() { //nextDouble
		return Double.parseDouble(nextHayami());
	}
	public void close() {
		try {
			in.close();
		} catch (IOException e) {
		}
    }

}


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s = sc.next();
		int n = sc.nextInt();
		boolean reverse = false;
		StringBuilder sb = new StringBuilder(s);
		for (int i = 0; i < n; i++) {
			int q = sc.nextInt();
			if(q == 1) {
				reverse = !reverse;
			} else {
				int q2 = sc.nextInt();
				if((!reverse && q2 == 1) || (reverse && q2 == 2)) {
					sb.insert(0, sc.next());
				} else {
					sb.append(sc.next());
				}
			}
		}
		if(reverse) sb.reverse();
		System.out.println(sb.toString());
	}
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.Reader;
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;
        MyInput in = new MyInput(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        EDivisibleSubstring solver = new EDivisibleSubstring();
        solver.solve(1, in, out);
        out.close();
    }

    static class EDivisibleSubstring {
        public void solve(int testNumber, MyInput in, PrintWriter out) {
            int n = in.nextInt();
            int p = in.nextInt();

            int[] mod1 = new int[p];
            char[] s = in.nextChars();
            int v = 0;
            int iv = (int) inverseModPrime(10, p);
            long ans = 0;
            int[] mod2 = new int[p];
            for (int i = 0; i < n; i++) {
                v = (v * 10 + s[i] - '0') % p;
                if (p <= 50) {
                    Arrays.fill(mod2, 0);
                    for (int j = 0; j < p; j++) {
                        mod2[j * 10 % p] += mod1[j];
                    }
                    int[] tmp = mod1;
                    mod1 = mod2;
                    mod2 = tmp;
                    ans += mod1[v];
                    if (v == 0) ans++;
                    mod1[v]++;
                } else {
                    ans += mod1[iv * v % p];
                    if (v == 0) ans++;
                    mod1[iv * v % p]++;
                }
            }
            out.println(ans);
        }

        static long powmod(long n, long r, int m) {
            long res = 1;
            for (; r != 0; r >>>= 1, n = n * n % m) {
                if ((r & 1) == 1) {
                    res = res * n;
                    if (res >= m) {
                        res %= m;
                    }
                }
            }
            return res;
        }

        static long inverseModPrime(long n, int p) {
            return powmod(n, p - 2, p);
        }

    }

    static class MyInput {
        private final BufferedReader in;
        private static int pos;
        private static int readLen;
        private static final char[] buffer = new char[1024 * 8];
        private static char[] str = new char[500 * 8 * 2];
        private static boolean[] isDigit = new boolean[256];
        private static boolean[] isSpace = new boolean[256];
        private static boolean[] isLineSep = new boolean[256];

        static {
            for (int i = 0; i < 10; i++) {
                isDigit['0' + i] = true;
            }
            isDigit['-'] = true;
            isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true;
            isLineSep['\r'] = isLineSep['\n'] = true;
        }

        public MyInput(InputStream is) {
            in = new BufferedReader(new InputStreamReader(is));
        }

        public int read() {
            if (pos >= readLen) {
                pos = 0;
                try {
                    readLen = in.read(buffer);
                } catch (IOException e) {
                    throw new RuntimeException();
                }
                if (readLen <= 0) {
                    throw new MyInput.EndOfFileRuntimeException();
                }
            }
            return buffer[pos++];
        }

        public int nextInt() {
            int len = 0;
            str[len++] = nextChar();
            len = reads(len, isSpace);
            int i = 0;
            int ret = 0;
            if (str[0] == '-') {
                i = 1;
            }
            for (; i < len; i++) ret = ret * 10 + str[i] - '0';
            if (str[0] == '-') {
                ret = -ret;
            }
            return ret;
        }

        public char nextChar() {
            while (true) {
                final int c = read();
                if (!isSpace[c]) {
                    return (char) c;
                }
            }
        }

        int reads(int len, boolean[] accept) {
            try {
                while (true) {
                    final int c = read();
                    if (accept[c]) {
                        break;
                    }
                    if (str.length == len) {
                        char[] rep = new char[str.length * 3 / 2];
                        System.arraycopy(str, 0, rep, 0, str.length);
                        str = rep;
                    }
                    str[len++] = (char) c;
                }
            } catch (MyInput.EndOfFileRuntimeException e) {
            }
            return len;
        }

        public char[] nextChars() {
            int len = 0;
            str[len++] = nextChar();
            len = reads(len, isSpace);
            return Arrays.copyOf(str, len);
        }

        static class EndOfFileRuntimeException extends RuntimeException {
        }

    }
}

Score : 500 points

Problem Statement

Takahashi has a string S of length N consisting of digits from 0 through 9.

He loves the prime number P. He wants to know how many non-empty (contiguous) substrings of S - there are N \times (N + 1) / 2 of them - are divisible by P when regarded as integers written in base ten.

Here substrings starting with a 0 also count, and substrings originated from different positions in S are distinguished, even if they are equal as strings or integers.

Compute this count to help Takahashi.

Constraints

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

S consists of digits.

|S| = N

2 \leq P \leq 10000

P is a prime number.

Input

Input is given from Standard Input in the following format:

N P
S

Output

Print the number of non-empty (contiguous) substrings of S that are divisible by P when regarded as an integer written in base ten.

Sample Input 1

4 3
3543

Sample Output 1

6

Here S = 3543. There are ten non-empty (contiguous) substrings of S:

3: divisible by 3.

35: not divisible by 3.

354: divisible by 3.

3543: divisible by 3.

5: not divisible by 3.

54: divisible by 3.

543: divisible by 3.

4: not divisible by 3.

43: not divisible by 3.

3: divisible by 3.

Six of these are divisible by 3, so print 6.

Sample Input 2

4 2
2020

Sample Output 2

10

Here S = 2020. There are ten non-empty (contiguous) substrings of S, all of which are divisible by 2, so print 10.

Note that substrings beginning with a 0 also count.

Sample Input 3

20 11
33883322005544116655

Sample Output 3

68


import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int a = sc.nextInt();
		System.out.println(a % 2 == 0 ? a / 2 : a / 2 + 1 );
	}
}

Score : 100 points

Problem Statement

Takahashi wants to print a document with N pages double-sided, where two pages of data can be printed on one sheet of paper.

At least how many sheets of paper does he need?

Constraints

N is an integer.

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

5

Sample Output 1

3

By printing the 1-st, 2-nd pages on the 1-st sheet, 3-rd and 4-th pages on the 2-nd sheet, and 5-th page on the 3-rd sheet, we can print all the data on 3 sheets of paper.

Sample Input 2

2

Sample Output 2

1

Sample Input 3

100

Sample Output 3

50


import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;

public class Main {
	public static void main(String args[]) throws IOException {
		FastScanner fs = new FastScanner();
		double  page = fs.nextInt();
		System.out.println((int)Math.ceil(page / 2) );
	}
}

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.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int p = n / 2;
        if(n % 2 == 1){
            p ++;
        }
        System.out.println(p);
    }
}


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 = "";
    static List<Integer>[] g;
    static int[] group;
    static int[] size;
    static int id;
    static int count;

    static void solve() {
        int n = ni();
        int m = ni();
        int k = ni();

        g = new List[n];
        group = new int[n];
        size = new int[n];
        int[][] block = new int[k][2];

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

        for (int i = 0; i < m; i++) {
            int a = ni() - 1;
            int b = ni() - 1;
            g[a].add(b);
            g[b].add(a);
        }

        for (int i = 0; i < k; i++) {
            block[i][0] = ni() - 1;
            block[i][1] = ni() - 1;
        }

        Arrays.fill(group, -1);
        id = 0;
        for (int i = 0; i < n; i++) {
            if (group[i] == -1) {
                count = 0;
                dfs(i);
                size[id] = count;
                id++;
            }
        }

        int[] ans = new int[n];
        for (int i = 0; i < n; i++) {
            ans[i] = size[group[i]] - 1 - g[i].size();
        }

        for (int i = 0; i < k; i++) {
            int c = block[i][0];
            int d = block[i][1];
            if (group[c] == group[d]) {
                ans[c]--;
                ans[d]--;
            }
        }

        for (int i = 0; i < n; i++) {
            out.print(ans[i]);
            out.print((i == n - 1)? "" : " ");
        }

        out.println();
    }

    public static void dfs(int v) {
        group[v] = id;
        count++;
        for (int u : g[v]) {
            if (group[u] == -1) {
                dfs(u);
            }
        }
    }

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

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

    // Union-Find
    // https://algs4.cs.princeton.edu/15uf/UF.java.html
    public static class UnionFind {
        private int count = 0;
        private int[] parent, rank;

        public UnionFind(int n) {
            count = n;
            parent = new int[n];
            rank = new int[n];
            for (int i = 0; i < n; i++) {
                parent[i] = i;
            }
        }

        public int find(int p) {
            while (p != parent[p]) {
                parent[p] = parent[parent[p]];
                p = parent[p];
            }
            return p;
        }

        public void union(int p, int q) {
            int rootP = find(p);
            int rootQ = find(q);
            if (rootP ==rootQ) return;
            if (rank[rootQ] > rank[rootP]) {
                parent[rootP] = rootQ;
            } else {
                parent[rootQ] = rootP;
                if (rank[rootP] == rank[rootQ]) {
                    rank[rootP]++;
                }
            }
            count--;
        }

        public int count() {
            return count;
        }

        public void print() {
            out.println("Parent:");
            for (int i : parent) {
                out.print(i);
                out.print(" ");
            }
            out.println();
            out.println("Rank:");
            for (int i : rank) {
                out.print(i);
                out.print(" ");
            }
            out.println();
        }
    }

    // Dijkstra
    // Return min distance from start to end O(ElogV) (negative cost is prohibited)
    // edge is int[3] array {from,to,cost}
    // edges is edge list from specific node
    // all_edges is Map<from node number,edges>
    static int dijkstra(Map<Integer,List<int[]>> all_edges,int start,int end,int max_node_number) {
        int[] distance = new int[max_node_number + 1];
        Arrays.fill(distance, -1);
        PriorityQueue<int[]> p_que = new PriorityQueue<>((a,b) -> ((distance[a[0]] + a[2]) - (distance[b[0]] + b[2])));
        distance[start] = 0;
        List<int[]> edges = all_edges.get(start);
        p_que.addAll(edges);
        while (distance[end] < 0) {
            int[] nearest_edge = p_que.poll();
            assert nearest_edge != null;
            if (distance[nearest_edge[1]] < 0) {
                distance[nearest_edge[1]] = distance[nearest_edge[0]] + nearest_edge[2];
                if (all_edges.containsKey(nearest_edge[1])) {
                    edges = all_edges.get(nearest_edge[1]);
                    for (int[] edge : edges) {
                        if (distance[edge[1]] < 0) p_que.add(edge);
                    }
                }
            }
        }
        return distance[end];
    }

    // Enumerate primes in [2, n] with O(n log log n)
    public static List<Integer> sieveOfEratosthenes(int n) {
        boolean[] isPrime = new boolean[n+1];
        Arrays.fill(isPrime, true);
        for (int i = 2; i * i <= n; i++) {
            if (isPrime[i]) {
                for (int j = i + i; j <= n; j += i) {
                    isPrime[j] = false;
                }
            }
        }
        List<Integer> primes = new ArrayList<>();
        for (int i = 2; i <= n; i++) {
            if (isPrime[i]) {
                primes.add(i);
            }
        }
        return primes;
    }

    // Count divisor
    public static int countDivisor(int n) {
        int[] list = new int[n + 1];
        Arrays.fill(list, 0);
        int num = n;
        for (int i = 2; i <= n; i++) {
            while (num % i == 0) {
                list[i] = list[i] + 1;
                num /= i;
            }
        }
        int ans = 1;
        for (int i : list) {
            ans *= (i + 1);
        }
        return ans;
    }
}

Score : 400 points

Problem Statement

An SNS has N users - User 1, User 2, \cdots, User N.

Between these N users, there are some relationships - M friendships and K blockships.

For each i = 1, 2, \cdots, M, there is a bidirectional friendship between User A_i and User B_i.

For each i = 1, 2, \cdots, K, there is a bidirectional blockship between User C_i and User D_i.

We define User a to be a friend candidate for User b when all of the following four conditions are satisfied:

a \neq b.

There is not a friendship between User a and User b.

There is not a blockship between User a and User b.

There exists a sequence c_0, c_1, c_2, \cdots, c_L consisting of integers between 1 and N (inclusive) such that c_0 = a, c_L = b, and there is a friendship between User c_i and c_{i+1} for each i = 0, 1, \cdots, L - 1.

For each user i = 1, 2, ... N, how many friend candidates does it have?

Constraints

All values in input are integers.

2 ≤ N ≤ 10^5

0 \leq M \leq 10^5

0 \leq K \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

1 \leq C_i, D_i \leq N

C_i \neq D_i

(A_i, B_i) \neq (A_j, B_j) (i \neq j)

(A_i, B_i) \neq (B_j, A_j)

(C_i, D_i) \neq (C_j, D_j) (i \neq j)

(C_i, D_i) \neq (D_j, C_j)

(A_i, B_i) \neq (C_j, D_j)

(A_i, B_i) \neq (D_j, C_j)

Input

Input is given from Standard Input in the following format:

N M K
A_1 B_1
\vdots
A_M B_M
C_1 D_1
\vdots
C_K D_K

Output

Print the answers in order, with space in between.

Sample Input 1

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

Sample Output 1

0 1 0 1

There is a friendship between User 2 and 3, and between 3 and 4. Also, there is no friendship or blockship between User 2 and 4. Thus, User 4 is a friend candidate for User 2.

However, neither User 1 or 3 is a friend candidate for User 2, so User 2 has one friend candidate.

Sample Input 2

5 10 0
1 2
1 3
1 4
1 5
3 2
2 4
2 5
4 3
5 3
4 5

Sample Output 2

0 0 0 0 0

Everyone is a friend of everyone else and has no friend candidate.

Sample Input 3

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

Sample Output 3

1 3 5 4 3 3 3 3 1 0


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

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int N = sc.nextInt();
    int M = sc.nextInt();
    int K = sc.nextInt();
    int[] A = new int[M];
    int[] B = new int[M];
    for (int i = 0; i < M; i++) {
      A[i] = sc.nextInt();
      B[i] = sc.nextInt();
    }
    int[] C = new int[K];
    int[] D = new int[K];
    for (int i = 0; i < K; i++) {
      C[i] = sc.nextInt();
      D[i] = sc.nextInt();
    }
    sc.close();

    int[] fc = new int[N + 1];
    @SuppressWarnings("unchecked")
    List<Integer>[] g = new List[N + 1];
    int[] gn = new int[N + 1];
    for (int i = 0; i < M; i++) {
      int a = A[i];
      int b = B[i];
      fc[a]++;
      fc[b]++;

      if (gn[a] == 0 && gn[b] == 0) {
        List<Integer> set = new ArrayList<>();
        set.add(a);
        set.add(b);
        gn[a] = a;
        gn[b] = a;
        g[a] = set;
      } else if (gn[a] == 0) {
        List<Integer> set = g[gn[b]];
        set.add(a);
        gn[a] = gn[b];
      } else if (gn[b] == 0) {
        List<Integer> set = g[gn[a]];
        set.add(b);
        gn[b] = gn[a];
      } else if (g[gn[a]] != g[gn[b]]) {
        List<Integer> setL = g[gn[a]];
        List<Integer> setS = g[gn[b]];
        int s = b;
        if (setL.size() < setS.size()) {
          List<Integer> temp = setL;
          setL = setS;
          setS = temp;
          s = a;
        }
        setL.addAll(setS);
        g[gn[s]] = setL;
      }
    }

    int[] bc = new int[N + 1];
    for (int i = 0; i < K; i++) {
      int c = C[i];
      int d = D[i];
      if (g[gn[c]] == g[gn[d]]) {
        bc[c]++;
        bc[d]++;
      }
    }

    int[] ans = new int[N + 1];
    for (int i = 1; i < N + 1; i++)
      if (g[gn[i]] != null)
        ans[i] = g[gn[i]].size() - 1 - fc[i] - bc[i];

    StringBuilder buf = new StringBuilder();
    for (int i = 1; i < N + 1; i++)
      buf.append(ans[i]).append(' ');
    System.out.println(buf);
  }
}


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

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int N = sc.nextInt();
    int M = sc.nextInt();
    int K = sc.nextInt();
    /*
    int[] A = new int[M];
    int[] B = new int[M];
    for (int i = 0; i < M; i++) {
      A[i] = sc.nextInt();
      B[i] = sc.nextInt();
    }
    int[] C = new int[K];
    int[] D = new int[K];
    for (int i = 0; i < K; i++) {
      C[i] = sc.nextInt();
      D[i] = sc.nextInt();
    }
    sc.close();
    */

    @SuppressWarnings("unchecked")
    Set<Integer>[] g = new Set[N + 1];
    int[] fc = new int[N + 1];
    for (int i = 0; i < M; i++) {
      int a = sc.nextInt();
      int b = sc.nextInt();
      if (g[a] == null && g[b] == null) {
        Set<Integer> set = new HashSet<>();
        set.add(a);
        set.add(b);
        g[a] = set;
        g[b] = set;
      } else if (g[a] == null) {
        Set<Integer> set = g[b];
        set.add(a);
        g[a] = set;
      } else if (g[b] == null) {
        Set<Integer> set = g[a];
        set.add(b);
        g[b] = set;
      } else if (g[a] != g[b]) {
        Set<Integer> setL = g[a];
        Set<Integer> setS = g[b];
        if (setL.size() < setS.size()) {
          Set<Integer> temp = setL;
          setL = setS;
          setS = temp;
        }
        setL.addAll(setS);
        for (int c : setS) g[c] = setL;
      }
      fc[a]++;
      fc[b]++;
    }

    int[] bc = new int[N + 1];
    for (int i = 0; i < K; i++) {
      int c = sc.nextInt();
      int d = sc.nextInt();
      if (g[c] == g[d]) {
        bc[c]++;
        bc[d]++;
      }
    }
    sc.close();

    int[] ans = new int[N + 1];
    for (int i = 1; i < N + 1; i++)
      if (g[i] != null)
        ans[i] = g[i].size() - 1 - fc[i] - bc[i];

    for (int i = 1; i < N + 1; i++)
      System.out.print(ans[i] + " ");
    System.out.println();
  }
}


import java.util.ArrayList;
import java.util.HashSet;
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 k = sc.nextInt();

		ArrayList<HashSet> setList = new ArrayList<HashSet>();
		int[] counts = new int[n];
		for (int i = 0; i < m; i++) {
			int a = sc.nextInt();
			int b = sc.nextInt();
			int index1 = getSetIndex(setList, a);
			int index2 = getSetIndex(setList, b);
			if (index1 == -1 && index2 == -1) {
				HashSet set = new HashSet();
				set.add(a);
				set.add(b);
				setList.add(set);
			} else if (index1 == -1) {
				setList.get(index2).add(a);
			} else if (index2 == -1) {
				setList.get(index1).add(b);
			} else if (index1 != index2) {
				for (Object x : setList.get(index2)) {
					setList.get(index1).add(x);
				}
				setList.remove(index2);
			}
			counts[a - 1]++;
			counts[b - 1]++;
		}

		for (int i = 0; i < k; i++) {
			int c = sc.nextInt();
			int d = sc.nextInt();
			int index1 = getSetIndex(setList, c);
			int index2 = getSetIndex(setList, d);
			if (setList.get(index1).contains(d)) {
				counts[c - 1]++;
			}
			if (setList.get(index2).contains(c)) {
				counts[d - 1]++;
			}
		}
		sc.close();

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < n; i++) {
			int index = getSetIndex(setList, i + 1);
			int result = index == -1 ? 0 : setList.get(index).size() - 1 - counts[i];
			sb.append(i == 0 ? "" : " ");
			sb.append(result);
		}
		System.out.print(sb.toString());
	}

	private static int getSetIndex(ArrayList<HashSet> setList, int n) {
		for (int i = 0; i < setList.size(); i++) {
			if (setList.get(i).contains(n)) {
				return i;
			}
		}

		return -1;
	}
}


import java.util.Scanner;

public class Main {
    public static void main(String[] c) {
        Scanner scan = new Scanner(System.in);
        String[] t = scan.nextLine().split("\\s");
        int n = Integer.valueOf(t[0]);
        int r = Integer.valueOf(t[1]);

        if (n >= 10)  {
            System.out.println(r);
        } else {
            int num = 100 * (10 - n);
            System.out.println(r + num);
        }
    }
}

Score : 100 points

Problem Statement

Takahashi is a member of a programming competition site, ButCoder.

Each member of ButCoder is assigned two values: Inner Rating and Displayed Rating.

The Displayed Rating of a member is equal to their Inner Rating if the member has participated in 10 or more contests. Otherwise, the Displayed Rating will be their Inner Rating minus 100 \times (10 - K) when the member has participated in K contests.

Takahashi has participated in N contests, and his Displayed Rating is R. Find his Inner Rating.

Constraints

All values in input are integers.

1 \leq N \leq 100

0 \leq R \leq 4111

Input

Input is given from Standard Input in the following format:

N R

Output

Print his Inner Rating.

Sample Input 1

2 2919

Sample Output 1

3719

Takahashi has participated in 2 contests, which is less than 10, so his Displayed Rating is his Inner Rating minus 100 \times (10 - 2) = 800.

Thus, Takahashi's Inner Rating is 2919 + 800 = 3719.

Sample Input 2

22 3051

Sample Output 2

3051


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

public class Main {
	static class FastReader{
		BufferedReader br;
		StringTokenizer st;
		public FastReader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}
		public String next() {
			while(st==null || !st.hasMoreElements()) {
				try {
					st = new StringTokenizer(br.readLine());

				}
				catch(IOException e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}
		int nextInt() {
			return Integer.parseInt(next());
		}
		long nextLong() {
			return Long.parseLong(next());
		}
		double nextDouble() {
			return Double.parseDouble(next());
		}
	}
	public static void main(String[] args) {
		FastReader ob = new FastReader();
		int n = ob.nextInt();
		System.out.println((1000-n)/100);
	}

}


import java.util.Scanner;
public class Main{
    public static void main(String args[]){
        int n,r,ans;
        Scanner reader = new Scanner(System.in);
        n=reader.nextInt();
        r=reader.nextInt();
        if(n>=10){
            ans=r;
        }
        else{
            ans=100*(10-n)+r;
        }
        System.out.println(ans);
    }
}