id
stringlengths
22
25
content
stringlengths
327
628k
max_stars_repo_path
stringlengths
49
49
condefects-java_data_601
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); double s = sc.nextDouble(); double l = Math.pow(-2, 31); double h = Math.pow(2, 31); if (l <= s && s <= h) { System.out.println("Yes"); } else { System.out.println("No"); } } } import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); double s = sc.nextDouble(); double l = Math.pow(-2, 31); double h = Math.pow(2, 31); if (l <= s && s < h) { System.out.println("Yes"); } else { System.out.println("No"); } } }
ConDefects/ConDefects/Code/abc237_a/Java/42053247
condefects-java_data_602
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); double x = sc.nextDouble(); if(x >= Math.pow(-2,31) && x <= Math.pow(2,31)){ System.out.println("Yes"); }else{ System.out.println("No"); } } } import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); double x = sc.nextDouble(); if(x >= Math.pow(-2,31) && x < Math.pow(2,31)){ System.out.println("Yes"); }else{ System.out.println("No"); } } }
ConDefects/ConDefects/Code/abc237_a/Java/40360900
condefects-java_data_603
import static java.lang.System.*; import java.util.*; public class Main{ public static void solve(){ Scanner sc = new Scanner(in); long N = sc.nextLong(); if(N >= Integer.MIN_VALUE && N <= Integer.MAX_VALUE - 1){ out.println("Yes"); }else out.println("No"); } public static void main(String[] args) { solve(); } } import static java.lang.System.*; import java.util.*; public class Main{ public static void solve(){ Scanner sc = new Scanner(in); long N = sc.nextLong(); if(N >= Integer.MIN_VALUE && N <= Integer.MAX_VALUE){ out.println("Yes"); }else out.println("No"); } public static void main(String[] args) { solve(); } }
ConDefects/ConDefects/Code/abc237_a/Java/38930886
condefects-java_data_604
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); long x = sc.nextLong(); if(x >= Math.pow(-2,31) && x <= Math.pow(2,31)){ System.out.println("Yes"); }else{ System.out.println("No"); } } } import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); long x = sc.nextLong(); if(x >= Math.pow(-2,31) && x < Math.pow(2,31)){ System.out.println("Yes"); }else{ System.out.println("No"); } } }
ConDefects/ConDefects/Code/abc237_a/Java/40361044
condefects-java_data_605
import java.util.*; import java.io.*; import java.math.*; public class Main{ public static void solve(){ Scanner input=new Scanner(System.in); long num=input.nextLong(); long ans1=-(long)Math.pow(2,31); long ans2=(long)Math.pow(2,31); if(num>ans1&&num<=ans2-1){ System.out.println("Yes"); } else{ System.out.println("No"); } } public static void input_output() { try { System.setIn(new FileInputStream("input.txt")); System.setOut(new PrintStream("output.txt")); } catch (Exception e) { //System.out.println("Error"); } } public static void main(String[]args){ if (System.getProperty("ONLINE_JUDGE") == null) { input_output(); solve(); } else { solve(); } } } import java.util.*; import java.io.*; import java.math.*; public class Main{ public static void solve(){ Scanner input=new Scanner(System.in); long num=input.nextLong(); long ans1=-(long)Math.pow(2,31); long ans2=(long)Math.pow(2,31); if(num>=ans1&&num<=ans2-1){ System.out.println("Yes"); } else{ System.out.println("No"); } } public static void input_output() { try { System.setIn(new FileInputStream("input.txt")); System.setOut(new PrintStream("output.txt")); } catch (Exception e) { //System.out.println("Error"); } } public static void main(String[]args){ if (System.getProperty("ONLINE_JUDGE") == null) { input_output(); solve(); } else { solve(); } } }
ConDefects/ConDefects/Code/abc237_a/Java/37405140
condefects-java_data_606
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); long N = Long.parseLong(br.readLine()); if ( N <= Math.pow(2, 31) && N >= - Math.pow(2, 31)){ System.out.println("Yes"); }else{ System.out.println("No"); } } } import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); long N = Long.parseLong(br.readLine()); if ( N <= (Math.pow(2, 31)-1) && N >= - Math.pow(2, 31)){ System.out.println("Yes"); }else{ System.out.println("No"); } } }
ConDefects/ConDefects/Code/abc237_a/Java/45514219
condefects-java_data_607
import java.util.*; import java.io.*; public class Main { private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static PrintWriter out = new PrintWriter(System.out); //解答作成用 public static void solve() throws IOException{ // io long n = Long.parseLong(IO.input_string()); String result = "No"; if(n<2147483648L&&n>-2147483648L){ result = "Yes"; } System.out.println(result); } public static void main(String[] args) throws IOException { solve(); out.flush(); } static class IO { public static char input_char() throws IOException { Scanner sc = new Scanner(System.in); return sc.next().charAt(0); } public static String input_string() throws IOException { return br.readLine(); } public static String[] input_n_array() throws IOException { return br.readLine().split(""); } public static String[] input_b_array() throws IOException { return br.readLine().split(" "); } public static String[] input_c_array() throws IOException { return br.readLine().split("\\."); } public static String[][] input_matrix(String[] str_array) throws IOException{ int len = Convert.str2int(str_array[0]); String[][] matrix = new String[len][]; for(int i=0;i<len;i++){ matrix[i]=input_b_array(); } return matrix; } public static void output_array(String[] str_array){ for(String str:str_array){ out.printf(str + " "); } out.println(); } public static void output_array(int[] int_array){ for(int i:int_array){ out.printf(i + " "); } out.println(); } } static class Convert { public static int str2int(String str){ return Integer.parseInt(str); } public static int[] str2int(String[] str_array){ return Arrays.stream(str_array).mapToInt(Integer::parseInt).toArray(); } } } import java.util.*; import java.io.*; public class Main { private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static PrintWriter out = new PrintWriter(System.out); //解答作成用 public static void solve() throws IOException{ // io long n = Long.parseLong(IO.input_string()); String result = "No"; if(n<2147483648L&&n>=-2147483648L){ result = "Yes"; } System.out.println(result); } public static void main(String[] args) throws IOException { solve(); out.flush(); } static class IO { public static char input_char() throws IOException { Scanner sc = new Scanner(System.in); return sc.next().charAt(0); } public static String input_string() throws IOException { return br.readLine(); } public static String[] input_n_array() throws IOException { return br.readLine().split(""); } public static String[] input_b_array() throws IOException { return br.readLine().split(" "); } public static String[] input_c_array() throws IOException { return br.readLine().split("\\."); } public static String[][] input_matrix(String[] str_array) throws IOException{ int len = Convert.str2int(str_array[0]); String[][] matrix = new String[len][]; for(int i=0;i<len;i++){ matrix[i]=input_b_array(); } return matrix; } public static void output_array(String[] str_array){ for(String str:str_array){ out.printf(str + " "); } out.println(); } public static void output_array(int[] int_array){ for(int i:int_array){ out.printf(i + " "); } out.println(); } } static class Convert { public static int str2int(String str){ return Integer.parseInt(str); } public static int[] str2int(String[] str_array){ return Arrays.stream(str_array).mapToInt(Integer::parseInt).toArray(); } } }
ConDefects/ConDefects/Code/abc237_a/Java/36008790
condefects-java_data_608
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); System.out.println(Math.abs(n)>=Math.pow(2, 31)?"No":"Yes"); sc.close(); } } import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); System.out.println(n<Math.pow(2, 31)&&n>=-1*Math.pow(2, 31)?"Yes":"No"); sc.close(); } }
ConDefects/ConDefects/Code/abc237_a/Java/36787644
condefects-java_data_609
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); long input = scanner.nextLong(); if (input > (-1 * Math.pow(2, 31)) && input < (Math.pow(2, 31) - 1)) System.out.println("Yes"); else System.out.println("No"); } } import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); long input = scanner.nextLong(); if (input >= (-1 * (long) Math.pow(2, 31)) && input <= ((long) Math.pow(2, 31) - 1)) System.out.println("Yes"); else System.out.println("No"); } }
ConDefects/ConDefects/Code/abc237_a/Java/45229624
condefects-java_data_610
import java.util.*; import java.io.*; import java.math.*; public class Main { private static final void solve() throws IOException { long n= nl(); if(n>Math.pow(-2, 31)&&n<Math.pow(2, 31)) { ou.println("Yes"); }else { ou.println("No"); } } public static void main(String[] args) throws IOException { solve(); ou.flush(); } private static final int ni() { return sc.nextInt(); } private static final int[] ni(int n) { return sc.nextIntArray(n); } private static final long nl() { return sc.nextLong(); } private static final long[] nl(int n) { return sc.nextLongArray(n); } private static final String ns() { return sc.next(); } private static final double nd(){ return sc.nextDouble(); } private static final ContestScanner sc = new ContestScanner(); private static final ContestPrinter ou = new ContestPrinter(); } class ContestScanner { private final java.io.InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public ContestScanner(java.io.InputStream in) { this.in = in; } public ContestScanner(java.io.File file) throws java.io.FileNotFoundException { this(new java.io.BufferedInputStream(new java.io.FileInputStream(file))); } public ContestScanner() { this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (java.io.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 java.util.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 java.util.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') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b))); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b))); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit)); } n = n * 10 + digit; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(int length) { long[] array = new long[length]; for (int i = 0; i < length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map) { long[] array = new long[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = this.nextInt(); return array; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width) { long[][] mat = new long[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width) { int[][] mat = new int[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width) { double[][] mat = new double[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width) { char[][] mat = new char[height][width]; for (int h = 0; h < height; h++) { String s = this.next(); for (int w = 0; w < width; w++) { mat[h][w] = s.charAt(w); } } return mat; } } class ContestPrinter extends java.io.PrintWriter { public ContestPrinter(java.io.PrintStream stream) { super(stream); } public ContestPrinter(java.io.File file) throws java.io.FileNotFoundException { super(new java.io.PrintStream(file)); } public ContestPrinter() { super(System.out); } private static String dtos(double x, int n) { StringBuilder sb = new StringBuilder(); if (x < 0) { sb.append('-'); x = -x; } x += Math.pow(10, -n) / 2; sb.append((long) x); sb.append("."); x -= (long) x; for (int i = 0; i < n; i++) { x *= 10; sb.append((int) x); x -= (int) x; } return sb.toString(); } @Override public void print(float f) { super.print(dtos(f, 20)); } @Override public void println(float f) { super.println(dtos(f, 20)); } @Override public void print(double d) { super.print(dtos(d, 20)); } @Override public void println(double d) { super.println(dtos(d, 20)); } public void printArray(int[] array, String separator) { int n = array.length; if (n == 0) { super.println(); return; } for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(int[] array) { this.printArray(array, " "); } public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map) { int n = array.length; if (n == 0) { super.println(); return; } for (int i = 0; i < n - 1; i++) { super.print(map.applyAsInt(array[i])); super.print(separator); } super.println(map.applyAsInt(array[n - 1])); } public void printArray(int[] array, java.util.function.IntUnaryOperator map) { this.printArray(array, " ", map); } public void printArray(long[] array, String separator) { int n = array.length; if (n == 0) { super.println(); return; } for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(long[] array) { this.printArray(array, " "); } public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map) { int n = array.length; if (n == 0) { super.println(); return; } for (int i = 0; i < n - 1; i++) { super.print(map.applyAsLong(array[i])); super.print(separator); } super.println(map.applyAsLong(array[n - 1])); } public void printArray(long[] array, java.util.function.LongUnaryOperator map) { this.printArray(array, " ", map); } public <T> void printArray(T[] array, String separator) { int n = array.length; if (n == 0) { super.println(); return; } for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public <T> void printArray(T[] array) { this.printArray(array, " "); } public <T> void printArray(T[] array, String separator, java.util.function.UnaryOperator<T> map) { int n = array.length; if (n == 0) { super.println(); return; } for (int i = 0; i < n - 1; i++) { super.print(map.apply(array[i])); super.print(separator); } super.println(map.apply(array[n - 1])); } public <T> void printArray(T[] array, java.util.function.UnaryOperator<T> map) { this.printArray(array, " ", map); } } class DSU { private int n; private int[] parentOrSize; public DSU(int n) { this.n = n; this.parentOrSize = new int[n]; java.util.Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; return x; } boolean same(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("" + a); return -parentOrSize[leader(a)]; } java.util.ArrayList<java.util.ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } java.util.ArrayList<java.util.ArrayList<Integer>> result = new java.util.ArrayList<>(n); for (int i = 0; i < n; i++) { result.add(new java.util.ArrayList<>(groupSize[i])); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } result.removeIf(java.util.ArrayList::isEmpty); return result; } } import java.util.*; import java.io.*; import java.math.*; public class Main { private static final void solve() throws IOException { long n= nl(); if(n>=Math.pow(-2, 31)&&n<Math.pow(2, 31)) { ou.println("Yes"); }else { ou.println("No"); } } public static void main(String[] args) throws IOException { solve(); ou.flush(); } private static final int ni() { return sc.nextInt(); } private static final int[] ni(int n) { return sc.nextIntArray(n); } private static final long nl() { return sc.nextLong(); } private static final long[] nl(int n) { return sc.nextLongArray(n); } private static final String ns() { return sc.next(); } private static final double nd(){ return sc.nextDouble(); } private static final ContestScanner sc = new ContestScanner(); private static final ContestPrinter ou = new ContestPrinter(); } class ContestScanner { private final java.io.InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public ContestScanner(java.io.InputStream in) { this.in = in; } public ContestScanner(java.io.File file) throws java.io.FileNotFoundException { this(new java.io.BufferedInputStream(new java.io.FileInputStream(file))); } public ContestScanner() { this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (java.io.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 java.util.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 java.util.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') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b))); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b))); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit)); } n = n * 10 + digit; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(int length) { long[] array = new long[length]; for (int i = 0; i < length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map) { long[] array = new long[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = this.nextInt(); return array; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map) { int[] array = new int[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map) { double[] array = new double[length]; for (int i = 0; i < length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width) { long[][] mat = new long[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width) { int[][] mat = new int[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width) { double[][] mat = new double[height][width]; for (int h = 0; h < height; h++) for (int w = 0; w < width; w++) { mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width) { char[][] mat = new char[height][width]; for (int h = 0; h < height; h++) { String s = this.next(); for (int w = 0; w < width; w++) { mat[h][w] = s.charAt(w); } } return mat; } } class ContestPrinter extends java.io.PrintWriter { public ContestPrinter(java.io.PrintStream stream) { super(stream); } public ContestPrinter(java.io.File file) throws java.io.FileNotFoundException { super(new java.io.PrintStream(file)); } public ContestPrinter() { super(System.out); } private static String dtos(double x, int n) { StringBuilder sb = new StringBuilder(); if (x < 0) { sb.append('-'); x = -x; } x += Math.pow(10, -n) / 2; sb.append((long) x); sb.append("."); x -= (long) x; for (int i = 0; i < n; i++) { x *= 10; sb.append((int) x); x -= (int) x; } return sb.toString(); } @Override public void print(float f) { super.print(dtos(f, 20)); } @Override public void println(float f) { super.println(dtos(f, 20)); } @Override public void print(double d) { super.print(dtos(d, 20)); } @Override public void println(double d) { super.println(dtos(d, 20)); } public void printArray(int[] array, String separator) { int n = array.length; if (n == 0) { super.println(); return; } for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(int[] array) { this.printArray(array, " "); } public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map) { int n = array.length; if (n == 0) { super.println(); return; } for (int i = 0; i < n - 1; i++) { super.print(map.applyAsInt(array[i])); super.print(separator); } super.println(map.applyAsInt(array[n - 1])); } public void printArray(int[] array, java.util.function.IntUnaryOperator map) { this.printArray(array, " ", map); } public void printArray(long[] array, String separator) { int n = array.length; if (n == 0) { super.println(); return; } for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public void printArray(long[] array) { this.printArray(array, " "); } public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map) { int n = array.length; if (n == 0) { super.println(); return; } for (int i = 0; i < n - 1; i++) { super.print(map.applyAsLong(array[i])); super.print(separator); } super.println(map.applyAsLong(array[n - 1])); } public void printArray(long[] array, java.util.function.LongUnaryOperator map) { this.printArray(array, " ", map); } public <T> void printArray(T[] array, String separator) { int n = array.length; if (n == 0) { super.println(); return; } for (int i = 0; i < n - 1; i++) { super.print(array[i]); super.print(separator); } super.println(array[n - 1]); } public <T> void printArray(T[] array) { this.printArray(array, " "); } public <T> void printArray(T[] array, String separator, java.util.function.UnaryOperator<T> map) { int n = array.length; if (n == 0) { super.println(); return; } for (int i = 0; i < n - 1; i++) { super.print(map.apply(array[i])); super.print(separator); } super.println(map.apply(array[n - 1])); } public <T> void printArray(T[] array, java.util.function.UnaryOperator<T> map) { this.printArray(array, " ", map); } } class DSU { private int n; private int[] parentOrSize; public DSU(int n) { this.n = n; this.parentOrSize = new int[n]; java.util.Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; return x; } boolean same(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("" + a); return -parentOrSize[leader(a)]; } java.util.ArrayList<java.util.ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } java.util.ArrayList<java.util.ArrayList<Integer>> result = new java.util.ArrayList<>(n); for (int i = 0; i < n; i++) { result.add(new java.util.ArrayList<>(groupSize[i])); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } result.removeIf(java.util.ArrayList::isEmpty); return result; } }
ConDefects/ConDefects/Code/abc237_a/Java/38467644
condefects-java_data_611
import java.io.*; import java.util.Arrays; import java.util.Scanner; class Main { private static void solve(long n) { long limit=(long)Math.pow(2, 31); if(n>=0 && n>=(-1*limit) && n<=(limit-1)) { System.out.println("Yes"); }else { System.out.println("No"); } } public static void main(String[] args) { Scanner scn = new Scanner(System.in); long n=scn.nextLong(); solve(n); } } import java.io.*; import java.util.Arrays; import java.util.Scanner; class Main { private static void solve(long n) { long limit=(long)Math.pow(2, 31); if(n>=(-1*limit) && n<=(limit-1)) { System.out.println("Yes"); }else { System.out.println("No"); } } public static void main(String[] args) { Scanner scn = new Scanner(System.in); long n=scn.nextLong(); solve(n); } }
ConDefects/ConDefects/Code/abc237_a/Java/37775211
condefects-java_data_612
import java.util.*; import java.util.HashMap; import java.io.*; import java.math.*; public class Main { private static PrintWriter wr = new PrintWriter(System.out); private static long privateNum; public static void write(Object obj) { wr.println(obj); } public static void flush() { wr.flush(); } public static void println(Object obj) { System.out.println(obj); } public static long numGetter() { return privateNum; } public static void numSetter(long input) { privateNum = input; } public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n_len = Integer.parseInt(reader.readLine()); // String[] inputArr = reader.readLine().split(" "); long[][] log_in_out_arr = new long[n_len][2]; TreeMap<Long, Integer> logger_map = new TreeMap<>(); for(int i = 0; i < n_len; i++) { String[] inputArr = reader.readLine().split(" "); long logIn_date = Long.parseLong(inputArr[0]); long logOut_data = logIn_date + Long.parseLong(inputArr[1]); log_in_out_arr[i][0] = logIn_date; log_in_out_arr[i][1] = logOut_data; logger_map.put(logIn_date, 0); logger_map.put(logOut_data, 0); } for(int i = 0; i < n_len; i++) { long logIn_date = log_in_out_arr[i][0]; logger_map.put(logIn_date, logger_map.get(logIn_date) + 1); long logOut_date = log_in_out_arr[i][1]; logger_map.put(logOut_date, logger_map.get(logOut_date) - 1); } long[] population_arr = new long[n_len + 1]; Arrays.fill(population_arr, 0); TreeSet<Long> date_set = new TreeSet<>(logger_map.keySet()); long prev_date = 0; int player_sum = 0; for(long date: date_set) { long current_date = date; long sub_date = current_date - prev_date; player_sum += logger_map.get(date); population_arr[player_sum] += sub_date; prev_date = current_date; } String[] output_arr = new String[n_len]; for(int i = 0; i < n_len; i++) { output_arr[i] = "" + population_arr[i + 1]; } println(String.join(" ", output_arr)); }catch(IOException e) { println(e); } } // main } import java.util.*; import java.util.HashMap; import java.io.*; import java.math.*; public class Main { private static PrintWriter wr = new PrintWriter(System.out); private static long privateNum; public static void write(Object obj) { wr.println(obj); } public static void flush() { wr.flush(); } public static void println(Object obj) { System.out.println(obj); } public static long numGetter() { return privateNum; } public static void numSetter(long input) { privateNum = input; } public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n_len = Integer.parseInt(reader.readLine()); // String[] inputArr = reader.readLine().split(" "); long[][] log_in_out_arr = new long[n_len][2]; TreeMap<Long, Integer> logger_map = new TreeMap<>(); for(int i = 0; i < n_len; i++) { String[] inputArr = reader.readLine().split(" "); long logIn_date = Long.parseLong(inputArr[0]); long logOut_data = logIn_date + Long.parseLong(inputArr[1]); log_in_out_arr[i][0] = logIn_date; log_in_out_arr[i][1] = logOut_data; logger_map.put(logIn_date, 0); logger_map.put(logOut_data, 0); } for(int i = 0; i < n_len; i++) { long logIn_date = log_in_out_arr[i][0]; logger_map.put(logIn_date, logger_map.get(logIn_date) + 1); long logOut_date = log_in_out_arr[i][1]; logger_map.put(logOut_date, logger_map.get(logOut_date) - 1); } long[] population_arr = new long[n_len + 1]; Arrays.fill(population_arr, 0); TreeSet<Long> date_set = new TreeSet<>(logger_map.keySet()); long prev_date = 0; int player_sum = 0; for(long date: date_set) { long current_date = date; long sub_date = current_date - prev_date; population_arr[player_sum] += sub_date; player_sum += logger_map.get(date); prev_date = current_date; } String[] output_arr = new String[n_len]; for(int i = 0; i < n_len; i++) { output_arr[i] = "" + population_arr[i + 1]; } println(String.join(" ", output_arr)); }catch(IOException e) { println(e); } } // main }
ConDefects/ConDefects/Code/abc221_d/Java/37124101
condefects-java_data_613
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt();//パーツ数 int q = sc.nextInt();//クエリ数 List<Integer> dx = new ArrayList<>();//時刻tまでのパーツ1のΔx List<Integer> dy = new ArrayList<>();//時刻tまでのパーツ1のΔy dx.add(0); dy.add(0); for (int i = 1; i <= q; i++) { int t = dx.size() - 1;//時刻 if (sc.nextInt() == 1) { //パーツ1の移動を記録 String move = sc.next(); if ("R".equals(move)) { dx.add(dx.get(t) + 1); dy.add(dy.get(t)); } else if ("L".equals(move)) { dx.add(dx.get(t) - 1); dy.add(dy.get(t)); } else if ("U".equals(move)) { dx.add(dx.get(t)); dy.add(dy.get(t) + 1); } else if ("D".equals(move)) { dx.add(dx.get(t)); dy.add(dy.get(t) - 1); } } else { int m = sc.nextInt(); //パーツmの移動はパーツ1にm-1遅れる int x = m - t; int y = 0; if (t >= m) { x = dx.get(t - m + 1); y = dy.get(t - m + 1); } System.out.println(x + " " + y); } } sc.close(); System.out.println(); } } import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt();//パーツ数 int q = sc.nextInt();//クエリ数 List<Integer> dx = new ArrayList<>();//時刻tまでのパーツ1のΔx List<Integer> dy = new ArrayList<>();//時刻tまでのパーツ1のΔy dx.add(0); dy.add(0); for (int i = 1; i <= q; i++) { int t = dx.size() - 1;//時刻 if (sc.nextInt() == 1) { //パーツ1の移動を記録 String move = sc.next(); if ("R".equals(move)) { dx.add(dx.get(t) + 1); dy.add(dy.get(t)); } else if ("L".equals(move)) { dx.add(dx.get(t) - 1); dy.add(dy.get(t)); } else if ("U".equals(move)) { dx.add(dx.get(t)); dy.add(dy.get(t) + 1); } else if ("D".equals(move)) { dx.add(dx.get(t)); dy.add(dy.get(t) - 1); } } else { int m = sc.nextInt(); //パーツmの移動はパーツ1にm-1遅れる int x = m - t; int y = 0; if (t >= m) { x = dx.get(t - m + 1) + 1; y = dy.get(t - m + 1); } System.out.println(x + " " + y); } } sc.close(); System.out.println(); } }
ConDefects/ConDefects/Code/abc335_c/Java/54256224
condefects-java_data_614
import java.io.* ; import java.math.* ; import java.util.* ; public class Main { final static int N = 300000; long mod = 998244353L; int n; int[] as = new int[N]; long[] u = new long[N]; long[] d = new long[N]; long[] rs = new long[N]; long[] tr = new long[N << 2]; long[] ct = new long[N << 2]; int lc(int p) { return p << 1; } int rc(int p) { return p << 1 | 1; } void push_up(int p, int l, int r) { if (l == r) return; tr[p] = tr[lc(p)] + tr[rc(p)]; ct[p] = ct[lc(p)] + ct[rc(p)]; } void add(int p, int l, int r, int pos) { if (pos <= l && r <= pos) { tr[p] += pos; ct[p] += 1; return; } int mid = (l + r) >> 1; if (pos <= mid) { add(lc(p), l, mid, pos); } else { add(rc(p), mid + 1, r, pos); } push_up(p, l, r); } long[] query(int p, int l, int r, int ll, int rr) { if (ll <= l && r <= rr) { return new long[] { tr[p], ct[p] }; } int mid = (l + r) >> 1; long res = 0; long cnt = 0; if (ll <= mid) { long[] nd = query(lc(p), l, mid, ll, rr); res += nd[0]; cnt += nd[1]; } if (rr > mid) { long[] nd = query(rc(p), mid + 1, r, ll, rr); res += nd[0]; cnt += nd[1]; } return new long[] {res, cnt}; } public void solve() throws Exception { n = nextInt(); for (int i = 1; i <= n; i ++) { as[i] = nextInt(); } for (int i = 1; i <= n; i ++) { add(1, 1, N - 1, as[i]); u[i] += u[i - 1]; u[i] += query(1, 1, N - 1, as[i], N - 1)[0] * 2 - as[i]; if (as[i] > 1) u[i] += query(1, 1, N - 1, 1, as[i] - 1)[1] * as[i] * 2; d[i] += d[i - 1] + i * 2 - 1; } for (int i = 1; i <= n; i ++) { long ni = qpow(d[i], mod - 2, mod); rs[i] = u[i] * ni % mod; cout.println(rs[i]); } cout.flush(); } public static void main(String[] args) throws Exception { Main cmd = new Main(); cmd.solve(); } static BufferedReader cin = new BufferedReader ( new InputStreamReader (System.in) ); static PrintWriter cout = new PrintWriter ( new OutputStreamWriter (System.out) ); static StreamTokenizer input = new StreamTokenizer( new BufferedReader( new InputStreamReader(System.in) ) ); static Scanner next = new Scanner(System.in); int nextInt() throws Exception { int x = 0, f = 1; char c = (char)cin.read(); while (c > '9' || c < '0') { if (c == '-') f = -1; c = (char)cin.read(); } while (c <= '9' && c >= '0') { x = x * 10 + (int)c - (int)'0'; c = (char)cin.read(); } return x * f; } long nextLong() throws Exception { long x = 0, f = 1; char c = (char)cin.read(); while (c > '9' || c < '0') { if (c == '-') f = -1L; c = (char)cin.read(); } while (c <= '9' && c >= '0') { x = x * 10 + (long)c - (long)'0'; c = (char)cin.read(); } return x * f; } double nextDouble() throws Exception { double x = 0, f = 1; char c = (char)cin.read(); while (c > '9' || c < '0') { if (c == '-') f = -1.0; c = (char)cin.read(); } long h = 0; while (c <= '9' && c >= '0') { h = h * 10 + (long)c - (long)'0'; c = (char)cin.read(); } double p = 0.1, e = 0; if (c == '.') { c = (char)cin.read(); while (c <= '9' && c >= '0') { e += p * ((double)c - (double)'0'); p *= 0.1; c = (char)cin.read(); } } return ((double)h + e) * f; } static int sed = (int)System.currentTimeMillis(); public static void seed(int x) { sed = x; } public static int _01_() { sed ^= sed << 13; sed ^= sed >> 17; sed ^= sed << 5; return (sed & 1) == 1 ? 1 : 0; } public static boolean nextBoolean() { return _01_() == 1; } public static int nextInt(int n) { if (n <= 1) return n; int x = n; if ((x & 1) == 1) x ++; int k = nextInt(x >> 1); int res = 2 * k - 1; if (_01_() == 1) res ++; if (res > n) return nextInt(n); return res; } public static long nextLong(long n) { if (n <= 1) return n; long x = n; if ((x & 1) == 1) x ++; long k = nextLong(x >> 1); long res = 2 * k - 1; if (_01_() == 1) res ++; if (res > n) return nextLong(n); return res; } // 获取 1 ~ n 中随机的 m 个 public static int[] nextInts(int n, int m) { int[] as, rs; as = new int[n]; rs = new int[m]; for (int i = 0; i < n; i ++) { as[i] = i + 1; } for (int i = 0; i < m; i ++) { int t = nextInt(m - i); rs[i] = as[m - 1 - t + 1]; int tp = as[m - 1 - t + 1]; as[m - 1 - t + 1] = as[i]; as[i] = tp; } return rs; } public static long qpow(long a, long b, long mod) { if (b == 1) return a % mod; if (a == 1) return a; long res = qpow(a, b >> 1, mod); res = res * res % mod; if ((b & 1) > 0) res = res * a % mod; return res; } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } } import java.io.* ; import java.math.* ; import java.util.* ; public class Main { final static int N = 300000; long mod = 998244353L; int n; int[] as = new int[N]; long[] u = new long[N]; long[] d = new long[N]; long[] rs = new long[N]; long[] tr = new long[N << 2]; long[] ct = new long[N << 2]; int lc(int p) { return p << 1; } int rc(int p) { return p << 1 | 1; } void push_up(int p, int l, int r) { if (l == r) return; tr[p] = tr[lc(p)] + tr[rc(p)]; ct[p] = ct[lc(p)] + ct[rc(p)]; } void add(int p, int l, int r, int pos) { if (pos <= l && r <= pos) { tr[p] += pos; ct[p] += 1; return; } int mid = (l + r) >> 1; if (pos <= mid) { add(lc(p), l, mid, pos); } else { add(rc(p), mid + 1, r, pos); } push_up(p, l, r); } long[] query(int p, int l, int r, int ll, int rr) { if (ll <= l && r <= rr) { return new long[] { tr[p], ct[p] }; } int mid = (l + r) >> 1; long res = 0; long cnt = 0; if (ll <= mid) { long[] nd = query(lc(p), l, mid, ll, rr); res += nd[0]; cnt += nd[1]; } if (rr > mid) { long[] nd = query(rc(p), mid + 1, r, ll, rr); res += nd[0]; cnt += nd[1]; } return new long[] {res, cnt}; } public void solve() throws Exception { n = nextInt(); for (int i = 1; i <= n; i ++) { as[i] = nextInt(); } for (int i = 1; i <= n; i ++) { add(1, 1, N - 1, as[i]); u[i] += u[i - 1]; u[i] += query(1, 1, N - 1, as[i], N - 1)[0] * 2 - as[i]; if (as[i] > 1) u[i] += query(1, 1, N - 1, 1, as[i] - 1)[1] * as[i] * 2; d[i] += d[i - 1] + i * 2 - 1; u[i] %= mod; d[i] %= mod; } for (int i = 1; i <= n; i ++) { long ni = qpow(d[i], mod - 2, mod); rs[i] = u[i] * ni % mod; cout.println(rs[i]); } cout.flush(); } public static void main(String[] args) throws Exception { Main cmd = new Main(); cmd.solve(); } static BufferedReader cin = new BufferedReader ( new InputStreamReader (System.in) ); static PrintWriter cout = new PrintWriter ( new OutputStreamWriter (System.out) ); static StreamTokenizer input = new StreamTokenizer( new BufferedReader( new InputStreamReader(System.in) ) ); static Scanner next = new Scanner(System.in); int nextInt() throws Exception { int x = 0, f = 1; char c = (char)cin.read(); while (c > '9' || c < '0') { if (c == '-') f = -1; c = (char)cin.read(); } while (c <= '9' && c >= '0') { x = x * 10 + (int)c - (int)'0'; c = (char)cin.read(); } return x * f; } long nextLong() throws Exception { long x = 0, f = 1; char c = (char)cin.read(); while (c > '9' || c < '0') { if (c == '-') f = -1L; c = (char)cin.read(); } while (c <= '9' && c >= '0') { x = x * 10 + (long)c - (long)'0'; c = (char)cin.read(); } return x * f; } double nextDouble() throws Exception { double x = 0, f = 1; char c = (char)cin.read(); while (c > '9' || c < '0') { if (c == '-') f = -1.0; c = (char)cin.read(); } long h = 0; while (c <= '9' && c >= '0') { h = h * 10 + (long)c - (long)'0'; c = (char)cin.read(); } double p = 0.1, e = 0; if (c == '.') { c = (char)cin.read(); while (c <= '9' && c >= '0') { e += p * ((double)c - (double)'0'); p *= 0.1; c = (char)cin.read(); } } return ((double)h + e) * f; } static int sed = (int)System.currentTimeMillis(); public static void seed(int x) { sed = x; } public static int _01_() { sed ^= sed << 13; sed ^= sed >> 17; sed ^= sed << 5; return (sed & 1) == 1 ? 1 : 0; } public static boolean nextBoolean() { return _01_() == 1; } public static int nextInt(int n) { if (n <= 1) return n; int x = n; if ((x & 1) == 1) x ++; int k = nextInt(x >> 1); int res = 2 * k - 1; if (_01_() == 1) res ++; if (res > n) return nextInt(n); return res; } public static long nextLong(long n) { if (n <= 1) return n; long x = n; if ((x & 1) == 1) x ++; long k = nextLong(x >> 1); long res = 2 * k - 1; if (_01_() == 1) res ++; if (res > n) return nextLong(n); return res; } // 获取 1 ~ n 中随机的 m 个 public static int[] nextInts(int n, int m) { int[] as, rs; as = new int[n]; rs = new int[m]; for (int i = 0; i < n; i ++) { as[i] = i + 1; } for (int i = 0; i < m; i ++) { int t = nextInt(m - i); rs[i] = as[m - 1 - t + 1]; int tp = as[m - 1 - t + 1]; as[m - 1 - t + 1] = as[i]; as[i] = tp; } return rs; } public static long qpow(long a, long b, long mod) { if (b == 1) return a % mod; if (a == 1) return a; long res = qpow(a, b >> 1, mod); res = res * res % mod; if ((b & 1) > 0) res = res * a % mod; return res; } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } }
ConDefects/ConDefects/Code/abc276_f/Java/39740106
condefects-java_data_615
import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] s = new String[n]; for(int i = 0;i<n;i++){ s[i] = sc.next(); } for(int i = n-1;i < 0 ;i--){ System.out.println(s[i]); } } } import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] s = new String[n]; for(int i = 0;i<n;i++){ s[i] = sc.next(); } for(int i = n-1;i >= 0 ;i--){ System.out.println(s[i]); } } }
ConDefects/ConDefects/Code/abc284_a/Java/42020207
condefects-java_data_616
import java.io.BufferedInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringJoiner; import java.util.function.IntUnaryOperator; import java.util.function.LongUnaryOperator; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Main { static In in = new In(); static Out out = new Out(false, false); static final long inf = 0x1fffffffffffffffL; static final int iinf = 0x3fffffff; static final double eps = 1e-9; static long mod = 998244353; void solve() { // for (int v = 0; v < 1000; v++) { // int n = 1000; // char[] s = new char[n]; // for (int i = 0; i < s.length; i++) { // s[i] = random() < 0.3333 ? 'o' : random() < 0.5 ? 'f' : 'a'; // } // k1(s, 10); // } char[] s = in.nextCharArray(); int k = in.nextInt(); if (k == 0) { out.println(k0(s)); } else { out.println(k1(s, k)); } } int k1(char[] s, int k) { int n = s.length; int[][] ok = new int[n][n + 1]; int[][] ok2 = new int[n][n + 1]; for (int i = n - 1; i >= 0; i--) { if (s[i] == 'o') { if (i + 1 < n && s[i + 1] == 'f') { ok[i][i + 2] = 2; for (int j = i + 3; j <= n; j++) { ok[i][j] = Math.min(ok2[i + 2][j] + k, j - (i + 2)) + 2; } } else if (i + 1 < n && s[i + 1] == 'o') { for (int j = i + 2; j < n; j++) { if (ok[i + 1][j] == j - (i + 1) && s[j] == 'f') { ok[i][j + 1] = j + 1 - i; for (int r = j + 2; r <= n; r++) { ok[i][r] = Math.min(ok2[j + 1][r] + k, r - (j + 1)) + (j + 1 - i); } } } } } for (int j = i + 1; j <= n; j++) { ok2[i][j] = Math.max(ok2[i][j], ok[i][j]); if (i + 1 < n) { ok2[i][j] = Math.max(ok2[i][j], ok2[i + 1][j]); } } for (int j = i + 1; j <= n; j++) { ok2[i][j] = Math.max(ok2[i][j], ok2[i][j - 1]); ok[i][j] = Math.max(ok[i][j], ok[i][j - 1]); } for (int r = i + 1; r <= n; r++) { for (int m = i + 1; m < r; m++) { ok[i][r] = Math.max(ok[i][r], ok[i][m] + ok2[m][r]); ok2[i][r] = Math.max(ok2[i][r], ok2[i][m] + ok2[m][r]); } } } int ans = 0; for (int i = 0; i < n; i++) { for (int j = 0; j <= n; j++) { ans = Math.max(ans, ok2[i][j]); } } return n - ans; } int k0(char[] s) { int depth = 0; int ans = s.length; for (char ch : s) { if (ch == 'o') { depth++; } else if (ch == 'f') { if (depth >= 1) { ans -= 2; depth--; } } else { depth = 0; } } return ans; } public static void main(String... args) { new Main().solve(); out.flush(); } } class In { private final BufferedInputStream reader = new BufferedInputStream(System.in); private final byte[] buffer = new byte[0x10000]; private int i = 0; private int length = 0; public int read() { if (i == length) { i = 0; try { length = reader.read(buffer); } catch (IOException ignored) { } if (length == -1) { return 0; } } if (length <= i) { throw new RuntimeException(); } return buffer[i++]; } public String next() { StringBuilder builder = new StringBuilder(); int b = read(); while (b < '!' || '~' < b) { b = read(); } while ('!' <= b && b <= '~') { builder.appendCodePoint(b); b = read(); } return builder.toString(); } public String nextLine() { StringBuilder builder = new StringBuilder(); int b = read(); while (b != 0 && b != '\r' && b != '\n') { builder.appendCodePoint(b); b = read(); } if (b == '\r') { read(); } return builder.toString(); } public int nextInt() { long val = nextLong(); if (val < Integer.MIN_VALUE || Integer.MAX_VALUE < val) { throw new NumberFormatException(); } return (int)val; } public long nextLong() { int b = read(); while (b < '!' || '~' < b) { b = read(); } boolean neg = false; if (b == '-') { neg = true; b = read(); } long n = 0; int c = 0; while ('0' <= b && b <= '9') { n = n * 10 + b - '0'; b = read(); c++; } if (c == 0 || c >= 2 && n == 0) { throw new NumberFormatException(); } return neg ? -n : n; } public double nextDouble() { return Double.parseDouble(next()); } public char[] nextCharArray() { return next().toCharArray(); } public String[] nextStringArray(int n) { String[] s = new String[n]; for (int i = 0; i < n; i++) { s[i] = next(); } return s; } public char[][] nextCharMatrix(int n, int m) { char[][] a = new char[n][m]; for (int i = 0; i < n; i++) { a[i] = next().toCharArray(); } return a; } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public int[] nextIntArray(int n, IntUnaryOperator op) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = op.applyAsInt(nextInt()); } return a; } public int[][] nextIntMatrix(int h, int w) { int[][] a = new int[h][w]; for (int i = 0; i < h; i++) { a[i] = nextIntArray(w); } return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public long[] nextLongArray(int n, LongUnaryOperator op) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = op.applyAsLong(nextLong()); } return a; } public long[][] nextLongMatrix(int h, int w) { long[][] a = new long[h][w]; for (int i = 0; i < h; i++) { a[i] = nextLongArray(w); } return a; } public List<List<Integer>> nextGraph(int n, int m, boolean directed) { List<List<Integer>> res = new ArrayList<>(); for (int i = 0; i < n; i++) { res.add(new ArrayList<>()); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; res.get(u).add(v); if (!directed) { res.get(v).add(u); } } return res; } } class Out { private final PrintWriter out = new PrintWriter(System.out); private final PrintWriter err = new PrintWriter(System.err); public boolean autoFlush; public boolean enableDebug; public Out(boolean autoFlush, boolean enableDebug) { this.autoFlush = autoFlush; this.enableDebug = enableDebug; } public void debug(Object... args) { if (!enableDebug) { return; } if (args == null || args.getClass() != Object[].class) { args = new Object[] {args}; } err.println(Arrays.stream(args).map(obj -> format(obj, true)).collect(Collectors.joining(" "))); err.flush(); } private String format(Object obj, boolean canMultiline) { if (obj == null) return "null"; Class<?> clazz = obj.getClass(); if (clazz == Double.class) return String.format("%.10f", obj); if (clazz == int[].class) return Arrays.toString((int[])obj); if (clazz == long[].class) return Arrays.toString((long[])obj); if (clazz == char[].class) return String.valueOf((char[])obj); if (clazz == boolean[].class) return IntStream.range(0, ((boolean[])obj).length).mapToObj(i -> ((boolean[])obj)[i] ? "1" : "0").collect(Collectors.joining()); if (clazz == double[].class) return Arrays.toString(Arrays.stream((double[])obj).mapToObj(a -> format(a, false)).toArray()); if (canMultiline && clazz.isArray() && clazz.componentType().isArray()) return Arrays.stream((Object[])obj).map(a -> format(a, false)).collect(Collectors.joining("\n")); if (clazz == Object[].class) return Arrays.toString(Arrays.stream((Object[])obj).map(a -> format(a, false)).toArray()); return String.valueOf(obj); } public void println(Object... args) { if (args == null || args.getClass() != Object[].class) { args = new Object[] {args}; } out.println(Arrays.stream(args) .map(obj -> obj instanceof Double ? String.format("%.10f", obj) : String.valueOf(obj)) .collect(Collectors.joining(" "))); if (autoFlush) { out.flush(); } } public void println(char a) { out.println(a); if (autoFlush) { out.flush(); } } public void println(int a) { out.println(a); if (autoFlush) { out.flush(); } } public void println(long a) { out.println(a); if (autoFlush) { out.flush(); } } public void println(double a) { out.println(String.format("%.10f", a)); if (autoFlush) { out.flush(); } } public void println(String s) { out.println(s); if (autoFlush) { out.flush(); } } public void println(char[] s) { out.println(String.valueOf(s)); if (autoFlush) { out.flush(); } } public void println(int[] a) { StringJoiner joiner = new StringJoiner(" "); for (int i : a) { joiner.add(Integer.toString(i)); } out.println(joiner); if (autoFlush) { out.flush(); } } public void println(long[] a) { StringJoiner joiner = new StringJoiner(" "); for (long i : a) { joiner.add(Long.toString(i)); } out.println(joiner); if (autoFlush) { out.flush(); } } public void flush() { err.flush(); out.flush(); } } import java.io.BufferedInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringJoiner; import java.util.function.IntUnaryOperator; import java.util.function.LongUnaryOperator; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Main { static In in = new In(); static Out out = new Out(false, false); static final long inf = 0x1fffffffffffffffL; static final int iinf = 0x3fffffff; static final double eps = 1e-9; static long mod = 998244353; void solve() { // for (int v = 0; v < 1000; v++) { // int n = 1000; // char[] s = new char[n]; // for (int i = 0; i < s.length; i++) { // s[i] = random() < 0.3333 ? 'o' : random() < 0.5 ? 'f' : 'a'; // } // k1(s, 10); // } char[] s = in.nextCharArray(); int k = in.nextInt(); if (k == 0) { out.println(k0(s)); } else { out.println(k1(s, k)); } } int k1(char[] s, int k) { int n = s.length; int[][] ok = new int[n][n + 1]; int[][] ok2 = new int[n][n + 1]; for (int i = n - 1; i >= 0; i--) { if (s[i] == 'o') { if (i + 1 < n && s[i + 1] == 'f') { ok[i][i + 2] = 2; for (int j = i + 3; j <= n; j++) { ok[i][j] = Math.min(ok2[i + 2][j] + k, j - (i + 2)) + 2; } } else if (i + 1 < n && s[i + 1] == 'o') { for (int j = i + 2; j < n; j++) { if (ok[i + 1][j] == j - (i + 1) && s[j] == 'f') { ok[i][j + 1] = j + 1 - i; for (int r = j + 2; r <= n; r++) { ok[i][r] = Math.max(ok[i][r], Math.min(ok2[j + 1][r] + k, r - (j + 1)) + (j + 1 - i)); } } } } } for (int j = i + 1; j <= n; j++) { ok2[i][j] = Math.max(ok2[i][j], ok[i][j]); if (i + 1 < n) { ok2[i][j] = Math.max(ok2[i][j], ok2[i + 1][j]); } } for (int j = i + 1; j <= n; j++) { ok2[i][j] = Math.max(ok2[i][j], ok2[i][j - 1]); ok[i][j] = Math.max(ok[i][j], ok[i][j - 1]); } for (int r = i + 1; r <= n; r++) { for (int m = i + 1; m < r; m++) { ok[i][r] = Math.max(ok[i][r], ok[i][m] + ok2[m][r]); ok2[i][r] = Math.max(ok2[i][r], ok2[i][m] + ok2[m][r]); } } } int ans = 0; for (int i = 0; i < n; i++) { for (int j = 0; j <= n; j++) { ans = Math.max(ans, ok2[i][j]); } } return n - ans; } int k0(char[] s) { int depth = 0; int ans = s.length; for (char ch : s) { if (ch == 'o') { depth++; } else if (ch == 'f') { if (depth >= 1) { ans -= 2; depth--; } } else { depth = 0; } } return ans; } public static void main(String... args) { new Main().solve(); out.flush(); } } class In { private final BufferedInputStream reader = new BufferedInputStream(System.in); private final byte[] buffer = new byte[0x10000]; private int i = 0; private int length = 0; public int read() { if (i == length) { i = 0; try { length = reader.read(buffer); } catch (IOException ignored) { } if (length == -1) { return 0; } } if (length <= i) { throw new RuntimeException(); } return buffer[i++]; } public String next() { StringBuilder builder = new StringBuilder(); int b = read(); while (b < '!' || '~' < b) { b = read(); } while ('!' <= b && b <= '~') { builder.appendCodePoint(b); b = read(); } return builder.toString(); } public String nextLine() { StringBuilder builder = new StringBuilder(); int b = read(); while (b != 0 && b != '\r' && b != '\n') { builder.appendCodePoint(b); b = read(); } if (b == '\r') { read(); } return builder.toString(); } public int nextInt() { long val = nextLong(); if (val < Integer.MIN_VALUE || Integer.MAX_VALUE < val) { throw new NumberFormatException(); } return (int)val; } public long nextLong() { int b = read(); while (b < '!' || '~' < b) { b = read(); } boolean neg = false; if (b == '-') { neg = true; b = read(); } long n = 0; int c = 0; while ('0' <= b && b <= '9') { n = n * 10 + b - '0'; b = read(); c++; } if (c == 0 || c >= 2 && n == 0) { throw new NumberFormatException(); } return neg ? -n : n; } public double nextDouble() { return Double.parseDouble(next()); } public char[] nextCharArray() { return next().toCharArray(); } public String[] nextStringArray(int n) { String[] s = new String[n]; for (int i = 0; i < n; i++) { s[i] = next(); } return s; } public char[][] nextCharMatrix(int n, int m) { char[][] a = new char[n][m]; for (int i = 0; i < n; i++) { a[i] = next().toCharArray(); } return a; } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public int[] nextIntArray(int n, IntUnaryOperator op) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = op.applyAsInt(nextInt()); } return a; } public int[][] nextIntMatrix(int h, int w) { int[][] a = new int[h][w]; for (int i = 0; i < h; i++) { a[i] = nextIntArray(w); } return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public long[] nextLongArray(int n, LongUnaryOperator op) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = op.applyAsLong(nextLong()); } return a; } public long[][] nextLongMatrix(int h, int w) { long[][] a = new long[h][w]; for (int i = 0; i < h; i++) { a[i] = nextLongArray(w); } return a; } public List<List<Integer>> nextGraph(int n, int m, boolean directed) { List<List<Integer>> res = new ArrayList<>(); for (int i = 0; i < n; i++) { res.add(new ArrayList<>()); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; res.get(u).add(v); if (!directed) { res.get(v).add(u); } } return res; } } class Out { private final PrintWriter out = new PrintWriter(System.out); private final PrintWriter err = new PrintWriter(System.err); public boolean autoFlush; public boolean enableDebug; public Out(boolean autoFlush, boolean enableDebug) { this.autoFlush = autoFlush; this.enableDebug = enableDebug; } public void debug(Object... args) { if (!enableDebug) { return; } if (args == null || args.getClass() != Object[].class) { args = new Object[] {args}; } err.println(Arrays.stream(args).map(obj -> format(obj, true)).collect(Collectors.joining(" "))); err.flush(); } private String format(Object obj, boolean canMultiline) { if (obj == null) return "null"; Class<?> clazz = obj.getClass(); if (clazz == Double.class) return String.format("%.10f", obj); if (clazz == int[].class) return Arrays.toString((int[])obj); if (clazz == long[].class) return Arrays.toString((long[])obj); if (clazz == char[].class) return String.valueOf((char[])obj); if (clazz == boolean[].class) return IntStream.range(0, ((boolean[])obj).length).mapToObj(i -> ((boolean[])obj)[i] ? "1" : "0").collect(Collectors.joining()); if (clazz == double[].class) return Arrays.toString(Arrays.stream((double[])obj).mapToObj(a -> format(a, false)).toArray()); if (canMultiline && clazz.isArray() && clazz.componentType().isArray()) return Arrays.stream((Object[])obj).map(a -> format(a, false)).collect(Collectors.joining("\n")); if (clazz == Object[].class) return Arrays.toString(Arrays.stream((Object[])obj).map(a -> format(a, false)).toArray()); return String.valueOf(obj); } public void println(Object... args) { if (args == null || args.getClass() != Object[].class) { args = new Object[] {args}; } out.println(Arrays.stream(args) .map(obj -> obj instanceof Double ? String.format("%.10f", obj) : String.valueOf(obj)) .collect(Collectors.joining(" "))); if (autoFlush) { out.flush(); } } public void println(char a) { out.println(a); if (autoFlush) { out.flush(); } } public void println(int a) { out.println(a); if (autoFlush) { out.flush(); } } public void println(long a) { out.println(a); if (autoFlush) { out.flush(); } } public void println(double a) { out.println(String.format("%.10f", a)); if (autoFlush) { out.flush(); } } public void println(String s) { out.println(s); if (autoFlush) { out.flush(); } } public void println(char[] s) { out.println(String.valueOf(s)); if (autoFlush) { out.flush(); } } public void println(int[] a) { StringJoiner joiner = new StringJoiner(" "); for (int i : a) { joiner.add(Integer.toString(i)); } out.println(joiner); if (autoFlush) { out.flush(); } } public void println(long[] a) { StringJoiner joiner = new StringJoiner(" "); for (long i : a) { joiner.add(Long.toString(i)); } out.println(joiner); if (autoFlush) { out.flush(); } } public void flush() { err.flush(); out.flush(); } }
ConDefects/ConDefects/Code/abc325_g/Java/46833570
condefects-java_data_617
import java.util.*; public class Main { public static void main(String... args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); System.out.println((n / 100 + (n % 100) / 10 + n % 100) * 111); } } import java.util.*; public class Main { public static void main(String... args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); System.out.println((n / 100 + (n % 100) / 10 + n % 10) * 111); } }
ConDefects/ConDefects/Code/abc235_a/Java/31506740
condefects-java_data_618
// A - +3 +5 +7 import java.util.*; import java.lang.*; import java.io.*; public class Main { // https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in) ); } String next() { while(st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { if(st.hasMoreTokens()) { str = st.nextToken("\n"); } else { str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader s = new FastReader(); int n = s.nextInt(); while(n-- > 0) { long a = s.nextInt(), b = s.nextInt(), c = s.nextInt(); if((a + b + c) % 3 != 0) { System.out.println(-1); } else { long m = (a + b + c)/3; long d = Math.abs(a - m) + Math.abs(b - m) + Math.abs(c - m); if(d % 4 != 0) { System.out.println(-1); } else { System.out.println(d/4); } } } } } // A - +3 +5 +7 import java.util.*; import java.lang.*; import java.io.*; public class Main { // https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in) ); } String next() { while(st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { if(st.hasMoreTokens()) { str = st.nextToken("\n"); } else { str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader s = new FastReader(); int n = s.nextInt(); while(n-- > 0) { long a = s.nextInt(), b = s.nextInt(), c = s.nextInt(); if((a % 2 != b % 2 || b % 2 != c % 2) || (a + b + c) % 3 != 0) { System.out.println(-1); } else { long m = (a + b + c)/3; long d = Math.abs(a - m) + Math.abs(b - m) + Math.abs(c - m); if(d % 4 != 0) { System.out.println(-1); } else { System.out.println(d/4); } } } } }
ConDefects/ConDefects/Code/arc158_a/Java/39781115
condefects-java_data_619
/* * Author: rickytsung * Date: 2023/2/9 * Problem: ABC 256 Ex */ import java.util.*; import java.time.*; import java.io.*; import java.math.*; public class Main{ public static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); public static BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); public static long ret,cnt; public static int reti,rd,n,m,ans; public static boolean neg,b1,b2,b3; public static final int mod=998244353,mox=998244352,mod2=1_000_000_007,ma=200005; public static Useful us=new Useful(mod); public static int[] A=new int[ma]; public static int[] B=new int[ma]; public static long[] Al=new long[ma]; public static long[] Bl=new long[ma]; public static ArrayList<ArrayList<Integer>> E=new ArrayList<>(); public static void main(String[] args) throws Exception{ final int n=readint(); for(int i=0;i<n;i++) { int[] A=new int[3]; for(int j=0;j<3;j++) { A[j]=readint(); } Arrays.sort(A); long s=A[2]-A[0]; //2x+4y=s long t=A[2]-A[1]; //4x+2y=t long u=s+t; if(2*t-s<0) { u-=2*t-s; } if(2*s-t<0) { u=Math.max(u,s+t-(2*s-t)); } if(s%2!=0||t%2!=0) { bw.write("-1\n"); continue; } bw.write((u/6)+"\n"); //break; } bw.flush(); } /* */ public static int readint() throws Exception{ reti=0; neg=false; while(rd<48||rd>57) { rd=br.read(); if(rd=='-') { neg=true; } } while(rd>47&&rd<58) { reti*=10; reti+=(rd&15); rd=br.read(); } if(neg)reti*=-1; return reti; } public static long readlong() throws Exception{ ret=0; neg=false; while(rd<48||rd>57) { rd=br.read(); if(rd=='-') { neg=true; } } while(rd>47&&rd<58) { ret*=10; ret+=(rd&15); rd=br.read(); } if(neg)ret*=-1; return ret; } public static int pint(String in) { return Integer.parseInt(in); } public static long plong(String in) { return Long.parseLong(in); } public static void outn() { System.out.println(); } public static void outn(long in) { System.out.println(in); } public static void outn(boolean in) { System.out.println(in); } public static void outn(String in) { System.out.println(in); } public static void out(long in) { System.out.print(in); } public static void out(boolean in) { System.out.print(in); } public static void out(String in) { System.out.print(in); } } /* */ /* */ class ooo{ int x,y,z; ooo(int a,int b,int c){ x=a; y=b; z=c; } } class Pii{ int x,y; Pii(int a,int b){ x=a; y=b; } @Override public boolean equals(Object o) { if (this==o) return true; if (!(o instanceof Pii)) return false; Pii key = (Pii) o; return x==key.x&&y==key.y; } @Override public int hashCode() { long result=x; result=31*result+y; return (int)(result%998244353); } } class Pll{ long x,y; Pll(long a,long b){ x=a; y=b; } @Override public boolean equals(Object o) { if (this==o) return true; if (!(o instanceof Pll)) return false; Pll key = (Pll) o; return x==key.x&&y==key.y; } @Override public int hashCode() { long result=x; result=31*result+y; return (int)(result%998244353); } } class Useful{ long mod; Useful(long m){mod=m;} void al(ArrayList<ArrayList<Integer>> a,int n){for(int i=0;i<n;i++) {a.add(new ArrayList<Integer>());}} void arr(int[] a,int init) {for(int i=0;i<a.length;i++) {a[i]=init;}} void arr(long[] a,long init) {for(int i=0;i<a.length;i++) {a[i]=init;}} void arr(int[][] a,int init) {for(int i=0;i<a.length;i++) {for(int j=0;j<a[i].length;j++) {a[i][j]=init;}}} void arr(long[][] a,long init) {for(int i=0;i<a.length;i++) {for(int j=0;j<a[i].length;j++) {a[i][j]=init;}}} void arr(int[][][] a,int init) {for(int i=0;i<a.length;i++) {for(int j=0;j<a[i].length;j++) {for(int k=0;k<a[i][j].length;k++) {a[i][j][k]=init;}}}} void arr(long[][][] a,long init) {for(int i=0;i<a.length;i++) {for(int j=0;j<a[i].length;j++) {for(int k=0;k<a[i][j].length;k++) {a[i][j][k]=init;}}}} void arr(int[][][][] a,int init) {for(int i=0;i<a.length;i++) {for(int j=0;j<a[i].length;j++) {for(int k=0;k<a[i][j].length;k++) {Arrays.fill(a[i][j][k],init);}}}} void arr(long[][][][] a,long init) {for(int i=0;i<a.length;i++) {for(int j=0;j<a[i].length;j++) {for(int k=0;k<a[i][j].length;k++) {Arrays.fill(a[i][j][k],init);}}}} long fast(long x,long pw) { if(pw<=0)return 1; if(pw==1)return x; long h=fast(x,pw>>1); if((pw&1)==0) { return h*h%mod; } return h*h%mod*x%mod; } long[][] mul(long[][] a,long[][] b){ long[][] c=new long[a.length][b[0].length]; for(int i=0;i<a.length;i++) { for(int j=0;j<b[0].length;j++) { for(int k=0;k<a[0].length;k++) { c[i][j]+=a[i][k]*b[k][j]; c[i][j]%=mod; } } } return c; } long[][] fast(long[][] x,int pw){ if(pw==1)return x; long[][] h=fast(x,pw>>1); if((pw&1)==0) { return mul(h,h); } else { return mul(mul(h,h),x); } } int gcd(int a,int b) { if(a==0)return b; if(b==0)return a; return gcd(b,a%b); } long gcd(long a,long b) { if(a==0)return b; if(b==0)return a; return gcd(b,a%b); } long lcm(long a, long b){ return a*(b/gcd(a,b)); } double log2(int x) { return (Math.log(x)/Math.log(2)); } double log2(long x) { return (Math.log(x)/Math.log(2)); } } /* * Author: rickytsung * Date: 2023/2/9 * Problem: ABC 256 Ex */ import java.util.*; import java.time.*; import java.io.*; import java.math.*; public class Main{ public static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); public static BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); public static long ret,cnt; public static int reti,rd,n,m,ans; public static boolean neg,b1,b2,b3; public static final int mod=998244353,mox=998244352,mod2=1_000_000_007,ma=200005; public static Useful us=new Useful(mod); public static int[] A=new int[ma]; public static int[] B=new int[ma]; public static long[] Al=new long[ma]; public static long[] Bl=new long[ma]; public static ArrayList<ArrayList<Integer>> E=new ArrayList<>(); public static void main(String[] args) throws Exception{ final int n=readint(); for(int i=0;i<n;i++) { int[] A=new int[3]; for(int j=0;j<3;j++) { A[j]=readint(); } Arrays.sort(A); long s=A[2]-A[0]; //2x+4y=s long t=A[2]-A[1]; //4x+2y=t long u=s+t; if(2*t-s<0) { u-=2*t-s; } if(2*s-t<0) { u=Math.max(u,s+t-(2*s-t)); } if(s%2!=0||t%2!=0||u%6!=0) { bw.write("-1\n"); continue; } bw.write((u/6)+"\n"); //break; } bw.flush(); } /* */ public static int readint() throws Exception{ reti=0; neg=false; while(rd<48||rd>57) { rd=br.read(); if(rd=='-') { neg=true; } } while(rd>47&&rd<58) { reti*=10; reti+=(rd&15); rd=br.read(); } if(neg)reti*=-1; return reti; } public static long readlong() throws Exception{ ret=0; neg=false; while(rd<48||rd>57) { rd=br.read(); if(rd=='-') { neg=true; } } while(rd>47&&rd<58) { ret*=10; ret+=(rd&15); rd=br.read(); } if(neg)ret*=-1; return ret; } public static int pint(String in) { return Integer.parseInt(in); } public static long plong(String in) { return Long.parseLong(in); } public static void outn() { System.out.println(); } public static void outn(long in) { System.out.println(in); } public static void outn(boolean in) { System.out.println(in); } public static void outn(String in) { System.out.println(in); } public static void out(long in) { System.out.print(in); } public static void out(boolean in) { System.out.print(in); } public static void out(String in) { System.out.print(in); } } /* */ /* */ class ooo{ int x,y,z; ooo(int a,int b,int c){ x=a; y=b; z=c; } } class Pii{ int x,y; Pii(int a,int b){ x=a; y=b; } @Override public boolean equals(Object o) { if (this==o) return true; if (!(o instanceof Pii)) return false; Pii key = (Pii) o; return x==key.x&&y==key.y; } @Override public int hashCode() { long result=x; result=31*result+y; return (int)(result%998244353); } } class Pll{ long x,y; Pll(long a,long b){ x=a; y=b; } @Override public boolean equals(Object o) { if (this==o) return true; if (!(o instanceof Pll)) return false; Pll key = (Pll) o; return x==key.x&&y==key.y; } @Override public int hashCode() { long result=x; result=31*result+y; return (int)(result%998244353); } } class Useful{ long mod; Useful(long m){mod=m;} void al(ArrayList<ArrayList<Integer>> a,int n){for(int i=0;i<n;i++) {a.add(new ArrayList<Integer>());}} void arr(int[] a,int init) {for(int i=0;i<a.length;i++) {a[i]=init;}} void arr(long[] a,long init) {for(int i=0;i<a.length;i++) {a[i]=init;}} void arr(int[][] a,int init) {for(int i=0;i<a.length;i++) {for(int j=0;j<a[i].length;j++) {a[i][j]=init;}}} void arr(long[][] a,long init) {for(int i=0;i<a.length;i++) {for(int j=0;j<a[i].length;j++) {a[i][j]=init;}}} void arr(int[][][] a,int init) {for(int i=0;i<a.length;i++) {for(int j=0;j<a[i].length;j++) {for(int k=0;k<a[i][j].length;k++) {a[i][j][k]=init;}}}} void arr(long[][][] a,long init) {for(int i=0;i<a.length;i++) {for(int j=0;j<a[i].length;j++) {for(int k=0;k<a[i][j].length;k++) {a[i][j][k]=init;}}}} void arr(int[][][][] a,int init) {for(int i=0;i<a.length;i++) {for(int j=0;j<a[i].length;j++) {for(int k=0;k<a[i][j].length;k++) {Arrays.fill(a[i][j][k],init);}}}} void arr(long[][][][] a,long init) {for(int i=0;i<a.length;i++) {for(int j=0;j<a[i].length;j++) {for(int k=0;k<a[i][j].length;k++) {Arrays.fill(a[i][j][k],init);}}}} long fast(long x,long pw) { if(pw<=0)return 1; if(pw==1)return x; long h=fast(x,pw>>1); if((pw&1)==0) { return h*h%mod; } return h*h%mod*x%mod; } long[][] mul(long[][] a,long[][] b){ long[][] c=new long[a.length][b[0].length]; for(int i=0;i<a.length;i++) { for(int j=0;j<b[0].length;j++) { for(int k=0;k<a[0].length;k++) { c[i][j]+=a[i][k]*b[k][j]; c[i][j]%=mod; } } } return c; } long[][] fast(long[][] x,int pw){ if(pw==1)return x; long[][] h=fast(x,pw>>1); if((pw&1)==0) { return mul(h,h); } else { return mul(mul(h,h),x); } } int gcd(int a,int b) { if(a==0)return b; if(b==0)return a; return gcd(b,a%b); } long gcd(long a,long b) { if(a==0)return b; if(b==0)return a; return gcd(b,a%b); } long lcm(long a, long b){ return a*(b/gcd(a,b)); } double log2(int x) { return (Math.log(x)/Math.log(2)); } double log2(long x) { return (Math.log(x)/Math.log(2)); } }
ConDefects/ConDefects/Code/arc158_a/Java/39677746
condefects-java_data_620
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); String sTails[] = new String[n]; for(int i=0; i<n; i++){ String tmp = sc.next(); sTails[i] = tmp.substring(3, 6); } int count = 0; String[] tList = new String[m]; for(int i=0; i<m; i++){ tList[i] = sc.next(); } for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ if(sTails[i] == tList[j]){ count++; break; } } } System.out.println(count); } } import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); String sTails[] = new String[n]; for(int i=0; i<n; i++){ String tmp = sc.next(); sTails[i] = tmp.substring(3, 6); } int count = 0; String[] tList = new String[m]; for(int i=0; i<m; i++){ tList[i] = sc.next(); } for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ if(sTails[i].equals(tList[j])){ count++; break; } } } System.out.println(count); } }
ConDefects/ConDefects/Code/abc287_b/Java/41135152
condefects-java_data_621
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 count = 0; String s[] = new String[n]; String t[] = new String[m]; for (int i = 0;i < n;i++) { s[i] = sc.next(); } for (int i = 0;i < m;i++) { t[i] = sc.next(); } for (int i = 0;i < n;i++) { for (int j = 0;j < m;j++) { if (s[i].endsWith(t[j])) { count++; continue; } } } System.out.println(count); } } import java.util.Scanner; public class Main { public static void main(String []args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int count = 0; String s[] = new String[n]; String t[] = new String[m]; for (int i = 0;i < n;i++) { s[i] = sc.next(); } for (int i = 0;i < m;i++) { t[i] = sc.next(); } for (int i = 0;i < n;i++) { for (int j = 0;j < m;j++) { if (s[i].endsWith(t[j])) { count++; break; } } } System.out.println(count); } }
ConDefects/ConDefects/Code/abc287_b/Java/43540042
condefects-java_data_622
//package atcoder.abc321; import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); solve(in.nextInt()); //solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; 6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial. If getting stuck, skip it and solve other similar level problems. Wait for 1 week then try to solve again. Only read editorial after you solved a problem. 7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already. 8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you rushed to coding! */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a thorough idea steps! 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? 5. Any chance you got WA due to integer overflow, especially if you are dealing with all subarrays. The sum can get deceptively large! If in doubt, just use long instead of int. */ static long n, x, k, maxLevel; static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { n = in.nextLong(); x = in.nextLong(); k = in.nextLong(); maxLevel = getLevel(n); long ans = compute(x, k); long childNode = x, parentNode = x / 2; k--; while(parentNode > 0 && k >= 0) { ans += compute(parentNode, k) - compute(childNode, k - 1); childNode = parentNode; parentNode /= 2; k--; } out.println(ans); } out.close(); } //the number of nodes in the subtree rooted at x that are k steps away from x static long compute(long subRoot, long d) { if(d < 0) { return 0; } else if(d == 0) { return 1; } long level = getLevel(subRoot); if(maxLevel - level < d) { return 0; } long l = subRoot, r = subRoot; for(int i = 0; i < d; i++) { l *= 2; r = r * 2 + 1; } return min(n, r) - l + 1; } static long getLevel(long x) { long level = 0; while(x > 1) { x /= 2; level++; } level++; return level; } static long addWithMod(long x, long y, long mod) { return (x + y) % mod; } static long subtractWithMod(long x, long y, long mod) { return ((x - y) % mod + mod) % mod; } static long multiplyWithMod(long x, long y, long mod) { x %= mod; y %= mod; return x * y % mod; } static long modInv(long x, long mod) { return fastPowMod(x, mod - 2, mod); } static long fastPowMod(long x, long n, long mod) { if (n == 0) return 1; long half = fastPowMod(x, n / 2, mod); if (n % 2 == 0) return half * half % mod; return half * half % mod * x % mod; } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("src/input.in")); out = new PrintWriter(new FileOutputStream("src/output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) g[i] = next(); return g; } List<Integer>[] readUnWeightedGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphOneIndexed(int n, int m) { List<int[]>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } List<Integer>[] readUnWeightedGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphZeroIndexed(int n, int m) { List<int[]>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building an undirected weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildUndirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]][0] = end2[i]; adj[end1[i]][idxForEachNode[end1[i]]][1] = weight[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]][0] = end1[i]; adj[end2[i]][idxForEachNode[end2[i]]][1] = weight[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } /* A more efficient way of building a directed weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildDirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]][0] = to[i]; adj[from[i]][idxForEachNode[from[i]]][1] = weight[i]; idxForEachNode[from[i]]++; } return adj; } } } //package atcoder.abc321; import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); solve(in.nextInt()); //solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; 6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial. If getting stuck, skip it and solve other similar level problems. Wait for 1 week then try to solve again. Only read editorial after you solved a problem. 7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already. 8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you rushed to coding! */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a thorough idea steps! 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? 5. Any chance you got WA due to integer overflow, especially if you are dealing with all subarrays. The sum can get deceptively large! If in doubt, just use long instead of int. */ static long n, x, k, maxLevel; static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { n = in.nextLong(); x = in.nextLong(); k = in.nextLong(); maxLevel = getLevel(n); long ans = compute(x, k); long childNode = x, parentNode = x / 2; k--; while(parentNode > 0 && k >= 0) { ans += compute(parentNode, k) - compute(childNode, k - 1); childNode = parentNode; parentNode /= 2; k--; } out.println(ans); } out.close(); } //the number of nodes in the subtree rooted at x that are k steps away from x static long compute(long subRoot, long d) { if(d < 0) { return 0; } else if(d == 0) { return 1; } long level = getLevel(subRoot); if(maxLevel - level < d) { return 0; } long l = subRoot, r = subRoot; for(int i = 0; i < d; i++) { l *= 2; r = r * 2 + 1; } return max(0, min(n, r) - l + 1); } static long getLevel(long x) { long level = 0; while(x > 1) { x /= 2; level++; } level++; return level; } static long addWithMod(long x, long y, long mod) { return (x + y) % mod; } static long subtractWithMod(long x, long y, long mod) { return ((x - y) % mod + mod) % mod; } static long multiplyWithMod(long x, long y, long mod) { x %= mod; y %= mod; return x * y % mod; } static long modInv(long x, long mod) { return fastPowMod(x, mod - 2, mod); } static long fastPowMod(long x, long n, long mod) { if (n == 0) return 1; long half = fastPowMod(x, n / 2, mod); if (n % 2 == 0) return half * half % mod; return half * half % mod * x % mod; } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("src/input.in")); out = new PrintWriter(new FileOutputStream("src/output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) g[i] = next(); return g; } List<Integer>[] readUnWeightedGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphOneIndexed(int n, int m) { List<int[]>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } List<Integer>[] readUnWeightedGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphZeroIndexed(int n, int m) { List<int[]>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building an undirected weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildUndirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]][0] = end2[i]; adj[end1[i]][idxForEachNode[end1[i]]][1] = weight[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]][0] = end1[i]; adj[end2[i]][idxForEachNode[end2[i]]][1] = weight[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } /* A more efficient way of building a directed weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildDirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]][0] = to[i]; adj[from[i]][idxForEachNode[from[i]]][1] = weight[i]; idxForEachNode[from[i]]++; } return adj; } } }
ConDefects/ConDefects/Code/abc321_e/Java/45896361
condefects-java_data_623
import java.util.*; public class Main { public static long gcd(long a, long b) { if(b==0) return a; return gcd(b, a%b); } public static long getMin(long x[], long a, long b, long c){ long min = Long.MAX_VALUE; List<Node> t1 = new ArrayList<>(); for(int i = 0;i < x.length;i++){ t1.add(new Node((a-x[i]%a)%a, i)); } t1.sort(Comparator.comparingLong(o -> o.diff)); List<Node> t2 = new ArrayList<>(); for(int i = 0;i < x.length;i++){ t2.add(new Node((b-x[i]%b)%b, i)); } t2.sort(Comparator.comparingLong(o -> o.diff)); List<Node> t3 = new ArrayList<>(); for(int i = 0;i < x.length;i++){ t3.add(new Node((c-x[i]%c)%c, i)); } t3.sort(Comparator.comparingLong(o -> o.diff)); for(int i = 0;i < 3;i++){ for(int j = 0;j < 3;j++){ if(t1.get(i).i == t2.get(j).i) continue; for(int k = 0;k < 3;k++){ if(t1.get(i).i == t3.get(j).i) continue; min = Math.min(min, t1.get(i).diff+t2.get(j).diff+t3.get(k).diff); } } } return min; } public static long getMin(long x[], long a, long b){ long min = Long.MAX_VALUE; List<Node> t1 = new ArrayList<>(); for(int i = 0;i < x.length;i++){ t1.add(new Node((a-x[i]%a)%a, i)); } t1.sort(Comparator.comparingLong(o -> o.diff)); List<Node> t2 = new ArrayList<>(); for(int i = 0;i < x.length;i++){ t2.add(new Node((b-x[i]%b)%b, i)); } t2.sort(Comparator.comparingLong(o -> o.diff)); for(int i = 0;i < 2;i++){ for(int j = 0;j < 2;j++){ if(t1.get(i).i == t2.get(j).i) continue; min = Math.min(min, t1.get(i).diff+t2.get(j).diff); } } return min; } static class Node{ Node(long diff, int i){ this.diff = diff; this.i = i; } long diff; int i; } public static void main(String[] args) { int n = getInt(); long a = getInt(); long b = getInt(); long c = getInt(); long x[] = getLongArray(n); long lcmab = a*b/gcd(a,b); long lcmbc = b*c/gcd(b,c); long lcmac = a*c/gcd(c,a); long lcm = lcmab*c/gcd(lcmab, c); long min = Long.MAX_VALUE; for(int i = 0;i < n;i++){ min = Math.min(min, (lcm-x[i] % lcm)%lcm); } if(n == 1){ out(min); return; } min = Math.min(getMin(x, a, lcmbc),min); min = Math.min(getMin(x, b, lcmac),min); min = Math.min(getMin(x, c, lcmab),min); if(n == 2){ out(min); return; } min = Math.min(getMin(x, a, b, c), min); out(min); } static int sqrtI(long n){ return toInt(Math.sqrt(n)); } static long toLong(double v) { return Double.valueOf(v).longValue(); } static int toInt(double v) { return Double.valueOf(v).intValue(); } static String[] createTiles(int w, int h, String out){ String[] s = new String[h + 2]; s[0] = s[h + 1] = out.repeat(w + 2); for (int i = 1; i <= h; i++) { s[i] = out + getString() + out; } return s; } static void outH(List<?> o){ int nl = o.size()-1; for (int i = 0; i < o.size(); i++) { System.out.print(o.get(i)+(i != nl ? " ":"\n")); } out(); } static void out(List<?> o){ for (Object oo: o) { System.out.println(oo); } } static void outH(Object[] o){ int nl = o.length-1; for (int i = 0; i < o.length; i++) { System.out.print(o[i]+(i != nl ? " ":"")); } out(); } static void outH(char[] d){ int nl = d.length-1; for (int i = 0; i < d.length; i++) { System.out.print(d[i]+(i != nl ? " ":"")); } out(); } static void outH(double[] d){ int nl = d.length-1; for (int i = 0; i < d.length; i++) { System.out.print(d[i]+(i != nl ? " ":"")); } out(); } static void outH(int[] in){ int nl = in.length-1; for (int i = 0; i < in.length; i++) { System.out.print(in[i]+(i != nl ? " ":"")); } out(); } static void outH(long[] l){ int nl = l.length-1; for (int i = 0; i < l.length; i++) { System.out.print(l[i]+(i != nl ? " ":"")); } out(); } static void outH(String[] s){ int nl = s.length-1; for (int i = 0; i < s.length; i++) { System.out.print(s[i]+(i != nl ? " ":"")); } out(); } static void out(){ System.out.println(); } static void out(Object[] o){ for (Object oo : o) { System.out.println(oo); } } static String sortString(String s) { char[] a = s.toCharArray(); Arrays.sort(a); return new String(a); } static String sortStringDesc(String s) { return new StringBuilder(sortString(s)).reverse().toString(); } static void out(char[] c){ for (Character aChar : c) { System.out.println(aChar); } } static void out(double[] d){ for (Double aDouble : d) { System.out.println(aDouble); } } static void out(int[] i){ for (Integer iInteger: i) { System.out.println(iInteger); } } static void out(long[] l){ for (Long lLong: l) { System.out.println(lLong); } } static void out(String[] s){ for (String sString: s) { System.out.println(sString); } } static void out(Double d){ System.out.println(d); } static void out(Integer i){ System.out.println(i); } static void out(Long l){ System.out.println(l); } static void out(String s){ System.out.println(s); } static void YesOrNo(boolean b){ System.out.println(b ? "Yes" : "No"); } static void YesOrNo(boolean b, String yes, String no){ System.out.println(b ? yes : no); } static void Yes(){ System.out.println("Yes"); } static void No(){ System.out.println("No"); } /* static StringTokenizer st; static InputStreamReader isr = new InputStreamReader(System.in); static BufferedReader br = new BufferedReader(isr); static String getString() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine().trim()); } catch (IOException e) { System.exit(0); } } return st.nextToken(); } static long getLong() { return Long.parseLong(getString()); } static int getInt() { return Integer.parseInt(getString()); } static Double getDouble() { return parseDouble(getString()); } */ private static final java.io.InputStream in = System.in; private static final byte[] buffer = new byte[1024]; private static int ptr = 0; private static int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; static boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (java.io.IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } static int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } static boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } static String getString() { if (!hasNext()) throw new java.util.NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } static long getLong() { if (!hasNext()) throw new java.util.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') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit) ); } n = n * 10 + digit; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } static public int getInt() { long nl = getLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } static public double getDouble() { return Double.parseDouble(getString()); } static public long[] getLongArray(int length){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = getLong(); return array; } static public long[] getLongArray(int length, java.util.function.LongUnaryOperator map){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = map.applyAsLong(getLong()); return array; } static public int[] getIntArray(int length){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = getInt(); return array; } static public int[] getIntArray(int length, java.util.function.IntUnaryOperator map){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = map.applyAsInt(getInt()); return array; } static public double[] getDoubleArray(int length){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = getDouble(); return array; } static public double[] getDoubleArray(int length, java.util.function.DoubleUnaryOperator map){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = map.applyAsDouble(getDouble()); return array; } static public long[][] getLongMatrix(int height, int width){ long[][] mat = new long[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = getLong(); } return mat; } static int[][] getIntMatrix(int height, int width){ int[][] mat = new int[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = getInt(); } return mat; } static public double[][] getDoubleMatrix(int height, int width){ double[][] mat = new double[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = getDouble(); } return mat; } static public char[][] nextCharMatrix(int height, int width){ char[][] mat = new char[height][width]; for(int h=0; h<height; h++){ String s = getString(); for(int w=0; w<width; w++){ mat[h][w] = s.charAt(w); } } return mat; } public static long mod1097 = 1000000007L; public static long mod9982 = 998244353L; } import java.util.*; public class Main { public static long gcd(long a, long b) { if(b==0) return a; return gcd(b, a%b); } public static long getMin(long x[], long a, long b, long c){ long min = Long.MAX_VALUE; List<Node> t1 = new ArrayList<>(); for(int i = 0;i < x.length;i++){ t1.add(new Node((a-x[i]%a)%a, i)); } t1.sort(Comparator.comparingLong(o -> o.diff)); List<Node> t2 = new ArrayList<>(); for(int i = 0;i < x.length;i++){ t2.add(new Node((b-x[i]%b)%b, i)); } t2.sort(Comparator.comparingLong(o -> o.diff)); List<Node> t3 = new ArrayList<>(); for(int i = 0;i < x.length;i++){ t3.add(new Node((c-x[i]%c)%c, i)); } t3.sort(Comparator.comparingLong(o -> o.diff)); for(int i = 0;i < 3;i++){ for(int j = 0;j < 3;j++){ if(t1.get(i).i == t2.get(j).i) continue; for(int k = 0;k < 3;k++){ if(t1.get(i).i == t3.get(k).i || t2.get(j).i == t3.get(k).i) continue; min = Math.min(min, t1.get(i).diff+t2.get(j).diff+t3.get(k).diff); } } } return min; } public static long getMin(long x[], long a, long b){ long min = Long.MAX_VALUE; List<Node> t1 = new ArrayList<>(); for(int i = 0;i < x.length;i++){ t1.add(new Node((a-x[i]%a)%a, i)); } t1.sort(Comparator.comparingLong(o -> o.diff)); List<Node> t2 = new ArrayList<>(); for(int i = 0;i < x.length;i++){ t2.add(new Node((b-x[i]%b)%b, i)); } t2.sort(Comparator.comparingLong(o -> o.diff)); for(int i = 0;i < 2;i++){ for(int j = 0;j < 2;j++){ if(t1.get(i).i == t2.get(j).i) continue; min = Math.min(min, t1.get(i).diff+t2.get(j).diff); } } return min; } static class Node{ Node(long diff, int i){ this.diff = diff; this.i = i; } long diff; int i; } public static void main(String[] args) { int n = getInt(); long a = getInt(); long b = getInt(); long c = getInt(); long x[] = getLongArray(n); long lcmab = a*b/gcd(a,b); long lcmbc = b*c/gcd(b,c); long lcmac = a*c/gcd(c,a); long lcm = lcmab*c/gcd(lcmab, c); long min = Long.MAX_VALUE; for(int i = 0;i < n;i++){ min = Math.min(min, (lcm-x[i] % lcm)%lcm); } if(n == 1){ out(min); return; } min = Math.min(getMin(x, a, lcmbc),min); min = Math.min(getMin(x, b, lcmac),min); min = Math.min(getMin(x, c, lcmab),min); if(n == 2){ out(min); return; } min = Math.min(getMin(x, a, b, c), min); out(min); } static int sqrtI(long n){ return toInt(Math.sqrt(n)); } static long toLong(double v) { return Double.valueOf(v).longValue(); } static int toInt(double v) { return Double.valueOf(v).intValue(); } static String[] createTiles(int w, int h, String out){ String[] s = new String[h + 2]; s[0] = s[h + 1] = out.repeat(w + 2); for (int i = 1; i <= h; i++) { s[i] = out + getString() + out; } return s; } static void outH(List<?> o){ int nl = o.size()-1; for (int i = 0; i < o.size(); i++) { System.out.print(o.get(i)+(i != nl ? " ":"\n")); } out(); } static void out(List<?> o){ for (Object oo: o) { System.out.println(oo); } } static void outH(Object[] o){ int nl = o.length-1; for (int i = 0; i < o.length; i++) { System.out.print(o[i]+(i != nl ? " ":"")); } out(); } static void outH(char[] d){ int nl = d.length-1; for (int i = 0; i < d.length; i++) { System.out.print(d[i]+(i != nl ? " ":"")); } out(); } static void outH(double[] d){ int nl = d.length-1; for (int i = 0; i < d.length; i++) { System.out.print(d[i]+(i != nl ? " ":"")); } out(); } static void outH(int[] in){ int nl = in.length-1; for (int i = 0; i < in.length; i++) { System.out.print(in[i]+(i != nl ? " ":"")); } out(); } static void outH(long[] l){ int nl = l.length-1; for (int i = 0; i < l.length; i++) { System.out.print(l[i]+(i != nl ? " ":"")); } out(); } static void outH(String[] s){ int nl = s.length-1; for (int i = 0; i < s.length; i++) { System.out.print(s[i]+(i != nl ? " ":"")); } out(); } static void out(){ System.out.println(); } static void out(Object[] o){ for (Object oo : o) { System.out.println(oo); } } static String sortString(String s) { char[] a = s.toCharArray(); Arrays.sort(a); return new String(a); } static String sortStringDesc(String s) { return new StringBuilder(sortString(s)).reverse().toString(); } static void out(char[] c){ for (Character aChar : c) { System.out.println(aChar); } } static void out(double[] d){ for (Double aDouble : d) { System.out.println(aDouble); } } static void out(int[] i){ for (Integer iInteger: i) { System.out.println(iInteger); } } static void out(long[] l){ for (Long lLong: l) { System.out.println(lLong); } } static void out(String[] s){ for (String sString: s) { System.out.println(sString); } } static void out(Double d){ System.out.println(d); } static void out(Integer i){ System.out.println(i); } static void out(Long l){ System.out.println(l); } static void out(String s){ System.out.println(s); } static void YesOrNo(boolean b){ System.out.println(b ? "Yes" : "No"); } static void YesOrNo(boolean b, String yes, String no){ System.out.println(b ? yes : no); } static void Yes(){ System.out.println("Yes"); } static void No(){ System.out.println("No"); } /* static StringTokenizer st; static InputStreamReader isr = new InputStreamReader(System.in); static BufferedReader br = new BufferedReader(isr); static String getString() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine().trim()); } catch (IOException e) { System.exit(0); } } return st.nextToken(); } static long getLong() { return Long.parseLong(getString()); } static int getInt() { return Integer.parseInt(getString()); } static Double getDouble() { return parseDouble(getString()); } */ private static final java.io.InputStream in = System.in; private static final byte[] buffer = new byte[1024]; private static int ptr = 0; private static int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; static boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (java.io.IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } static int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } static boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } static String getString() { if (!hasNext()) throw new java.util.NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } static long getLong() { if (!hasNext()) throw new java.util.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') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit) ); } n = n * 10 + digit; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } static public int getInt() { long nl = getLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } static public double getDouble() { return Double.parseDouble(getString()); } static public long[] getLongArray(int length){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = getLong(); return array; } static public long[] getLongArray(int length, java.util.function.LongUnaryOperator map){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = map.applyAsLong(getLong()); return array; } static public int[] getIntArray(int length){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = getInt(); return array; } static public int[] getIntArray(int length, java.util.function.IntUnaryOperator map){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = map.applyAsInt(getInt()); return array; } static public double[] getDoubleArray(int length){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = getDouble(); return array; } static public double[] getDoubleArray(int length, java.util.function.DoubleUnaryOperator map){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = map.applyAsDouble(getDouble()); return array; } static public long[][] getLongMatrix(int height, int width){ long[][] mat = new long[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = getLong(); } return mat; } static int[][] getIntMatrix(int height, int width){ int[][] mat = new int[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = getInt(); } return mat; } static public double[][] getDoubleMatrix(int height, int width){ double[][] mat = new double[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = getDouble(); } return mat; } static public char[][] nextCharMatrix(int height, int width){ char[][] mat = new char[height][width]; for(int h=0; h<height; h++){ String s = getString(); for(int w=0; w<width; w++){ mat[h][w] = s.charAt(w); } } return mat; } public static long mod1097 = 1000000007L; public static long mod9982 = 998244353L; }
ConDefects/ConDefects/Code/arc166_b/Java/50407485
condefects-java_data_624
//package atcoder.arc166; import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); //solve(in.nextInt()); solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; 6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial. If getting stuck, skip it and solve other similar level problems. Wait for 1 week then try to solve again. Only read editorial after you solved a problem. 7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already. 8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you rushed to coding! */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a thorough idea steps! 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? 5. Any chance you got WA due to integer overflow, especially if you are dealing with all subarrays. The sum can get deceptively large! If in doubt, just use long instead of int. */ static int n, a, b, c; static long[] x; static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { n = in.nextInt(); a = in.nextInt(); b = in.nextInt(); c = in.nextInt(); x = in.nextLongArrayPrimitive(n); long ans = Long.MAX_VALUE; long v = lcm(a, lcm(b, c)); ans = min(ans, compute1(v)); if(n >= 2) { long v1 = lcm(a, b); ans = min(ans, compute2(v1, c)); v1 = lcm(a, c); ans = min(ans, compute2(v1, b)); v1 = lcm(b, c); ans = min(ans, compute2(v1, a)); } if(n >= 3) { ans = min(ans, compute3(new long[]{a, b, c})); } out.println(ans); } out.close(); } static long compute1(long v) { long cost = Long.MAX_VALUE; for(long d : x) { long c = d % v == 0 ? 0 : v - d % v; cost = min(cost, c); } return cost; } static long compute2(long v1, long v2) { long[] cost1 = new long[n], cost2 = new long[n]; for(int i = 0; i < n; i++) { cost1[i] = x[i] % v1 == 0 ? 0 : v1 - x[i] % v1; cost2[i] = x[i] % v2 == 0 ? 0 : v2 - x[i] % v2; } long[] suffixMin1 = new long[n], suffixMin2 = new long[n]; suffixMin1[n - 1] = cost1[n - 1]; suffixMin2[n - 1] = cost2[n - 1]; for(int i = n - 2; i >= 0; i--) { suffixMin1[i] = min(suffixMin1[i + 1], cost1[i]); suffixMin2[i] = min(suffixMin2[i + 1], cost2[i]); } long best = Long.MAX_VALUE; for(int i = 0; i < n - 1; i++) { best = min(best, cost1[i] + suffixMin2[i + 1]); } for(int i = 0; i < n - 1; i++) { best = min(best, cost2[i] + suffixMin1[i + 1]); } return best; } static long compute3(long[] v) { List<List<Long>> perms = getPerm(v); long best = Long.MAX_VALUE; for(List<Long> perm : perms) { best = min(best, compute3Helper(perm)); } return best; } static long compute3Helper(List<Long> d) { long[][] cost = new long[3][n]; for(int i = 0; i < d.size(); i++) { for(int j = 0; j < n; j++) { cost[i][j] = x[i] % d.get(i) == 0 ? 0 : d.get(i) - x[i] % d.get(i); } } long best = Long.MAX_VALUE; //first compute the 2nd 3rd comb result long[] suffixMin = new long[n]; suffixMin[n - 1] = cost[2][n - 1]; for(int i = n - 2; i >= 0; i--) { suffixMin[i] = min(suffixMin[i + 1], cost[2][i]); } long[] comb = new long[n], combSuffixMin = new long[n]; for(int i = 0; i < n - 1; i++) { comb[i] = cost[1][i] + suffixMin[i + 1]; } combSuffixMin[n - 1] = Long.MAX_VALUE; for(int i = n - 2; i >= 0; i--) { combSuffixMin[i] = min(combSuffixMin[i + 1], comb[i]); } for(int i = 0; i < n - 2; i++) { best = min(best, cost[0][i] + combSuffixMin[i + 1]); } return best; } static List<List<Long>> getPerm(long[] v) { List<List<Long>> perms = new ArrayList<>(); permHelper(perms, new ArrayList<>(), v, new boolean[v.length]); return perms; } static void permHelper(List<List<Long>> perms, List<Long> list, long[] v, boolean[] used) { if(list.size() == v.length) { perms.add(new ArrayList<>(list)); } else { for(int i = 0; i < v.length; i++) { if(!used[i]) { used[i] = true; list.add(v[i]); permHelper(perms, list, v, used); list.remove(list.size() - 1); used[i] = false; } } } } static long gcd(long x, long y) { if(y == 0) return x; return gcd(y, x % y); } static long lcm(long x, long y) { return x * y / gcd(x, y); } static long addWithMod(long x, long y, long mod) { return (x + y) % mod; } static long subtractWithMod(long x, long y, long mod) { return ((x - y) % mod + mod) % mod; } static long multiplyWithMod(long x, long y, long mod) { x %= mod; y %= mod; return x * y % mod; } static long modInv(long x, long mod) { return fastPowMod(x, mod - 2, mod); } static long fastPowMod(long x, long n, long mod) { if (n == 0) return 1; long half = fastPowMod(x, n / 2, mod); if (n % 2 == 0) return half * half % mod; return half * half % mod * x % mod; } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("src/input.in")); out = new PrintWriter(new FileOutputStream("src/output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) g[i] = next(); return g; } List<Integer>[] readUnWeightedGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphOneIndexed(int n, int m) { List<int[]>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } List<Integer>[] readUnWeightedGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphZeroIndexed(int n, int m) { List<int[]>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building an undirected weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildUndirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]][0] = end2[i]; adj[end1[i]][idxForEachNode[end1[i]]][1] = weight[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]][0] = end1[i]; adj[end2[i]][idxForEachNode[end2[i]]][1] = weight[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } /* A more efficient way of building a directed weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildDirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]][0] = to[i]; adj[from[i]][idxForEachNode[from[i]]][1] = weight[i]; idxForEachNode[from[i]]++; } return adj; } } } //package atcoder.arc166; import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); //solve(in.nextInt()); solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; 6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial. If getting stuck, skip it and solve other similar level problems. Wait for 1 week then try to solve again. Only read editorial after you solved a problem. 7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already. 8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you rushed to coding! */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a thorough idea steps! 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? 5. Any chance you got WA due to integer overflow, especially if you are dealing with all subarrays. The sum can get deceptively large! If in doubt, just use long instead of int. */ static int n, a, b, c; static long[] x; static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { n = in.nextInt(); a = in.nextInt(); b = in.nextInt(); c = in.nextInt(); x = in.nextLongArrayPrimitive(n); long ans = Long.MAX_VALUE; long v = lcm(a, lcm(b, c)); ans = min(ans, compute1(v)); if(n >= 2) { long v1 = lcm(a, b); ans = min(ans, compute2(v1, c)); v1 = lcm(a, c); ans = min(ans, compute2(v1, b)); v1 = lcm(b, c); ans = min(ans, compute2(v1, a)); } if(n >= 3) { ans = min(ans, compute3(new long[]{a, b, c})); } out.println(ans); } out.close(); } static long compute1(long v) { long cost = Long.MAX_VALUE; for(long d : x) { long c = d % v == 0 ? 0 : v - d % v; cost = min(cost, c); } return cost; } static long compute2(long v1, long v2) { long[] cost1 = new long[n], cost2 = new long[n]; for(int i = 0; i < n; i++) { cost1[i] = x[i] % v1 == 0 ? 0 : v1 - x[i] % v1; cost2[i] = x[i] % v2 == 0 ? 0 : v2 - x[i] % v2; } long[] suffixMin1 = new long[n], suffixMin2 = new long[n]; suffixMin1[n - 1] = cost1[n - 1]; suffixMin2[n - 1] = cost2[n - 1]; for(int i = n - 2; i >= 0; i--) { suffixMin1[i] = min(suffixMin1[i + 1], cost1[i]); suffixMin2[i] = min(suffixMin2[i + 1], cost2[i]); } long best = Long.MAX_VALUE; for(int i = 0; i < n - 1; i++) { best = min(best, cost1[i] + suffixMin2[i + 1]); } for(int i = 0; i < n - 1; i++) { best = min(best, cost2[i] + suffixMin1[i + 1]); } return best; } static long compute3(long[] v) { List<List<Long>> perms = getPerm(v); long best = Long.MAX_VALUE; for(List<Long> perm : perms) { best = min(best, compute3Helper(perm)); } return best; } static long compute3Helper(List<Long> d) { long[][] cost = new long[3][n]; for(int i = 0; i < d.size(); i++) { for(int j = 0; j < n; j++) { cost[i][j] = x[j] % d.get(i) == 0 ? 0 : d.get(i) - x[j] % d.get(i); } } long best = Long.MAX_VALUE; //first compute the 2nd 3rd comb result long[] suffixMin = new long[n]; suffixMin[n - 1] = cost[2][n - 1]; for(int i = n - 2; i >= 0; i--) { suffixMin[i] = min(suffixMin[i + 1], cost[2][i]); } long[] comb = new long[n], combSuffixMin = new long[n]; for(int i = 0; i < n - 1; i++) { comb[i] = cost[1][i] + suffixMin[i + 1]; } combSuffixMin[n - 1] = Long.MAX_VALUE; for(int i = n - 2; i >= 0; i--) { combSuffixMin[i] = min(combSuffixMin[i + 1], comb[i]); } for(int i = 0; i < n - 2; i++) { best = min(best, cost[0][i] + combSuffixMin[i + 1]); } return best; } static List<List<Long>> getPerm(long[] v) { List<List<Long>> perms = new ArrayList<>(); permHelper(perms, new ArrayList<>(), v, new boolean[v.length]); return perms; } static void permHelper(List<List<Long>> perms, List<Long> list, long[] v, boolean[] used) { if(list.size() == v.length) { perms.add(new ArrayList<>(list)); } else { for(int i = 0; i < v.length; i++) { if(!used[i]) { used[i] = true; list.add(v[i]); permHelper(perms, list, v, used); list.remove(list.size() - 1); used[i] = false; } } } } static long gcd(long x, long y) { if(y == 0) return x; return gcd(y, x % y); } static long lcm(long x, long y) { return x * y / gcd(x, y); } static long addWithMod(long x, long y, long mod) { return (x + y) % mod; } static long subtractWithMod(long x, long y, long mod) { return ((x - y) % mod + mod) % mod; } static long multiplyWithMod(long x, long y, long mod) { x %= mod; y %= mod; return x * y % mod; } static long modInv(long x, long mod) { return fastPowMod(x, mod - 2, mod); } static long fastPowMod(long x, long n, long mod) { if (n == 0) return 1; long half = fastPowMod(x, n / 2, mod); if (n % 2 == 0) return half * half % mod; return half * half % mod * x % mod; } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("src/input.in")); out = new PrintWriter(new FileOutputStream("src/output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) g[i] = next(); return g; } List<Integer>[] readUnWeightedGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphOneIndexed(int n, int m) { List<int[]>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } List<Integer>[] readUnWeightedGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphZeroIndexed(int n, int m) { List<int[]>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building an undirected weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildUndirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]][0] = end2[i]; adj[end1[i]][idxForEachNode[end1[i]]][1] = weight[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]][0] = end1[i]; adj[end2[i]][idxForEachNode[end2[i]]][1] = weight[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } /* A more efficient way of building a directed weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildDirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]][0] = to[i]; adj[from[i]][idxForEachNode[from[i]]][1] = weight[i]; idxForEachNode[from[i]]++; } return adj; } } }
ConDefects/ConDefects/Code/arc166_b/Java/46393864
condefects-java_data_625
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] sa = br.readLine().split(" "); int n = Integer.parseInt(sa[0]); int m = Integer.parseInt(sa[1]); br.close(); int x = Math.min(n, m); int y = Math.max(n, m); List<Integer> lx = new ArrayList<>(); List<Integer> ly = new ArrayList<>(); for (int i = 1; i < x; i++) { int end = Math.min(i + 2, y); for (int j = Math.max(i - 1, 1); j <= end; j++) { lx.add(i); ly.add(j); } } for (int j = Math.max(x - 1, 1); j <= y; j++) { lx.add(x); ly.add(j); } if (x == y && x % 3 == 2 && x > 2) { lx.add(x); ly.add(y - 2); int val = x + (y - 2) * 3; for (int i = lx.size() - 2; i >= 0; i--) { if (lx.get(i) + ly.get(i) * 3 == val) { lx.set(i, lx.get(i) + 1); ly.set(i, ly.get(i + 1) - 1); val = lx.get(i) + ly.get(i) * 3; } } } PrintWriter pw = new PrintWriter(System.out); pw.println(lx.size()); if (n > m) { List<Integer> tmp = lx; lx = ly; ly = tmp; } for (int i = 0; i < lx.size(); i++) { pw.println(lx.get(i) + " " + ly.get(i)); } pw.flush(); } } import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] sa = br.readLine().split(" "); int n = Integer.parseInt(sa[0]); int m = Integer.parseInt(sa[1]); br.close(); int x = Math.min(n, m); int y = Math.max(n, m); List<Integer> lx = new ArrayList<>(); List<Integer> ly = new ArrayList<>(); for (int i = 1; i < x; i++) { int end = Math.min(i + 2, y); for (int j = Math.max(i - 1, 1); j <= end; j++) { lx.add(i); ly.add(j); } } for (int j = Math.max(x - 1, 1); j <= y; j++) { lx.add(x); ly.add(j); } if (x == y && x % 2 == 1 && x > 1) { lx.add(x); ly.add(y - 2); int val = x + (y - 2) * 3; for (int i = lx.size() - 2; i >= 0; i--) { if (lx.get(i) + ly.get(i) * 3 == val) { lx.set(i, lx.get(i) + 1); ly.set(i, ly.get(i + 1) - 1); val = lx.get(i) + ly.get(i) * 3; } } } PrintWriter pw = new PrintWriter(System.out); pw.println(lx.size()); if (n > m) { List<Integer> tmp = lx; lx = ly; ly = tmp; } for (int i = 0; i < lx.size(); i++) { pw.println(lx.get(i) + " " + ly.get(i)); } pw.flush(); } }
ConDefects/ConDefects/Code/arc139_c/Java/31247848
condefects-java_data_626
import java.io.File; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws Exception{ //Scanner sc = new Scanner( new File("src/data.txt") ); Scanner sc = new Scanner( System.in ); // int n = Integer.parseInt(sc.next()); // long n = Long.parseLong(sc.next()); // int [] a = arrayInputInt(n, sc); // int [][] a = arrayInputInt(y, x, sc); // String s = sc.next(); // String w [] = s.split(""); // HashMap<String,Integer> map = new HashMap<String,Integer>(); // BigInteger bg = new BigInteger(sc.next()); // System.out.println(String.format("%.1f", 21.8755)); //arrayPrint(a, 0);//配列出力 空白なし //System.out.println(); //テンプレーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー int n = Integer.parseInt(sc.next()); int [] a = new int[n+1]; int [] idx = new int[n+1]; List<String> list = new ArrayList<String>(); for(int i = 1;i <= n;i++){ a[i] = Integer.parseInt(sc.next()); idx[a[i]] = i; } int cnt = 0; for(int i = 1;i <= n;i++) { if(a[i] != i) { list.add(a[i] +" "+ a[idx[i]]); int worka = a[idx[i]]; a[idx[i]] = a[i]; a[i] = worka; // arrayPrint(idx, 0); int workidx = a[idx[i]]; idx[workidx] = idx[i]; idx[i] = i; // arrayPrint(idx, 0); cnt++; } } // arrayPrint(a, 0); // arrayPrint(idx, 0); System.out.println(cnt); list.forEach(x -> System.out.println(x)); }//main終わりーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー //入出力系--------------------------------------------------------------------------------------------- //1次元配列の入力--------------------------------------------------------------------------------------------- public static int [] arrayInputInt(int n, Scanner sc) { int [] a = new int[n]; for(int i = 0;i < n;i++){ a[i] = Integer.parseInt(sc.next()); } return a; } public static long [] arrayInputLong(int n, Scanner sc) { long [] a = new long[n]; for(int i = 0;i < n;i++){ a[i] = Long.parseLong(sc.next()); } return a; } public static double [] arrayInputDouble(int n, Scanner sc) { double [] a = new double[n]; for(int i = 0;i < n;i++){ a[i] = Double.parseDouble(sc.next()); } return a; } public static String [] arrayInputString(int n, Scanner sc) { String [] a = new String[n]; for(int i = 0;i < n;i++){ a[i] = sc.next(); } return a; } //2次元配列の入力--------------------------------------------------------------------------------------------- public static int [][] arrayInputInt(int y, int x,Scanner sc) { int [][] a = new int[y][x]; for(int i = 0;i < y;i++){ for(int j = 0;j < x;j++) { a[i][j] = Integer.parseInt(sc.next()); } } return a; } public static long [][] arrayInputLong(int y, int x, Scanner sc) { long [][] a = new long[y][x]; for(int i = 0;i < y;i++){ for(int j = 0;j < x;j++) { a[i][j] = Long.parseLong(sc.next()); } } return a; } public static double [][] arrayInputDouble(int y, int x, Scanner sc) { double [][] a = new double[y][x]; for(int i = 0;i < y;i++){ for(int j = 0;j < x;j++) { a[i][j] = Double.parseDouble(sc.next()); } } return a; } public static String [][] arrayInputString(int y, int x, Scanner sc) { String [][] a = new String[y][x]; for(int i = 0;i < y;i++){ for(int j = 0;j < x;j++) { a[i][j] = sc.next(); } } return a; } //1次元配列の出力(blank 0:間の空白なし 1:あり)--------------------------------------------------------------------------------------------- public static void arrayPrint(int[] n, int blank) { for(int x = 0;x < n.length; x++) { System.out.print(n[x]); if(x != n.length -1 && blank == 1) System.out.print(" "); } System.out.println(); } public static void arrayPrint(long[] n, int blank) { for(int x = 0;x < n.length; x++) { System.out.print(n[x]); if(x != n.length -1 && blank == 1) System.out.print(" "); } System.out.println(); } public static void arrayPrint(double[] n, int blank) { for(int x = 0;x < n.length; x++) { System.out.print(n[x]); if(x != n.length -1 && blank == 1) System.out.print(" "); } System.out.println(); } public static void arrayPrint(String[] n, int blank) { for(int x = 0;x < n.length; x++) { System.out.print(n[x]); if(x != n.length -1 && blank == 1) System.out.print(" "); } System.out.println(); } //2次元配列の出力--------------------------------------------------------------------------------------------- public static void arrayPrint(int[][] n, int blank) { // System.out.println(n.length+" "+n[1].length); for(int y = 0 ;y < n.length ; y++) { for(int x = 0;x < n[1].length; x++) { System.out.print(n[y][x]); if(x != n[1].length -1 && blank == 1) System.out.print(" "); } System.out.println(); } } public static void arrayPrint(long[][] n, int blank) { for(int y = 0 ;y < n.length; y++) { for(int x = 0;x < n[1].length; x++) { System.out.print(n[y][x]); if(x != n[1].length -1 && blank == 1) System.out.print(" "); } System.out.println(); } } public static void arrayPrint(double[][] n, int blank) { for(int y = 0 ;y < n.length; y++) { for(int x = 0;x < n[1].length; x++) { System.out.print(n[y][x]); if(x != n[1].length -1 && blank == 1) System.out.print(" "); } System.out.println(); } } public static void arrayPrint(String[][] n, int blank) { for(int y = 0 ;y < n.length; y++) { for(int x = 0;x < n[1].length; x++) { System.out.print(n[y][x]); if(x != n[1].length -1 && blank == 1) System.out.print(" "); } System.out.println(); } } //ーーーーーーーーーーーーーーーーーーーーーーーーーー //数値を1桁ずつ取り出してarraylistに格納(向き逆--------------------------------------------------------------------------------------------- public static List<Integer> CutInt(int n) { List<Integer> list = new ArrayList<>(); while(n != 0) { list.add(n%10); n /=10; } return list; } //配列の値を大きい順に並べ替える--------------------------------------------------------------------------------------------- public static int [] SortDesc(int []n) { Arrays.sort(n); int [] m = new int[n.length]; for(int i=0;i<n.length;i++) { m[i] = n[n.length - i - 1]; } return m; } //int、long系 //10進数のintを2進数のStringで返す 値が65535より大きくなるときはintにできないので注意 public static String DtoB (int d) {//Decimal to Binary StringBuilder b = new StringBuilder(); if(d == 0) return "0"; while(d != 0) { int work = d % 2; b.insert(0, work); d /= 2; } return b.toString(); } //double系--------------------------------------------------------------------------------------------- //少数点のf桁までを出力(f+1桁を四捨五入) public static void doublePrint(double n, int f) { Integer i = Integer.valueOf(f); String s = "%."+i.toString()+"f"; System.out.println(String.format(s, n)); } //String系--------------------------------------------------------------------------------------------- //文字列を1文字ずつ空白開けて1行に出力 public static String [] separateString(String s) { String [] ss = s.split(""); for(int i = 0;i < ss.length;i++){ System.out.print(ss[i]); if(i != ss.length-1) System.out.print(" "); } return ss; } //hashmap系--------------------------------------------------------------------------------------------- //アルファベットをカウントするhashmap 小文字 public static LinkedHashMap<String,Integer> LowerABMap (LinkedHashMap<String,Integer> map) { map.put("a", 0); map.put("b", 0); map.put("c", 0); map.put("d", 0); map.put("e", 0); map.put("f", 0); map.put("g", 0); map.put("h", 0); map.put("i", 0); map.put("j", 0); map.put("k", 0); map.put("l", 0); map.put("m", 0); map.put("n", 0); map.put("o", 0); map.put("p", 0); map.put("q", 0); map.put("r", 0); map.put("s", 0); map.put("t", 0); map.put("u", 0); map.put("v", 0); map.put("w", 0); map.put("x", 0); map.put("y", 0); map.put("z", 0); return map; } //アルファベットをカウントするhashmap 大文字 public static LinkedHashMap<String,Integer> UpperABMap (LinkedHashMap<String,Integer> map) { map.put("A", 0); map.put("B", 0); map.put("C", 0); map.put("D", 0); map.put("E", 0); map.put("F", 0); map.put("G", 0); map.put("H", 0); map.put("I", 0); map.put("J", 0); map.put("K", 0); map.put("L", 0); map.put("M", 0); map.put("N", 0); map.put("O", 0); map.put("P", 0); map.put("Q", 0); map.put("R", 0); map.put("S", 0); map.put("T", 0); map.put("U", 0); map.put("V", 0); map.put("W", 0); map.put("X", 0); map.put("Y", 0); map.put("Z", 0); return map; } //数学系ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー //階乗(!n) static long factorial(int n) { long ans = 1; for(int i =2; i <= n; i++) { ans *=(long)i; } return ans; } //順列(nPk) static long permutation(int n, int k) { long ans = 1; for(int i = n - k + 1; i <= n; i++) { ans *=(long)i; } return ans; } //組合せ(nCk) static long combination(int n, int k) { return permutation(n, k) / factorial(k); } } import java.io.File; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws Exception{ //Scanner sc = new Scanner( new File("src/data.txt") ); Scanner sc = new Scanner( System.in ); // int n = Integer.parseInt(sc.next()); // long n = Long.parseLong(sc.next()); // int [] a = arrayInputInt(n, sc); // int [][] a = arrayInputInt(y, x, sc); // String s = sc.next(); // String w [] = s.split(""); // HashMap<String,Integer> map = new HashMap<String,Integer>(); // BigInteger bg = new BigInteger(sc.next()); // System.out.println(String.format("%.1f", 21.8755)); //arrayPrint(a, 0);//配列出力 空白なし //System.out.println(); //テンプレーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー int n = Integer.parseInt(sc.next()); int [] a = new int[n+1]; int [] idx = new int[n+1]; List<String> list = new ArrayList<String>(); for(int i = 1;i <= n;i++){ a[i] = Integer.parseInt(sc.next()); idx[a[i]] = i; } int cnt = 0; for(int i = 1;i <= n;i++) { if(a[i] != i) { list.add(i +" "+ idx[i]); int worka = a[idx[i]]; a[idx[i]] = a[i]; a[i] = worka; // arrayPrint(idx, 0); int workidx = a[idx[i]]; idx[workidx] = idx[i]; idx[i] = i; // arrayPrint(idx, 0); cnt++; } } // arrayPrint(a, 0); // arrayPrint(idx, 0); System.out.println(cnt); list.forEach(x -> System.out.println(x)); }//main終わりーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー //入出力系--------------------------------------------------------------------------------------------- //1次元配列の入力--------------------------------------------------------------------------------------------- public static int [] arrayInputInt(int n, Scanner sc) { int [] a = new int[n]; for(int i = 0;i < n;i++){ a[i] = Integer.parseInt(sc.next()); } return a; } public static long [] arrayInputLong(int n, Scanner sc) { long [] a = new long[n]; for(int i = 0;i < n;i++){ a[i] = Long.parseLong(sc.next()); } return a; } public static double [] arrayInputDouble(int n, Scanner sc) { double [] a = new double[n]; for(int i = 0;i < n;i++){ a[i] = Double.parseDouble(sc.next()); } return a; } public static String [] arrayInputString(int n, Scanner sc) { String [] a = new String[n]; for(int i = 0;i < n;i++){ a[i] = sc.next(); } return a; } //2次元配列の入力--------------------------------------------------------------------------------------------- public static int [][] arrayInputInt(int y, int x,Scanner sc) { int [][] a = new int[y][x]; for(int i = 0;i < y;i++){ for(int j = 0;j < x;j++) { a[i][j] = Integer.parseInt(sc.next()); } } return a; } public static long [][] arrayInputLong(int y, int x, Scanner sc) { long [][] a = new long[y][x]; for(int i = 0;i < y;i++){ for(int j = 0;j < x;j++) { a[i][j] = Long.parseLong(sc.next()); } } return a; } public static double [][] arrayInputDouble(int y, int x, Scanner sc) { double [][] a = new double[y][x]; for(int i = 0;i < y;i++){ for(int j = 0;j < x;j++) { a[i][j] = Double.parseDouble(sc.next()); } } return a; } public static String [][] arrayInputString(int y, int x, Scanner sc) { String [][] a = new String[y][x]; for(int i = 0;i < y;i++){ for(int j = 0;j < x;j++) { a[i][j] = sc.next(); } } return a; } //1次元配列の出力(blank 0:間の空白なし 1:あり)--------------------------------------------------------------------------------------------- public static void arrayPrint(int[] n, int blank) { for(int x = 0;x < n.length; x++) { System.out.print(n[x]); if(x != n.length -1 && blank == 1) System.out.print(" "); } System.out.println(); } public static void arrayPrint(long[] n, int blank) { for(int x = 0;x < n.length; x++) { System.out.print(n[x]); if(x != n.length -1 && blank == 1) System.out.print(" "); } System.out.println(); } public static void arrayPrint(double[] n, int blank) { for(int x = 0;x < n.length; x++) { System.out.print(n[x]); if(x != n.length -1 && blank == 1) System.out.print(" "); } System.out.println(); } public static void arrayPrint(String[] n, int blank) { for(int x = 0;x < n.length; x++) { System.out.print(n[x]); if(x != n.length -1 && blank == 1) System.out.print(" "); } System.out.println(); } //2次元配列の出力--------------------------------------------------------------------------------------------- public static void arrayPrint(int[][] n, int blank) { // System.out.println(n.length+" "+n[1].length); for(int y = 0 ;y < n.length ; y++) { for(int x = 0;x < n[1].length; x++) { System.out.print(n[y][x]); if(x != n[1].length -1 && blank == 1) System.out.print(" "); } System.out.println(); } } public static void arrayPrint(long[][] n, int blank) { for(int y = 0 ;y < n.length; y++) { for(int x = 0;x < n[1].length; x++) { System.out.print(n[y][x]); if(x != n[1].length -1 && blank == 1) System.out.print(" "); } System.out.println(); } } public static void arrayPrint(double[][] n, int blank) { for(int y = 0 ;y < n.length; y++) { for(int x = 0;x < n[1].length; x++) { System.out.print(n[y][x]); if(x != n[1].length -1 && blank == 1) System.out.print(" "); } System.out.println(); } } public static void arrayPrint(String[][] n, int blank) { for(int y = 0 ;y < n.length; y++) { for(int x = 0;x < n[1].length; x++) { System.out.print(n[y][x]); if(x != n[1].length -1 && blank == 1) System.out.print(" "); } System.out.println(); } } //ーーーーーーーーーーーーーーーーーーーーーーーーーー //数値を1桁ずつ取り出してarraylistに格納(向き逆--------------------------------------------------------------------------------------------- public static List<Integer> CutInt(int n) { List<Integer> list = new ArrayList<>(); while(n != 0) { list.add(n%10); n /=10; } return list; } //配列の値を大きい順に並べ替える--------------------------------------------------------------------------------------------- public static int [] SortDesc(int []n) { Arrays.sort(n); int [] m = new int[n.length]; for(int i=0;i<n.length;i++) { m[i] = n[n.length - i - 1]; } return m; } //int、long系 //10進数のintを2進数のStringで返す 値が65535より大きくなるときはintにできないので注意 public static String DtoB (int d) {//Decimal to Binary StringBuilder b = new StringBuilder(); if(d == 0) return "0"; while(d != 0) { int work = d % 2; b.insert(0, work); d /= 2; } return b.toString(); } //double系--------------------------------------------------------------------------------------------- //少数点のf桁までを出力(f+1桁を四捨五入) public static void doublePrint(double n, int f) { Integer i = Integer.valueOf(f); String s = "%."+i.toString()+"f"; System.out.println(String.format(s, n)); } //String系--------------------------------------------------------------------------------------------- //文字列を1文字ずつ空白開けて1行に出力 public static String [] separateString(String s) { String [] ss = s.split(""); for(int i = 0;i < ss.length;i++){ System.out.print(ss[i]); if(i != ss.length-1) System.out.print(" "); } return ss; } //hashmap系--------------------------------------------------------------------------------------------- //アルファベットをカウントするhashmap 小文字 public static LinkedHashMap<String,Integer> LowerABMap (LinkedHashMap<String,Integer> map) { map.put("a", 0); map.put("b", 0); map.put("c", 0); map.put("d", 0); map.put("e", 0); map.put("f", 0); map.put("g", 0); map.put("h", 0); map.put("i", 0); map.put("j", 0); map.put("k", 0); map.put("l", 0); map.put("m", 0); map.put("n", 0); map.put("o", 0); map.put("p", 0); map.put("q", 0); map.put("r", 0); map.put("s", 0); map.put("t", 0); map.put("u", 0); map.put("v", 0); map.put("w", 0); map.put("x", 0); map.put("y", 0); map.put("z", 0); return map; } //アルファベットをカウントするhashmap 大文字 public static LinkedHashMap<String,Integer> UpperABMap (LinkedHashMap<String,Integer> map) { map.put("A", 0); map.put("B", 0); map.put("C", 0); map.put("D", 0); map.put("E", 0); map.put("F", 0); map.put("G", 0); map.put("H", 0); map.put("I", 0); map.put("J", 0); map.put("K", 0); map.put("L", 0); map.put("M", 0); map.put("N", 0); map.put("O", 0); map.put("P", 0); map.put("Q", 0); map.put("R", 0); map.put("S", 0); map.put("T", 0); map.put("U", 0); map.put("V", 0); map.put("W", 0); map.put("X", 0); map.put("Y", 0); map.put("Z", 0); return map; } //数学系ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー //階乗(!n) static long factorial(int n) { long ans = 1; for(int i =2; i <= n; i++) { ans *=(long)i; } return ans; } //順列(nPk) static long permutation(int n, int k) { long ans = 1; for(int i = n - k + 1; i <= n; i++) { ans *=(long)i; } return ans; } //組合せ(nCk) static long combination(int n, int k) { return permutation(n, k) / factorial(k); } }
ConDefects/ConDefects/Code/abc350_c/Java/54455016
condefects-java_data_627
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int maxQuery = 20; //最も右にある0 int l = 0; //最も左にある1 int r = n; // int a[] = new int[n]; // Arrays.fill(a, -1); while(l + 1 < r) { int mid = (l + r)/2; System.out.println("? " + (mid + 1)); int tmp = sc.nextInt(); if(tmp == 0) { l = mid; } else { r = mid; } } System.out.println(l + 1); } } import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int maxQuery = 20; //最も右にある0 int l = 0; //最も左にある1 int r = n; // int a[] = new int[n]; // Arrays.fill(a, -1); while(l + 1 < r) { int mid = (l + r)/2; System.out.println("? " + (mid + 1)); int tmp = sc.nextInt(); if(tmp == 0) { l = mid; } else { r = mid; } } System.out.println("! " + (l + 1)); } }
ConDefects/ConDefects/Code/abc299_d/Java/44425477
condefects-java_data_628
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int leftPointer = 1; int rightPointer = n; while(rightPointer - leftPointer > 1) { int mid = (leftPointer + rightPointer) / 2; System.out.println("? " + mid); int s = sc.nextInt(); if(s == 0) { leftPointer = mid; } else { rightPointer = mid; } } System.out.println(leftPointer); out.close(); } /** * returns n^k */ public static long power(long n, long k) { if (k == 0) { return 1; } else if (k == 1) { return n; } else if (k % 2 == 0) { long temp = power(n, k / 2); return temp * temp; } else { long temp = power(n, (k - 1) / 2); return n * temp * temp; } } public static PrintWriter out; public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Pair<T, U> { T first; U second; public Pair(T first, U second) { this.first = first; this.second = second; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; if (!Objects.equals(first, pair.first)) return false; return Objects.equals(second, pair.second); } @Override public int hashCode() { int result = first != null ? first.hashCode() : 0; result = 31 * result + (second != null ? second.hashCode() : 0); return result; } @Override public String toString() { return "Pair{" + "first=" + first + ", second=" + second + '}'; } } static class Node { List<Node> adj = new ArrayList<>(); int value; public Node() { } public Node(int value) { this.value = value; } public static void dfs(List<Node> graph) { Set<Node> visited = new HashSet<>(); for (Node node : graph) { if (!visited.contains(node)) { node.dfsFromThisNodeHelper(visited); } } } public void dfsFromThisNode() { dfsFromThisNodeHelper(new HashSet<>()); } private void dfsFromThisNodeHelper(Set<Node> visited) { visited.add(this); for (Node neighbour : this.adj) { if (!visited.contains(neighbour)) { neighbour.dfsFromThisNodeHelper(visited); } } } public static void bfs(List<Node> graph) { Set<Node> discovered = new HashSet<>(); for (Node node : graph) { if (!discovered.contains(node)) { discovered.add(node); node.bfsFromThisNodeHelper(discovered); } } } public void bfsFromThisNode() { Set<Node> discovered = new HashSet<>(); bfsFromThisNodeHelper(discovered); } private void bfsFromThisNodeHelper(Set<Node> discovered) { Queue<Node> bfs = new LinkedList<>(); bfs.add(this); while (!bfs.isEmpty()) { Node currentNode = bfs.poll(); for (Node neighbour : currentNode.adj) { if (!discovered.contains(neighbour)) { bfs.add(neighbour); discovered.add(neighbour); } } } } } } import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int leftPointer = 1; int rightPointer = n; while(rightPointer - leftPointer > 1) { int mid = (leftPointer + rightPointer) / 2; System.out.println("? " + mid); int s = sc.nextInt(); if(s == 0) { leftPointer = mid; } else { rightPointer = mid; } } System.out.println("! " + leftPointer); out.close(); } /** * returns n^k */ public static long power(long n, long k) { if (k == 0) { return 1; } else if (k == 1) { return n; } else if (k % 2 == 0) { long temp = power(n, k / 2); return temp * temp; } else { long temp = power(n, (k - 1) / 2); return n * temp * temp; } } public static PrintWriter out; public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Pair<T, U> { T first; U second; public Pair(T first, U second) { this.first = first; this.second = second; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; if (!Objects.equals(first, pair.first)) return false; return Objects.equals(second, pair.second); } @Override public int hashCode() { int result = first != null ? first.hashCode() : 0; result = 31 * result + (second != null ? second.hashCode() : 0); return result; } @Override public String toString() { return "Pair{" + "first=" + first + ", second=" + second + '}'; } } static class Node { List<Node> adj = new ArrayList<>(); int value; public Node() { } public Node(int value) { this.value = value; } public static void dfs(List<Node> graph) { Set<Node> visited = new HashSet<>(); for (Node node : graph) { if (!visited.contains(node)) { node.dfsFromThisNodeHelper(visited); } } } public void dfsFromThisNode() { dfsFromThisNodeHelper(new HashSet<>()); } private void dfsFromThisNodeHelper(Set<Node> visited) { visited.add(this); for (Node neighbour : this.adj) { if (!visited.contains(neighbour)) { neighbour.dfsFromThisNodeHelper(visited); } } } public static void bfs(List<Node> graph) { Set<Node> discovered = new HashSet<>(); for (Node node : graph) { if (!discovered.contains(node)) { discovered.add(node); node.bfsFromThisNodeHelper(discovered); } } } public void bfsFromThisNode() { Set<Node> discovered = new HashSet<>(); bfsFromThisNodeHelper(discovered); } private void bfsFromThisNodeHelper(Set<Node> discovered) { Queue<Node> bfs = new LinkedList<>(); bfs.add(this); while (!bfs.isEmpty()) { Node currentNode = bfs.poll(); for (Node neighbour : currentNode.adj) { if (!discovered.contains(neighbour)) { bfs.add(neighbour); discovered.add(neighbour); } } } } } }
ConDefects/ConDefects/Code/abc299_d/Java/43536224
condefects-java_data_629
import java.util.*; public class Main{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); String s = scan.nextLine(); int cnt = scan.nextInt(); int start = 0; int end = 0; int maxCnt = 0; while(end > s.length()){ if(s.charAt(end) == 'X'){ end++; maxCnt = Math.max(maxCnt, end - start); continue; } else if(cnt > 0){ end++; cnt--; maxCnt = Math.max(maxCnt, end - start); continue; } else{ if(s.charAt(start) == 'X'){ start++; } else{ cnt++; start++; } } } System.out.println(maxCnt); } } import java.util.*; public class Main{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); String s = scan.nextLine(); int cnt = scan.nextInt(); int start = 0; int end = 0; int maxCnt = 0; while(end < s.length()){ if(s.charAt(end) == 'X'){ end++; maxCnt = Math.max(maxCnt, end - start); continue; } else if(cnt > 0){ end++; cnt--; maxCnt = Math.max(maxCnt, end - start); continue; } else{ if(s.charAt(start) == 'X'){ start++; } else{ cnt++; start++; } } } System.out.println(maxCnt); } }
ConDefects/ConDefects/Code/abc229_d/Java/36116766
condefects-java_data_630
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringJoiner; public class Main { static int N; static int[] U, V; public static void main(String[] args) { var sc = new FastScanner(System.in); N = sc.nextInt(); U = new int[N-1]; V = new int[N-1]; for (int i = 0; i < N - 1; i++) { U[i] = sc.nextInt()-1; V[i] = sc.nextInt()-1; } writeSingleLine(solve()); } static int[] solve() { // 次数1の点の横が必ず星の中心 int[] cnt = new int[N]; int[] q = new int[N]; int s = 0, t = 0; var G = adjB(N, U, V); for (int i = 0; i < N; i++) { cnt[i] = G[i].length; if( cnt[i] == 1 ) { q[t++] = i; } } var ans = new ArrayList<Integer>(); while( s != t ) { int a = q[s++]; if( cnt[a] != 1 ) continue; int center = -1; for (int b : G[a]) { if( cnt[b] != 0 ) { center = b; break; } } ans.add( cnt[center] ); for (int frontier : G[center]) { cnt[frontier]--; if( cnt[frontier] == 1 ) { for (int next : G[frontier]) { if( next != center ) { q[t++] = next; cnt[next]--; cnt[frontier]--; } } } } } return ans.stream().mapToInt(i -> i).toArray(); } static int[][] adjB(int n, int[] from, int[] to) { int[][] adj = new int[n][]; int[] cnt = new int[n]; for (int f : from) { cnt[f]++; } for (int t : to) { cnt[t]++; } for (int i = 0; i < n; i++) { adj[i] = new int[cnt[i]]; } for (int i = 0; i < from.length; i++) { adj[from[i]][--cnt[from[i]]] = to[i]; adj[to[i]][--cnt[to[i]]] = from[i]; } return adj; } static void writeLines(int[] as) { var pw = new PrintWriter(System.out); for (var a : as) pw.println(a); pw.flush(); } static void writeLines(long[] as) { var pw = new PrintWriter(System.out); for (var a : as) pw.println(a); pw.flush(); } static void writeSingleLine(int[] as) { var pw = new PrintWriter(System.out); for (var i = 0; i < as.length; i++) { if (i != 0) pw.print(" "); pw.print(as[i]); } pw.println(); pw.flush(); } static void debug(Object... args) { var j = new StringJoiner(" "); for (var arg : args) { if (arg == null) j.add("null"); else if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg)); else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg)); else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg)); else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg)); else j.add(arg.toString()); } System.err.println(j); } @SuppressWarnings("unused") private static class FastScanner { private final InputStream in; private final byte[] buffer = new byte[1024]; private int curbuf; private int lenbuf; public FastScanner(InputStream in) { this.in = in; this.curbuf = this.lenbuf = 0; } public boolean hasNextByte() { if (curbuf >= lenbuf) { curbuf = 0; try { lenbuf = in.read(buffer); } catch (IOException e) { throw new RuntimeException(); } if (lenbuf <= 0) return false; } return true; } private int readByte() { if (hasNextByte()) return buffer[curbuf++]; else return -1; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private void skip() { while (hasNextByte() && isSpaceChar(buffer[curbuf])) curbuf++; } public boolean hasNext() { skip(); return hasNextByte(); } public String next() { if (!hasNext()) throw new RuntimeException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { if (!hasNext()) throw new RuntimeException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } int res = 0; do { if (c < '0' || c > '9') throw new RuntimeException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public long nextLong() { if (!hasNext()) throw new RuntimeException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } long res = 0; do { if (c < '0' || c > '9') throw new RuntimeException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[][] nextCharMap(int n, int m) { char[][] map = new char[n][m]; for (int i = 0; i < n; i++) map[i] = next().toCharArray(); return map; } } } import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringJoiner; public class Main { static int N; static int[] U, V; public static void main(String[] args) { var sc = new FastScanner(System.in); N = sc.nextInt(); U = new int[N-1]; V = new int[N-1]; for (int i = 0; i < N - 1; i++) { U[i] = sc.nextInt()-1; V[i] = sc.nextInt()-1; } writeSingleLine(solve()); } static int[] solve() { // 次数1の点の横が必ず星の中心 int[] cnt = new int[N]; int[] q = new int[N]; int s = 0, t = 0; var G = adjB(N, U, V); for (int i = 0; i < N; i++) { cnt[i] = G[i].length; if( cnt[i] == 1 ) { q[t++] = i; } } var ans = new ArrayList<Integer>(); while( s != t ) { int a = q[s++]; if( cnt[a] != 1 ) continue; int center = -1; for (int b : G[a]) { if( cnt[b] != 0 ) { center = b; break; } } ans.add( cnt[center] ); for (int frontier : G[center]) { cnt[frontier]--; if( cnt[frontier] == 1 ) { for (int next : G[frontier]) { if( next != center ) { q[t++] = next; cnt[next]--; cnt[frontier]--; } } } } } return ans.stream().mapToInt(i -> i).sorted().toArray(); } static int[][] adjB(int n, int[] from, int[] to) { int[][] adj = new int[n][]; int[] cnt = new int[n]; for (int f : from) { cnt[f]++; } for (int t : to) { cnt[t]++; } for (int i = 0; i < n; i++) { adj[i] = new int[cnt[i]]; } for (int i = 0; i < from.length; i++) { adj[from[i]][--cnt[from[i]]] = to[i]; adj[to[i]][--cnt[to[i]]] = from[i]; } return adj; } static void writeLines(int[] as) { var pw = new PrintWriter(System.out); for (var a : as) pw.println(a); pw.flush(); } static void writeLines(long[] as) { var pw = new PrintWriter(System.out); for (var a : as) pw.println(a); pw.flush(); } static void writeSingleLine(int[] as) { var pw = new PrintWriter(System.out); for (var i = 0; i < as.length; i++) { if (i != 0) pw.print(" "); pw.print(as[i]); } pw.println(); pw.flush(); } static void debug(Object... args) { var j = new StringJoiner(" "); for (var arg : args) { if (arg == null) j.add("null"); else if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg)); else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg)); else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg)); else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg)); else j.add(arg.toString()); } System.err.println(j); } @SuppressWarnings("unused") private static class FastScanner { private final InputStream in; private final byte[] buffer = new byte[1024]; private int curbuf; private int lenbuf; public FastScanner(InputStream in) { this.in = in; this.curbuf = this.lenbuf = 0; } public boolean hasNextByte() { if (curbuf >= lenbuf) { curbuf = 0; try { lenbuf = in.read(buffer); } catch (IOException e) { throw new RuntimeException(); } if (lenbuf <= 0) return false; } return true; } private int readByte() { if (hasNextByte()) return buffer[curbuf++]; else return -1; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private void skip() { while (hasNextByte() && isSpaceChar(buffer[curbuf])) curbuf++; } public boolean hasNext() { skip(); return hasNextByte(); } public String next() { if (!hasNext()) throw new RuntimeException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { if (!hasNext()) throw new RuntimeException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } int res = 0; do { if (c < '0' || c > '9') throw new RuntimeException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public long nextLong() { if (!hasNext()) throw new RuntimeException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } long res = 0; do { if (c < '0' || c > '9') throw new RuntimeException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[][] nextCharMap(int n, int m) { char[][] map = new char[n][m]; for (int i = 0; i < n; i++) map[i] = next().toCharArray(); return map; } } }
ConDefects/ConDefects/Code/abc303_e/Java/41847247
condefects-java_data_631
import java.util.*; import static java.lang.Math.abs; import static java.lang.Math.min; /** * F - Main Street */ class Main { public static void main(String[] arg) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); for (int i = 0; i < t; i++) { long b = scanner.nextLong(); long k = scanner.nextLong(); long sx = scanner.nextLong(); long sy = scanner.nextLong(); long gx = scanner.nextLong(); long gy = scanner.nextLong(); Pos[] spos = positions(sx, sy, b); Pos[] gpos = positions(gx, gy, b); long m = Long.MAX_VALUE; for (Pos sp : spos) { for (Pos gp : gpos) { m = min(dist(sx, sy, sp.x, sp.y, b, k) + dist(sp.x, sp.y, gp.x, gp.y, b, k) + dist(gp.x, gp.y, gx, gy, b, k), m); } } System.out.println(m); } } public static class Pos { final long x; final long y; Pos(long x, long y) { this.x = x; this.y = y; } } static Pos[] positions(long x, long y, long b) { long xb = x % b; long yb = y % b; return new Pos[] { new Pos(x, y), new Pos(x - xb, y), new Pos(x, y - yb), new Pos(x - xb + b, y), new Pos(x, y - yb + b)}; } static long dist(long x1, long y1, long x2, long y2, long b, long k) { long d = abs(x2 - x1) + abs(y2 - y1); long x1b = x1 % b; long y1b = y1 % b; long x2b = x2 % b; long y2b = y2 % b; if ((x1b == 0 && y2b == 0) || (y1b == 0 && x2b == 0)) { } else if (x1b == 0 && x2b == 0) { if (y1 - y1b == y2 - y2b && x1 != x2) { long vy1 = y1b + y2b; long vy2 = (b - y1b) + (b - y2b); d = abs(x2 - x1) + min(vy1, vy2); } } else if (y1b == 0 && y2b == 0) { if (x1 - x1b == x2 - x2b && y1 != y2) { long vx1 = x1b + x2b; long vx2 = (b - x1b) + (b - x2b); d = min(vx1, vx2) + abs(y2 - y1); } } else { d *= k; } return d; } } import java.util.*; import static java.lang.Math.abs; import static java.lang.Math.min; /** * F - Main Street */ class Main { public static void main(String[] arg) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); for (int i = 0; i < t; i++) { long b = scanner.nextLong(); long k = scanner.nextLong(); long sx = scanner.nextLong(); long sy = scanner.nextLong(); long gx = scanner.nextLong(); long gy = scanner.nextLong(); Pos[] spos = positions(sx, sy, b); Pos[] gpos = positions(gx, gy, b); long m = Long.MAX_VALUE; for (Pos sp : spos) { for (Pos gp : gpos) { m = min(dist(sx, sy, sp.x, sp.y, b, k) + dist(sp.x, sp.y, gp.x, gp.y, b, k) + dist(gp.x, gp.y, gx, gy, b, k), m); } } System.out.println(m); } } public static class Pos { final long x; final long y; Pos(long x, long y) { this.x = x; this.y = y; } } static Pos[] positions(long x, long y, long b) { long xb = x % b; long yb = y % b; return new Pos[] { new Pos(x, y), new Pos(x - xb, y), new Pos(x, y - yb), new Pos(x - xb + b, y), new Pos(x, y - yb + b)}; } static long dist(long x1, long y1, long x2, long y2, long b, long k) { long d = abs(x2 - x1) + abs(y2 - y1); long x1b = x1 % b; long y1b = y1 % b; long x2b = x2 % b; long y2b = y2 % b; if ((x1b == 0 && y2b == 0) || (y1b == 0 && x2b == 0)) { } else if (x1b == 0 && x2b == 0) { if (y1 - y1b == y2 - y2b && x1 != x2) { long vy1 = y1b + y2b; long vy2 = (b - y1b) + (b - y2b); d = abs(x2 - x1) + min(vy1, vy2); d = min(d, abs(x2 - x1) * k + abs(y2 - y1)); } } else if (y1b == 0 && y2b == 0) { if (x1 - x1b == x2 - x2b && y1 != y2) { long vx1 = x1b + x2b; long vx2 = (b - x1b) + (b - x2b); d = min(vx1, vx2) + abs(y2 - y1); d = min(d, abs(x2 - x1) + abs(y2 - y1) * k); } } else { d *= k; } return d; } }
ConDefects/ConDefects/Code/abc258_f/Java/32969397
condefects-java_data_632
import java.io.*; import java.util.*; public class Main { //--------------------------INPUT READER---------------------------------// static class fs { public BufferedReader br; StringTokenizer st = new StringTokenizer(""); public fs() { this(System.in); } public fs(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String ns() { return next(); } int[] na(long nn) { int n = (int) nn; int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } long[] nal(long nn) { int n = (int) nn; long[] l = new long[n]; for(int i = 0; i < n; i++) l[i] = nl(); return l; } } //-----------------------------------------------------------------------// //---------------------------PRINTER-------------------------------------// static class Printer { static PrintWriter w; public Printer() {this(System.out);} public Printer(OutputStream os) { w = new PrintWriter(os); } public void p(int i) {w.println(i);} public void p(long l) {w.println(l);} public void p(double d) {w.println(d);} public void p(String s) { w.println(s);} public void pr(int i) {w.print(i);} public void pr(long l) {w.print(l);} public void pr(double d) {w.print(d);} public void pr(String s) { w.print(s);} public void pl() {w.println();} public void close() {w.close();} } //-----------------------------------------------------------------------// //--------------------------VARIABLES------------------------------------// static fs sc = new fs(); static OutputStream outputStream = System.out; static Printer w = new Printer(outputStream); static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; static int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; static long mod = 1000000007; //-----------------------------------------------------------------------// //--------------------------ADMIN_MODE-----------------------------------// private static void ADMIN_MODE() throws IOException { String DIR = "ADMIN"; try { DIR = System.getProperty("user.dir"); } catch (Exception e) { } if(new File(DIR).getName().equals("LOCAL")) { w = new Printer(new FileOutputStream("output.txt")); sc = new fs(new FileInputStream("input.txt")); } } //-----------------------------------------------------------------------// //----------------------------START--------------------------------------// public static void main(String[] args) throws IOException { ADMIN_MODE(); int t = sc.ni();while(t-->0) solve(); w.close(); } static void solve() throws IOException { char[] strr = sc.ns().toCharArray(); long given = Long.parseLong(String.valueOf(strr)); int n = strr.length; int[] arr = new int[n]; for(int i = 0; i < n; i++) { arr[i] = Integer.parseInt(strr[i]+""); } StringBuilder sb = new StringBuilder(); for(int i = 0; i < n-1; i++) { sb.append(9); } long best = Long.parseLong(sb.toString()); for(int i = 0; i < n-1; i++) { if(n%(i+1)!=0) continue; sb = new StringBuilder(String.valueOf(strr, 0, (i+1))); int q = n/(i+1); StringBuilder res = new StringBuilder(); for(int j = 0; j < q; j++) { res.append(sb); } long curr = Long.parseLong(res.toString()); if(curr <= given) { best = Math.max(best, curr); continue; } if(sb.charAt(sb.length()-1)=='0') continue; long prev = Long.parseLong(sb.toString()); prev--; sb = new StringBuilder(Long.toString(prev)); res = new StringBuilder(); for(int j = 0; j < q; j++) { res.append(sb); } curr = Long.parseLong(res.toString()); if(curr <= given) { best = Math.max(best, curr); } } w.p(best); } } import java.io.*; import java.util.*; public class Main { //--------------------------INPUT READER---------------------------------// static class fs { public BufferedReader br; StringTokenizer st = new StringTokenizer(""); public fs() { this(System.in); } public fs(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String ns() { return next(); } int[] na(long nn) { int n = (int) nn; int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } long[] nal(long nn) { int n = (int) nn; long[] l = new long[n]; for(int i = 0; i < n; i++) l[i] = nl(); return l; } } //-----------------------------------------------------------------------// //---------------------------PRINTER-------------------------------------// static class Printer { static PrintWriter w; public Printer() {this(System.out);} public Printer(OutputStream os) { w = new PrintWriter(os); } public void p(int i) {w.println(i);} public void p(long l) {w.println(l);} public void p(double d) {w.println(d);} public void p(String s) { w.println(s);} public void pr(int i) {w.print(i);} public void pr(long l) {w.print(l);} public void pr(double d) {w.print(d);} public void pr(String s) { w.print(s);} public void pl() {w.println();} public void close() {w.close();} } //-----------------------------------------------------------------------// //--------------------------VARIABLES------------------------------------// static fs sc = new fs(); static OutputStream outputStream = System.out; static Printer w = new Printer(outputStream); static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; static int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; static long mod = 1000000007; //-----------------------------------------------------------------------// //--------------------------ADMIN_MODE-----------------------------------// private static void ADMIN_MODE() throws IOException { String DIR = "ADMIN"; try { DIR = System.getProperty("user.dir"); } catch (Exception e) { } if(new File(DIR).getName().equals("LOCAL")) { w = new Printer(new FileOutputStream("output.txt")); sc = new fs(new FileInputStream("input.txt")); } } //-----------------------------------------------------------------------// //----------------------------START--------------------------------------// public static void main(String[] args) throws IOException { ADMIN_MODE(); int t = sc.ni();while(t-->0) solve(); w.close(); } static void solve() throws IOException { char[] strr = sc.ns().toCharArray(); long given = Long.parseLong(String.valueOf(strr)); int n = strr.length; int[] arr = new int[n]; for(int i = 0; i < n; i++) { arr[i] = Integer.parseInt(strr[i]+""); } StringBuilder sb = new StringBuilder(); for(int i = 0; i < n-1; i++) { sb.append(9); } long best = Long.parseLong(sb.toString()); for(int i = 0; i < n-1; i++) { if(n%(i+1)!=0) continue; sb = new StringBuilder(String.valueOf(strr, 0, (i+1))); int q = n/(i+1); StringBuilder res = new StringBuilder(); for(int j = 0; j < q; j++) { res.append(sb); } long curr = Long.parseLong(res.toString()); if(curr <= given) { best = Math.max(best, curr); continue; } long prev = Long.parseLong(sb.toString()); prev--; if(Long.toString(prev).length() != sb.length()) continue; sb = new StringBuilder(Long.toString(prev)); res = new StringBuilder(); for(int j = 0; j < q; j++) { res.append(sb); } curr = Long.parseLong(res.toString()); if(curr <= given) { best = Math.max(best, curr); } } w.p(best); } }
ConDefects/ConDefects/Code/arc141_a/Java/32252225
condefects-java_data_633
/* @supplement-auto-stop @supplement-println-stop */ import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.PriorityQueue; import java.util.Scanner; public class Main{ public static void main(String[] args){ int t = in.nextInt(); lp : for(int i = 0; i < t; i++){ long n = in.nextLong(); String str = (n + ""); int len = str.length(); long l = 0; lx : for(int x = 2; x < len; x++){if(len % x == 0){ String s = str.substring(0, len / x); boolean b = true; long alt = Long.parseLong(s.repeat(x)); if(alt > n){s = "" + (Long.parseLong(s)-1); alt = Long.parseLong(s.repeat(x)); b = false;}; if(alt > l){l = alt;}; if(b){break lx;}; };}; String s = str.substring(0, 1); long alt = Long.parseLong(s.repeat(len)); if(alt > n){int z = Integer.parseInt(s); if(z == 1){alt = Long.parseLong("9".repeat(len-1));}else{alt = Long.parseLong(((z-1) + "").repeat(len));};}; if(alt > l){l = alt;}; out.println(l); }; } public static boolean calc(String str, int l, long n){ String rep = str.substring(0, str.length() / l); if(Long.parseLong(rep.repeat(l)) > n){return false;}; return true; } public static String val(String str, int l, long n){ String rep = str.substring(0, str.length() / l); if(Long.parseLong(rep.repeat(l)) > n){rep = "" + (Integer.parseInt(rep) - 1);}; return rep.repeat(l); } public static String val(String str, int l, long n, boolean b){ String rep = str.substring(0, str.length() / l); if(! b){rep = "" + (Integer.parseInt(rep) - 1);}; return rep.repeat(l); } }//main class in{ private static Scanner sc = new Scanner(System.in); public static int[] nextInt(int len){ int[] ret = new int[len]; for(int i = 0; i < len; i++){ret[i] = nextInt();}; return ret; } public static int[][] nextInt(int x, int y){ int[][] ret = new int[x][y]; for(int i = 0; i < x; i++){for(int j = 0; j < y; j++){ret[i][j] = nextInt();};}; return ret; } public static int nextInt(){return Integer.parseInt(sc.next());} public static long[] nextLong(int len){ long[] ret = new long[len]; for(int i = 0; i < len; i++){ret[i] = nextLong();}; return ret; } public static long[][] nextLong(int x, int y){ long[][] ret = new long[x][y]; for(int i = 0; i < x; i++){for(int j = 0; j < y; j++){ret[i][j] = nextInt();};}; return ret; } public static long nextLong(){return Long.parseLong(sc.next());} public static String next(){return sc.next();} public static String[] nextString(int len){ String[] ret = new String[len]; for(int i = 0; i < len; i++){ret[i] = next();}; return ret; } }//input class out{ public static void println(int... list){ StringBuilder sb = new StringBuilder(); sb.append(list[0]); for(int i = 1; i < list.length; i++){sb.append(" ").append(list[i]);}; System.out.println(sb.toString()); } public static void println(long... list){ StringBuilder sb = new StringBuilder(); sb.append(list[0]); for(int i = 1; i < list.length; i++){sb.append(" ").append(list[i]);}; System.out.println(sb.toString()); } public static void println(String text){System.out.println(text);} public static void println(int i){System.out.println(i);} public static void println(long i){System.out.println(i);} }//output /* @supplement-auto-stop @supplement-println-stop */ import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.PriorityQueue; import java.util.Scanner; public class Main{ public static void main(String[] args){ int t = in.nextInt(); lp : for(int i = 0; i < t; i++){ long n = in.nextLong(); String str = (n + ""); int len = str.length(); long l = 0; lx : for(int x = 2; x < len; x++){if(len % x == 0){ String s = str.substring(0, len / x); boolean b = true; long alt = Long.parseLong(s.repeat(x)); if(alt > n){s = "" + (Long.parseLong(s)-1); alt = Long.parseLong(s.repeat(x)); b = false;}; if(alt > l){l = alt;}; // if(b){break lx;}; };}; String s = str.substring(0, 1); long alt = Long.parseLong(s.repeat(len)); if(alt > n){int z = Integer.parseInt(s); if(z == 1){alt = Long.parseLong("9".repeat(len-1));}else{alt = Long.parseLong(((z-1) + "").repeat(len));};}; if(alt > l){l = alt;}; out.println(l); }; } public static boolean calc(String str, int l, long n){ String rep = str.substring(0, str.length() / l); if(Long.parseLong(rep.repeat(l)) > n){return false;}; return true; } public static String val(String str, int l, long n){ String rep = str.substring(0, str.length() / l); if(Long.parseLong(rep.repeat(l)) > n){rep = "" + (Integer.parseInt(rep) - 1);}; return rep.repeat(l); } public static String val(String str, int l, long n, boolean b){ String rep = str.substring(0, str.length() / l); if(! b){rep = "" + (Integer.parseInt(rep) - 1);}; return rep.repeat(l); } }//main class in{ private static Scanner sc = new Scanner(System.in); public static int[] nextInt(int len){ int[] ret = new int[len]; for(int i = 0; i < len; i++){ret[i] = nextInt();}; return ret; } public static int[][] nextInt(int x, int y){ int[][] ret = new int[x][y]; for(int i = 0; i < x; i++){for(int j = 0; j < y; j++){ret[i][j] = nextInt();};}; return ret; } public static int nextInt(){return Integer.parseInt(sc.next());} public static long[] nextLong(int len){ long[] ret = new long[len]; for(int i = 0; i < len; i++){ret[i] = nextLong();}; return ret; } public static long[][] nextLong(int x, int y){ long[][] ret = new long[x][y]; for(int i = 0; i < x; i++){for(int j = 0; j < y; j++){ret[i][j] = nextInt();};}; return ret; } public static long nextLong(){return Long.parseLong(sc.next());} public static String next(){return sc.next();} public static String[] nextString(int len){ String[] ret = new String[len]; for(int i = 0; i < len; i++){ret[i] = next();}; return ret; } }//input class out{ public static void println(int... list){ StringBuilder sb = new StringBuilder(); sb.append(list[0]); for(int i = 1; i < list.length; i++){sb.append(" ").append(list[i]);}; System.out.println(sb.toString()); } public static void println(long... list){ StringBuilder sb = new StringBuilder(); sb.append(list[0]); for(int i = 1; i < list.length; i++){sb.append(" ").append(list[i]);}; System.out.println(sb.toString()); } public static void println(String text){System.out.println(text);} public static void println(int i){System.out.println(i);} public static void println(long i){System.out.println(i);} }//output
ConDefects/ConDefects/Code/arc141_a/Java/32092189
condefects-java_data_634
import java.util.Arrays; import java.util.Scanner; import java.util.Vector; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int i = 0; i < t; i++) { // System.out.println("i = "+i); long result = 0; String strN = sc.next(); long n = Long.parseLong(strN); // System.out.println("n = "+n); // Vector<Integer> divisors = new Vector<Integer>(); // for(int j = 1; j < strN.length(); j++) { // if(strN.length()%j == 0) { // divisors.add(j); // } // } // for(int j = 0; j < divisors.size(); j++) { for(int j = 2; j <= strN.length() ; j++) { // System.out.println("j = "+j); // int len = divisors.elementAt(j); int len = strN.length() / j; long left = 1; long right = (long)Math.pow(10, len); // for(int k = (int)Math.pow(10, len - 1); k < Math.pow(10, len); k++) { while(right > left + 1) { // System.out.println("left "+left+" right "+right); // System.out.println("k = "+k); long mid = (left + right)/2; // System.out.println("mid "+mid); String tmpStr = ""; for(int l = 0; l < j; l++) { // tmpStr += k; tmpStr += mid; } // System.out.println(tmpStr); long tmpN = Long.parseLong(tmpStr); if(tmpN > n) { right = mid; } else { // result = Math.max(result, tmpN); left = mid; } // System.out.println("result "+result); } String tmpResult = ""; for(int k = 0; k < j; k++) { tmpResult += left; } result = Math.max(result, Long.parseLong(tmpResult)); } System.out.println(result); } } } import java.util.Arrays; import java.util.Scanner; import java.util.Vector; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int i = 0; i < t; i++) { // System.out.println("i = "+i); long result = 0; String strN = sc.next(); long n = Long.parseLong(strN); // System.out.println("n = "+n); // Vector<Integer> divisors = new Vector<Integer>(); // for(int j = 1; j < strN.length(); j++) { // if(strN.length()%j == 0) { // divisors.add(j); // } // } // for(int j = 0; j < divisors.size(); j++) { for(int j = 2; j <= strN.length() ; j++) { // System.out.println("j = "+j); // int len = divisors.elementAt(j); int len = strN.length() / j; long left = 0; long right = (long)Math.pow(10, len); // for(int k = (int)Math.pow(10, len - 1); k < Math.pow(10, len); k++) { while(right > left + 1) { // System.out.println("left "+left+" right "+right); // System.out.println("k = "+k); long mid = (left + right)/2; // System.out.println("mid "+mid); String tmpStr = ""; for(int l = 0; l < j; l++) { // tmpStr += k; tmpStr += mid; } // System.out.println(tmpStr); long tmpN = Long.parseLong(tmpStr); if(tmpN > n) { right = mid; } else { // result = Math.max(result, tmpN); left = mid; } // System.out.println("result "+result); } String tmpResult = ""; for(int k = 0; k < j; k++) { tmpResult += left; } result = Math.max(result, Long.parseLong(tmpResult)); } System.out.println(result); } } }
ConDefects/ConDefects/Code/arc141_a/Java/32178413
condefects-java_data_635
import java.util.*; import java.io.*; class Main { private static final void solve() throws IOException { final int n = ni(), nn = 1 << n, k = ni(); if (n == 1) { ou.println("Yes").println(1); return; } if (k % 2 == 0 || n == k) { ou.printYN(false); return; } var a = new boolean[nn]; a[0] = true; var t = new int[n]; int c = 0; for (int i = 1; i < nn; i++) { if (a[i]) continue; if (Integer.bitCount(i) != k) continue; t[c++] = i; for (int j = 0; j < nn; j++) a[j ^ i] |= a[j]; } ou.printYN(true); var aa = new int[nn]; var tt = new ArrayList<Boolean>(); int cnt = 1; for (int i = 0; i < n; i++) { tt.clear(); for (int j = 0; j < cnt; j++) tt.add(false); for (int j = 0; j < cnt; j++) tt.add(true); for (int j = 0; j < cnt; j++) tt.add(true); for (int j = 0; j < cnt; j++) tt.add(false); for (int j = 0; j < nn; j++) if (tt.get(j % tt.size())) aa[j] |= 1 << i; cnt <<= 1; } for (int i : aa) { int ans = 0; for (int j = 0; j < n; j++) { if ((i & 1) == 1) ans ^= t[j]; i >>= 1; } ou.print(ans).print(" "); } } public static void main(String[] args) throws IOException { solve(); ou.flush(); } private static final int ni() throws IOException { return sc.nextInt(); } private static final int[] ni(int n) throws IOException { return sc.nextIntArray(n); } private static final long nl() throws IOException { return sc.nextLong(); } private static final long[] nl(int n) throws IOException { return sc.nextLongArray(n); } private static final String ns() throws IOException { return sc.nextString(); } private static final ContestInputStream sc = new ContestInputStream(); private static final ContestOutputStream ou = new ContestOutputStream(); } class ContestInputStream extends FilterInputStream { protected final byte[] buf; protected int pos = 0; protected int lim = 0; private final char[] cbuf; public ContestInputStream() { super(System.in); this.buf = new byte[1 << 13]; this.cbuf = new char[1 << 19]; } boolean hasRemaining() throws IOException { if (pos < lim) return true; lim = in.read(buf); pos = 0; return lim > 0; } int remaining() throws IOException { if (pos >= lim) { lim = in.read(buf); pos = 0; } return lim - pos; } @Override public int available() throws IOException { if (pos < lim) return lim - pos + in.available(); return in.available(); } @Override public long skip(long n) throws IOException { if (pos < lim) { int rem = lim - pos; if (n < rem) { pos += n; return n; } pos = lim; return rem; } return in.skip(n); } @Override public int read() throws IOException { if (hasRemaining()) return buf[pos++]; return -1; } @Override public int read(byte[] b, int off, int len) throws IOException { if (pos < lim) { int rem = Math.min(lim - pos, len); for (int i = 0; i < rem; i++) b[off + i] = buf[pos + i]; pos += rem; return rem; } return in.read(b, off, len); } public char[] readToken() throws IOException { int cpos = 0; int rem; int i; byte b; l: while ((rem = remaining()) > 0) { for (i = 0; i < rem; i++) { b = buf[pos + i]; if (b <= 0x20) { pos += i + 1; cpos += i; break l; } cbuf[cpos + i] = (char) b; } pos += rem; cpos += rem; } char[] arr = new char[cpos]; for (i = 0; i < cpos; i++) arr[i] = cbuf[i]; return arr; } public int readToken(char[] cbuf, int off) throws IOException { int cpos = off; int rem; int i; byte b; l: while ((rem = remaining()) > 0) { for (i = 0; i < rem; i++) { b = buf[pos + i]; if (b <= 0x20) { pos += i + 1; cpos += i; break l; } cbuf[cpos + i] = (char) b; } pos += rem; cpos += rem; } return cpos - off; } public int readToken(char[] cbuf) throws IOException { return readToken(cbuf, 0); } public String nextString() throws IOException { int cpos = 0; int rem; int i; byte b; l: while ((rem = remaining()) > 0) { for (i = 0; i < rem; i++) { b = buf[pos + i]; if (b <= 0x20) { pos += i + 1; cpos += i; break l; } cbuf[cpos + i] = (char) b; } pos += rem; cpos += rem; } return String.valueOf(cbuf, 0, cpos); } public int nextInt() throws IOException { if (!hasRemaining()) return 0; int value = 0; byte b = buf[pos++]; if (b == 0x2d) { while (hasRemaining() && (b = buf[pos++]) > 0x20) value = value * 10 - b + 0x30; } else { do { value = value * 10 + b - 0x30; } while (hasRemaining() && (b = buf[pos++]) > 0x20); } return value; } public long nextLong() throws IOException { if (!hasRemaining()) return 0L; long value = 0L; byte b = buf[pos++]; if (b == 0x2d) { while (hasRemaining() && (b = buf[pos++]) > 0x20) value = value * 10 - b + 0x30; } else { do { value = value * 10 + b - 0x30; } while (hasRemaining() && (b = buf[pos++]) > 0x20); } return value; } public float nextFloat() throws IOException { return Float.parseFloat(nextString()); } public double nextDouble() throws IOException { return Double.parseDouble(nextString()); } public boolean[] nextBooleanArray(char ok) throws IOException { char[] s = nextString().toCharArray(); int n = s.length; boolean[] t = new boolean[n]; for (int i = 0; i < n; i++) t[i] = s[i] == ok; return t; } public String[] nextStringArray(int len) throws IOException { String[] arr = new String[len]; for (int i = 0; i < len; i++) arr[i] = nextString(); return arr; } public int[] nextIntArray(int len) throws IOException { int[] arr = new int[len]; for (int i = 0; i < len; i++) arr[i] = nextInt(); return arr; } public int[] nextIntArray(int len, java.util.function.IntUnaryOperator map) throws IOException { int[] arr = new int[len]; for (int i = 0; i < len; i++) arr[i] = map.applyAsInt(nextInt()); return arr; } public long[] nextLongArray(int len, java.util.function.LongUnaryOperator map) throws IOException { long[] arr = new long[len]; for (int i = 0; i < len; i++) arr[i] = map.applyAsLong(nextLong()); return arr; } public int[][] nextIntMatrix(int h, int w) throws IOException { int[][] arr = new int[h][w]; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) arr[i][j] = nextInt(); return arr; } public long[] nextLongArray(int len) throws IOException { long[] arr = new long[len]; for (int i = 0; i < len; i++) arr[i] = nextLong(); return arr; } public long[][] nextLongMatrix(int h, int w) throws IOException { long[][] arr = new long[h][w]; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) arr[i][j] = nextLong(); return arr; } public float[] nextFloatArray(int len) throws IOException { float[] arr = new float[len]; for (int i = 0; i < len; i++) arr[i] = nextFloat(); return arr; } public double[] nextDoubleArray(int len) throws IOException { double[] arr = new double[len]; for (int i = 0; i < len; i++) arr[i] = nextDouble(); return arr; } public char[][] nextCharMatrix(int h, int w) throws IOException { char[][] arr = new char[h][]; for (int i = 0; i < h; i++) arr[i] = nextString().toCharArray(); return arr; } } class ContestOutputStream extends FilterOutputStream implements Appendable { protected final byte[] buf; protected int pos = 0; public ContestOutputStream() { super(System.out); this.buf = new byte[1 << 13]; } @Override public void flush() throws IOException { out.write(buf, 0, pos); pos = 0; out.flush(); } void put(byte b) throws IOException { if (pos >= buf.length) flush(); buf[pos++] = b; } int remaining() throws IOException { if (pos >= buf.length) flush(); return buf.length - pos; } @Override public void write(int b) throws IOException { put((byte) b); } @Override public void write(byte[] b, int off, int len) throws IOException { int o = off; int l = len; while (l > 0) { int rem = Math.min(remaining(), l); for (int i = 0; i < rem; i++) buf[pos + i] = b[o + i]; pos += rem; o += rem; l -= rem; } } @Override public ContestOutputStream append(char c) throws IOException { put((byte) c); return this; } @Override public ContestOutputStream append(CharSequence csq, int start, int end) throws IOException { int off = start; int len = end - start; while (len > 0) { int rem = Math.min(remaining(), len); for (int i = 0; i < rem; i++) buf[pos + i] = (byte) csq.charAt(off + i); pos += rem; off += rem; len -= rem; } return this; } @Override public ContestOutputStream append(CharSequence csq) throws IOException { return append(csq, 0, csq.length()); } public ContestOutputStream append(char[] arr, int off, int len) throws IOException { int o = off; int l = len; while (l > 0) { int rem = Math.min(remaining(), l); for (int i = 0; i < rem; i++) buf[pos + i] = (byte) arr[o + i]; pos += rem; o += rem; l -= rem; } return this; } public ContestOutputStream print(char[] arr) throws IOException { return append(arr, 0, arr.length).newLine(); } public ContestOutputStream print(boolean value) throws IOException { if (value) return append("o"); return append("x"); } public ContestOutputStream println(boolean value) throws IOException { if (value) return append("o\n"); return append("x\n"); } public ContestOutputStream print(boolean[][] value) throws IOException { final int n = value.length, m = value[0].length; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) print(value[i][j]); newLine(); } return this; } public ContestOutputStream print(int value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(int value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(long value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(long value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(float value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(float value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(double value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(double value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(char value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(char value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(String value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(String value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(Object value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(Object value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream printYN(boolean yes) throws IOException { if (yes) return println("Yes"); return println("No"); } public ContestOutputStream print(CharSequence[] arr) throws IOException { if (arr.length > 0) { append(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').append(arr[i]); } return this; } public ContestOutputStream print(int[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } newLine(); return this; } public ContestOutputStream println(int[] arr) throws IOException { for (int i : arr) print(i).newLine(); return this; } public ContestOutputStream print(long[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } newLine(); return this; } public ContestOutputStream println(long[] arr) throws IOException { for (long i : arr) print(i).newLine(); return this; } public ContestOutputStream print(float[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } return this; } public ContestOutputStream println(float[] arr) throws IOException { for (float i : arr) print(i).newLine(); return this; } public ContestOutputStream print(double[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } return this; } public ContestOutputStream println(double[] arr) throws IOException { for (double i : arr) print(i).newLine(); return this; } public ContestOutputStream print(Object[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } return this; } public ContestOutputStream print(java.util.ArrayList<?> arr) throws IOException { final int n = arr.size(); print(arr.get(0)); for (int i = 1; i < n; i++) print(" ").print(arr.get(i)); newLine(); return this; } public ContestOutputStream println(java.util.ArrayList<?> arr) throws IOException { final int n = arr.size(); for (int i = 0; i < n; i++) println(arr.get(i)); return this; } public ContestOutputStream println(Object[] arr) throws IOException { for (Object i : arr) print(i).newLine(); return this; } public ContestOutputStream newLine() throws IOException { return append('\n'); } public ContestOutputStream endl() throws IOException { newLine().flush(); return this; } public ContestOutputStream print(int[][] arr) throws IOException { for (int[] i : arr) print(i); return this; } public ContestOutputStream print(long[][] arr) throws IOException { for (long[] i : arr) print(i); return this; } public ContestOutputStream print(char[][] arr) throws IOException { for (char[] i : arr) print(i); return this; } public ContestOutputStream print(Object[][] arr) throws IOException { for (Object[] i : arr) print(i); return this; } } import java.util.*; import java.io.*; class Main { private static final void solve() throws IOException { final int n = ni(), nn = 1 << n, k = ni(); if (n == 1) { ou.println("Yes").print(0).print(" ").println(1); return; } if (k % 2 == 0 || n == k) { ou.printYN(false); return; } var a = new boolean[nn]; a[0] = true; var t = new int[n]; int c = 0; for (int i = 1; i < nn; i++) { if (a[i]) continue; if (Integer.bitCount(i) != k) continue; t[c++] = i; for (int j = 0; j < nn; j++) a[j ^ i] |= a[j]; } ou.printYN(true); var aa = new int[nn]; var tt = new ArrayList<Boolean>(); int cnt = 1; for (int i = 0; i < n; i++) { tt.clear(); for (int j = 0; j < cnt; j++) tt.add(false); for (int j = 0; j < cnt; j++) tt.add(true); for (int j = 0; j < cnt; j++) tt.add(true); for (int j = 0; j < cnt; j++) tt.add(false); for (int j = 0; j < nn; j++) if (tt.get(j % tt.size())) aa[j] |= 1 << i; cnt <<= 1; } for (int i : aa) { int ans = 0; for (int j = 0; j < n; j++) { if ((i & 1) == 1) ans ^= t[j]; i >>= 1; } ou.print(ans).print(" "); } } public static void main(String[] args) throws IOException { solve(); ou.flush(); } private static final int ni() throws IOException { return sc.nextInt(); } private static final int[] ni(int n) throws IOException { return sc.nextIntArray(n); } private static final long nl() throws IOException { return sc.nextLong(); } private static final long[] nl(int n) throws IOException { return sc.nextLongArray(n); } private static final String ns() throws IOException { return sc.nextString(); } private static final ContestInputStream sc = new ContestInputStream(); private static final ContestOutputStream ou = new ContestOutputStream(); } class ContestInputStream extends FilterInputStream { protected final byte[] buf; protected int pos = 0; protected int lim = 0; private final char[] cbuf; public ContestInputStream() { super(System.in); this.buf = new byte[1 << 13]; this.cbuf = new char[1 << 19]; } boolean hasRemaining() throws IOException { if (pos < lim) return true; lim = in.read(buf); pos = 0; return lim > 0; } int remaining() throws IOException { if (pos >= lim) { lim = in.read(buf); pos = 0; } return lim - pos; } @Override public int available() throws IOException { if (pos < lim) return lim - pos + in.available(); return in.available(); } @Override public long skip(long n) throws IOException { if (pos < lim) { int rem = lim - pos; if (n < rem) { pos += n; return n; } pos = lim; return rem; } return in.skip(n); } @Override public int read() throws IOException { if (hasRemaining()) return buf[pos++]; return -1; } @Override public int read(byte[] b, int off, int len) throws IOException { if (pos < lim) { int rem = Math.min(lim - pos, len); for (int i = 0; i < rem; i++) b[off + i] = buf[pos + i]; pos += rem; return rem; } return in.read(b, off, len); } public char[] readToken() throws IOException { int cpos = 0; int rem; int i; byte b; l: while ((rem = remaining()) > 0) { for (i = 0; i < rem; i++) { b = buf[pos + i]; if (b <= 0x20) { pos += i + 1; cpos += i; break l; } cbuf[cpos + i] = (char) b; } pos += rem; cpos += rem; } char[] arr = new char[cpos]; for (i = 0; i < cpos; i++) arr[i] = cbuf[i]; return arr; } public int readToken(char[] cbuf, int off) throws IOException { int cpos = off; int rem; int i; byte b; l: while ((rem = remaining()) > 0) { for (i = 0; i < rem; i++) { b = buf[pos + i]; if (b <= 0x20) { pos += i + 1; cpos += i; break l; } cbuf[cpos + i] = (char) b; } pos += rem; cpos += rem; } return cpos - off; } public int readToken(char[] cbuf) throws IOException { return readToken(cbuf, 0); } public String nextString() throws IOException { int cpos = 0; int rem; int i; byte b; l: while ((rem = remaining()) > 0) { for (i = 0; i < rem; i++) { b = buf[pos + i]; if (b <= 0x20) { pos += i + 1; cpos += i; break l; } cbuf[cpos + i] = (char) b; } pos += rem; cpos += rem; } return String.valueOf(cbuf, 0, cpos); } public int nextInt() throws IOException { if (!hasRemaining()) return 0; int value = 0; byte b = buf[pos++]; if (b == 0x2d) { while (hasRemaining() && (b = buf[pos++]) > 0x20) value = value * 10 - b + 0x30; } else { do { value = value * 10 + b - 0x30; } while (hasRemaining() && (b = buf[pos++]) > 0x20); } return value; } public long nextLong() throws IOException { if (!hasRemaining()) return 0L; long value = 0L; byte b = buf[pos++]; if (b == 0x2d) { while (hasRemaining() && (b = buf[pos++]) > 0x20) value = value * 10 - b + 0x30; } else { do { value = value * 10 + b - 0x30; } while (hasRemaining() && (b = buf[pos++]) > 0x20); } return value; } public float nextFloat() throws IOException { return Float.parseFloat(nextString()); } public double nextDouble() throws IOException { return Double.parseDouble(nextString()); } public boolean[] nextBooleanArray(char ok) throws IOException { char[] s = nextString().toCharArray(); int n = s.length; boolean[] t = new boolean[n]; for (int i = 0; i < n; i++) t[i] = s[i] == ok; return t; } public String[] nextStringArray(int len) throws IOException { String[] arr = new String[len]; for (int i = 0; i < len; i++) arr[i] = nextString(); return arr; } public int[] nextIntArray(int len) throws IOException { int[] arr = new int[len]; for (int i = 0; i < len; i++) arr[i] = nextInt(); return arr; } public int[] nextIntArray(int len, java.util.function.IntUnaryOperator map) throws IOException { int[] arr = new int[len]; for (int i = 0; i < len; i++) arr[i] = map.applyAsInt(nextInt()); return arr; } public long[] nextLongArray(int len, java.util.function.LongUnaryOperator map) throws IOException { long[] arr = new long[len]; for (int i = 0; i < len; i++) arr[i] = map.applyAsLong(nextLong()); return arr; } public int[][] nextIntMatrix(int h, int w) throws IOException { int[][] arr = new int[h][w]; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) arr[i][j] = nextInt(); return arr; } public long[] nextLongArray(int len) throws IOException { long[] arr = new long[len]; for (int i = 0; i < len; i++) arr[i] = nextLong(); return arr; } public long[][] nextLongMatrix(int h, int w) throws IOException { long[][] arr = new long[h][w]; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) arr[i][j] = nextLong(); return arr; } public float[] nextFloatArray(int len) throws IOException { float[] arr = new float[len]; for (int i = 0; i < len; i++) arr[i] = nextFloat(); return arr; } public double[] nextDoubleArray(int len) throws IOException { double[] arr = new double[len]; for (int i = 0; i < len; i++) arr[i] = nextDouble(); return arr; } public char[][] nextCharMatrix(int h, int w) throws IOException { char[][] arr = new char[h][]; for (int i = 0; i < h; i++) arr[i] = nextString().toCharArray(); return arr; } } class ContestOutputStream extends FilterOutputStream implements Appendable { protected final byte[] buf; protected int pos = 0; public ContestOutputStream() { super(System.out); this.buf = new byte[1 << 13]; } @Override public void flush() throws IOException { out.write(buf, 0, pos); pos = 0; out.flush(); } void put(byte b) throws IOException { if (pos >= buf.length) flush(); buf[pos++] = b; } int remaining() throws IOException { if (pos >= buf.length) flush(); return buf.length - pos; } @Override public void write(int b) throws IOException { put((byte) b); } @Override public void write(byte[] b, int off, int len) throws IOException { int o = off; int l = len; while (l > 0) { int rem = Math.min(remaining(), l); for (int i = 0; i < rem; i++) buf[pos + i] = b[o + i]; pos += rem; o += rem; l -= rem; } } @Override public ContestOutputStream append(char c) throws IOException { put((byte) c); return this; } @Override public ContestOutputStream append(CharSequence csq, int start, int end) throws IOException { int off = start; int len = end - start; while (len > 0) { int rem = Math.min(remaining(), len); for (int i = 0; i < rem; i++) buf[pos + i] = (byte) csq.charAt(off + i); pos += rem; off += rem; len -= rem; } return this; } @Override public ContestOutputStream append(CharSequence csq) throws IOException { return append(csq, 0, csq.length()); } public ContestOutputStream append(char[] arr, int off, int len) throws IOException { int o = off; int l = len; while (l > 0) { int rem = Math.min(remaining(), l); for (int i = 0; i < rem; i++) buf[pos + i] = (byte) arr[o + i]; pos += rem; o += rem; l -= rem; } return this; } public ContestOutputStream print(char[] arr) throws IOException { return append(arr, 0, arr.length).newLine(); } public ContestOutputStream print(boolean value) throws IOException { if (value) return append("o"); return append("x"); } public ContestOutputStream println(boolean value) throws IOException { if (value) return append("o\n"); return append("x\n"); } public ContestOutputStream print(boolean[][] value) throws IOException { final int n = value.length, m = value[0].length; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) print(value[i][j]); newLine(); } return this; } public ContestOutputStream print(int value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(int value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(long value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(long value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(float value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(float value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(double value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(double value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(char value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(char value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(String value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(String value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream print(Object value) throws IOException { return append(String.valueOf(value)); } public ContestOutputStream println(Object value) throws IOException { return append(String.valueOf(value)).newLine(); } public ContestOutputStream printYN(boolean yes) throws IOException { if (yes) return println("Yes"); return println("No"); } public ContestOutputStream print(CharSequence[] arr) throws IOException { if (arr.length > 0) { append(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').append(arr[i]); } return this; } public ContestOutputStream print(int[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } newLine(); return this; } public ContestOutputStream println(int[] arr) throws IOException { for (int i : arr) print(i).newLine(); return this; } public ContestOutputStream print(long[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } newLine(); return this; } public ContestOutputStream println(long[] arr) throws IOException { for (long i : arr) print(i).newLine(); return this; } public ContestOutputStream print(float[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } return this; } public ContestOutputStream println(float[] arr) throws IOException { for (float i : arr) print(i).newLine(); return this; } public ContestOutputStream print(double[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } return this; } public ContestOutputStream println(double[] arr) throws IOException { for (double i : arr) print(i).newLine(); return this; } public ContestOutputStream print(Object[] arr) throws IOException { if (arr.length > 0) { print(arr[0]); for (int i = 1; i < arr.length; i++) append('\u0020').print(arr[i]); } return this; } public ContestOutputStream print(java.util.ArrayList<?> arr) throws IOException { final int n = arr.size(); print(arr.get(0)); for (int i = 1; i < n; i++) print(" ").print(arr.get(i)); newLine(); return this; } public ContestOutputStream println(java.util.ArrayList<?> arr) throws IOException { final int n = arr.size(); for (int i = 0; i < n; i++) println(arr.get(i)); return this; } public ContestOutputStream println(Object[] arr) throws IOException { for (Object i : arr) print(i).newLine(); return this; } public ContestOutputStream newLine() throws IOException { return append('\n'); } public ContestOutputStream endl() throws IOException { newLine().flush(); return this; } public ContestOutputStream print(int[][] arr) throws IOException { for (int[] i : arr) print(i); return this; } public ContestOutputStream print(long[][] arr) throws IOException { for (long[] i : arr) print(i); return this; } public ContestOutputStream print(char[][] arr) throws IOException { for (char[] i : arr) print(i); return this; } public ContestOutputStream print(Object[][] arr) throws IOException { for (Object[] i : arr) print(i); return this; } }
ConDefects/ConDefects/Code/arc138_d/Java/31268295
condefects-java_data_636
import java.util.*; public class Main{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int a = scan.nextInt(); int b = scan.nextInt(); HashSet<Integer> set = new HashSet<>(); for(int i = 0 ; i < a ; i++){ set.add(scan.nextInt()); } int arg = b; for(int i = 0 ; i < a ; i++ ){ if(!set.contains(i)){ arg = i; break; } } System.out.println(arg); } } import java.util.*; public class Main{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int a = scan.nextInt(); int b = scan.nextInt(); HashSet<Integer> set = new HashSet<>(); for(int i = 0 ; i < a ; i++){ set.add(scan.nextInt()); } int arg = b; for(int i = 0 ; i < b ; i++ ){ if(!set.contains(i)){ arg = i; break; } } System.out.println(arg); } }
ConDefects/ConDefects/Code/abc290_c/Java/45729491
condefects-java_data_637
import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Main { public static void printArray(int[]a) { for(int i=0;i<a.length-1;i++) { System.out.print(a[i]+" "); } System.out.println(a[a.length-1]); } public static long lmax(long a,long b) { if(a<b)return b; else return a; } public static long lmin(long a,long b) { if(a>b)return b; else return a; } public static int max(int a,int b) { if(a<b)return b; else return a; } public static int min(int a,int b) { if(a>b)return b; else return a; } public static int[] setArray(int n) { int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=scan.nextInt(); return a; } public static long[] lsetArray(int n) { long a[]=new long[n]; for(int i=0;i<n;i++)a[i]=scan.nextLong(); return a; } public static int abs(int n) { if(n<0)n*=-1; return n; } public static long labs(long n) { if(n<0)n*=-1; return n; } static Scanner scan=new Scanner(System.in); public static void main(String[] args) { int n=scan.nextInt(); int k=scan.nextInt(); int count[]=new int[3*100000+100]; int a[]=setArray(n); for(int e:a) { if(e<count.length) count[e]++; } int ans=0; while(count[ans]!=0)ans++; System.out.println(min(ans-1,k)); } } import java.util.Arrays; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Main { public static void printArray(int[]a) { for(int i=0;i<a.length-1;i++) { System.out.print(a[i]+" "); } System.out.println(a[a.length-1]); } public static long lmax(long a,long b) { if(a<b)return b; else return a; } public static long lmin(long a,long b) { if(a>b)return b; else return a; } public static int max(int a,int b) { if(a<b)return b; else return a; } public static int min(int a,int b) { if(a>b)return b; else return a; } public static int[] setArray(int n) { int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=scan.nextInt(); return a; } public static long[] lsetArray(int n) { long a[]=new long[n]; for(int i=0;i<n;i++)a[i]=scan.nextLong(); return a; } public static int abs(int n) { if(n<0)n*=-1; return n; } public static long labs(long n) { if(n<0)n*=-1; return n; } static Scanner scan=new Scanner(System.in); public static void main(String[] args) { int n=scan.nextInt(); int k=scan.nextInt(); int count[]=new int[3*100000+100]; int a[]=setArray(n); for(int e:a) { if(e<count.length) count[e]++; } int ans=0; while(count[ans]!=0)ans++; System.out.println(min(ans,k)); } }
ConDefects/ConDefects/Code/abc290_c/Java/40951829
condefects-java_data_638
import java.util.*; class Main { public static void main(String[] args) { Scanner scanner =new Scanner(System.in); int n=scanner.nextInt(); int k=scanner.nextInt(); Set<Integer>set =new HashSet<>(); for(int i=0;i<n;i++){ set.add(scanner.nextInt()); } for(int i=0;i<=k;i++){ if(set.size()==i || set.contains(i)){ System.out.println(i); return; } } System.out.println(k); } } import java.util.*; class Main { public static void main(String[] args) { Scanner scanner =new Scanner(System.in); int n=scanner.nextInt(); int k=scanner.nextInt(); Set<Integer>set =new HashSet<>(); for(int i=0;i<n;i++){ set.add(scanner.nextInt()); } for(int i=0;i<=k;i++){ if(set.size()==i ||!set.contains(i)){ System.out.println(i); return; } } System.out.println(k); } }
ConDefects/ConDefects/Code/abc290_c/Java/41841791
condefects-java_data_639
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); HashSet<Integer> set = new HashSet<>(); for (int i = 0; i < n; i++) { set.add(sc.nextInt()); }int ans = k; for (int j = 0; j < n; j++) { if (!set.contains(j)) { ans = j; break; } } System.out.println(ans); } } import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); HashSet<Integer> set = new HashSet<>(); for (int i = 0; i < n; i++) { set.add(sc.nextInt()); }int ans = k; for (int j = 0; j < k; j++) { if (!set.contains(j)) { ans = j; break; } } System.out.println(ans); } }
ConDefects/ConDefects/Code/abc290_c/Java/45751361
condefects-java_data_640
import java.util.*; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int pnum = sc.nextInt(); int [] order = new int [pnum]; for(int i = 0; i < pnum; i++){ int person = sc.nextInt(); order[person - 1] = i; } int qnum = sc.nextInt(); for(int i = 0; i < qnum; i++){ int query1 = sc.nextInt(); int query2 = sc.nextInt(); if (query1 < query2){ System.out.println(query1); }else{ System.out.println(query2); } } } } import java.util.*; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int pnum = sc.nextInt(); int [] order = new int [pnum]; for(int i = 0; i < pnum; i++){ int person = sc.nextInt(); order[person - 1] = i; } int qnum = sc.nextInt(); for(int i = 0; i < qnum; i++){ int query1 = sc.nextInt(); int query2 = sc.nextInt(); if (order[query1 - 1] < order[query2 - 1]){ System.out.println(query1); }else{ System.out.println(query2); } } } }
ConDefects/ConDefects/Code/abc342_b/Java/50759308
condefects-java_data_641
import java.util.*; import static java.lang.System.out; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int h1 = sc.nextInt(); int h2 = sc.nextInt(); int h3 = sc.nextInt(); int w1 = sc.nextInt(); int w2 = sc.nextInt(); int w3 = sc.nextInt(); long cnt = 0; for(int i = 1;i <= 30;i++){ for(int j = 1;j <= 30;j++){ for(int k = 1;k <= 30;k++){ for(int l = 1;l <= 30;l++){ int a = h1 - (i + j); int b = h2 - (k + l); int c = w1 - (i + k); int d = w2 - (j + l); if(a >= 1 && b >= 1 && c >= 1 && d >= 1){ if((h3 - (c + d) >= 1) && (w3 - (a + b) >= 1))cnt++; } } } } } out.println(cnt); } } import java.util.*; import static java.lang.System.out; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int h1 = sc.nextInt(); int h2 = sc.nextInt(); int h3 = sc.nextInt(); int w1 = sc.nextInt(); int w2 = sc.nextInt(); int w3 = sc.nextInt(); long cnt = 0; for(int i = 1;i <= 30;i++){ for(int j = 1;j <= 30;j++){ for(int k = 1;k <= 30;k++){ for(int l = 1;l <= 30;l++){ int a = h1 - (i + j); int b = h2 - (k + l); int c = w1 - (i + k); int d = w2 - (j + l); if(a >= 1 && b >= 1 && c >= 1 && d >= 1){ if((h3 - (c + d) == w3 - (a + b)) && (h3 - (c + d) >= 1))cnt++; } } } } } out.println(cnt); } }
ConDefects/ConDefects/Code/abc256_c/Java/35045592
condefects-java_data_642
import java.util.Arrays; import java.util.Scanner; public class Main { //2022/10/01 271 public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int sum=sc.nextInt(); int[][] nums=new int[n][2]; for(int i=0;i<n;i++) { Arrays.fill(nums[i], 0); } // for(int[] i:nums) { // System.out.println("****"); // for(int j:i) { // System.out.print(j+","); // } // } // //nums=>0,0,0,0,0,0 // System.out.println("========"); // for(int i=0;i<n;i++) { int a=sc.nextInt(); int b=sc.nextInt(); nums[i][0]=a; nums[i][1]=b; } int[][] dp=new int[n+1][sum+1]; dp[0][0]=1; for(int i=0;i<n;i++) { for(int j=0;j<=sum;j++) { if(dp[i][j]==0)continue; if(j+nums[i][0]<=sum) { dp[i+1][j+nums[i][0]]=1; // System.out.print("i="+i+"j="+j+","); // System.out.println("dp[i+1][j+nums[i][0]]="+dp[i+1][j+nums[i][0]]); } if(j+nums[i][1]<=sum) { dp[i+1][j+nums[i][1]]=1; // System.out.print("i="+i+"j="+j+","); // System.out.println("dp[i+1][j+nums[i][1]]="+dp[i+1][j+nums[i][1]]); } } } // for(int[] i:dp) { // System.out.println("****"); // for(int j:i)System.out.print(j+"."); // } if(dp[n][sum]==0) { System.out.println("No"); //elseではゴールが存在することが確定 }else { System.out.println("Yes"); StringBuilder sb=new StringBuilder(); for(int i=n-1;i>=0;i--) { if(sum>=nums[i][0] && dp[i][sum-nums[i][0]]==1) { sb.append("H"); sum-=nums[i][1]; }else { sb.append("T"); sum-=nums[i][1]; } } System.out.println(sb.reverse()); } } } import java.util.Arrays; import java.util.Scanner; public class Main { //2022/10/01 271 public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int sum=sc.nextInt(); int[][] nums=new int[n][2]; for(int i=0;i<n;i++) { Arrays.fill(nums[i], 0); } // for(int[] i:nums) { // System.out.println("****"); // for(int j:i) { // System.out.print(j+","); // } // } // //nums=>0,0,0,0,0,0 // System.out.println("========"); // for(int i=0;i<n;i++) { int a=sc.nextInt(); int b=sc.nextInt(); nums[i][0]=a; nums[i][1]=b; } int[][] dp=new int[n+1][sum+1]; dp[0][0]=1; for(int i=0;i<n;i++) { for(int j=0;j<=sum;j++) { if(dp[i][j]==0)continue; if(j+nums[i][0]<=sum) { dp[i+1][j+nums[i][0]]=1; // System.out.print("i="+i+"j="+j+","); // System.out.println("dp[i+1][j+nums[i][0]]="+dp[i+1][j+nums[i][0]]); } if(j+nums[i][1]<=sum) { dp[i+1][j+nums[i][1]]=1; // System.out.print("i="+i+"j="+j+","); // System.out.println("dp[i+1][j+nums[i][1]]="+dp[i+1][j+nums[i][1]]); } } } // for(int[] i:dp) { // System.out.println("****"); // for(int j:i)System.out.print(j+"."); // } if(dp[n][sum]==0) { System.out.println("No"); //elseではゴールが存在することが確定 }else { System.out.println("Yes"); StringBuilder sb=new StringBuilder(); for(int i=n-1;i>=0;i--) { if(sum>=nums[i][0] && dp[i][sum-nums[i][0]]==1) { sb.append("H"); sum-=nums[i][0]; }else { sb.append("T"); sum-=nums[i][1]; } } System.out.println(sb.reverse()); } } }
ConDefects/ConDefects/Code/abc271_d/Java/39598729
condefects-java_data_643
import java.io.*; import java.math.*; import java.time.*; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.Map.Entry; import java.util.regex.Pattern; import java.util.stream.Collectors; class Main implements Runnable { public static void solve () { int n = nextInt(), s = nextInt(); int[] a = new int[n+1], b = new int[n+1]; for (int i=1; i<=n; i++) { a[i] = nextInt(); b[i] = nextInt(); } //dp[i][j] i番目までのカードを使って和をjにできるか boolean[][] dp = new boolean[n+1][s+1]; dp[0][0] = true; for (int i=1; i<=n; i++) { //表を使う場合 for (int j=s; j>=a[i]; j--) { dp[i][j] |= dp[i-1][j - a[i]]; } //裏を使う場合 for (int j=s; j>=b[i]; j--) { dp[i][j] |= dp[i-1][j - b[i]]; } } println(dp[n][s]==true? "Yes" : "No"); if (dp[n][s] == false) return; int now = s; StringBuilder ans = new StringBuilder(); for (int i=n; i>=1; i--) { if (dp[i-1][now - a[i]] == true && now >= a[i]) { now -= a[i]; ans.append('H'); } else { now -= b[i]; ans.append('T'); } } println(ans.reverse()); } ///////////////////////////////////////////////////////////////////////////////////////////////// // useful methods, useful fields, useful static inner class ///////////////////////////////////////////////////////////////////////////////////////////////// public static final int infi = (int)1e9; public static final long infl = (long)1e18; public static final int modi = (int)1e9 + 7; public static final long modl = (long)1e18 + 7; public static int[] dy = {-1, 0, 1, 0}; public static int[] dx = {0, 1, 0, -1}; // public static int[] dy = {-1, 0, -1, 1, 0, 1}; // public static int[] dx = {-1, -1, 0, 0, 1, 1}; // public static int[] dy = {-1, -1, -1, 0, 1, 1, 1, 0}; // public static int[] dx = {-1, 0, 1, 1, 1, 0, -1, -1}; public static class Edge { int id, from, to, cost; Edge(int to, int cost) { //基本コレ this.to = to; this.cost = cost; } Edge(int from, int to, int cost) { this.from = from; this.to = to; this.cost = cost; } Edge(int id, int from, int to, int cost) { this.id = id; this.from = from; this.to = to; this.cost = cost; } int getCost() {return this.cost;} } ///////////////////////////////////////////////////////////////////////////////////////////////// // input ///////////////////////////////////////////////////////////////////////////////////////////////// public static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 32768); public static StringTokenizer tokenizer = null; public static String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public static String[] nextArray(int n) { String[] a = new String[n]; for (int i=0; i<n; i++) a[i] = next(); return a; } public static int nextInt() {return Integer.parseInt(next());}; public static int[] nextIntArray(int n) { int[] a = new int[n]; for (int i=0; i<n; i++) a[i] = nextInt(); return a; } public static int[][] nextIntTable(int n, int m) { int[][] a = new int[n][m]; for (int i=0; i<n; i++) { for (int j=0; j<m; j++) a[i][j] = nextInt(); } return a; } public static long nextLong() {return Long.parseLong(next());} public static long[] nextLongArray(int n) { long[] a = new long[n]; for (int i=0; i<n; i++) a[i] = nextLong(); return a; } public static double nextDouble() {return Double.parseDouble(next());} public static char nextChar() {return next().charAt(0);} public static char[] nextCharArray() {return next().toCharArray();} public static char[][] nextCharTable(int n, int m) { char[][] a = new char[n][m]; for (int i=0; i<n; i++) { a[i] = next().toCharArray(); } return a; } ///////////////////////////////////////////////////////////////////////////////////////////////// // output ///////////////////////////////////////////////////////////////////////////////////////////////// static PrintWriter out = new PrintWriter(System.out); public static void print(Object o) {out.print(o);} public static void println(Object o) {out.println(o);} public static void printStringArray(String[] a) { for (int i=0; i<a.length; i++) { if (i != 0) print(" "); print(a[i]); } println(""); } public static void printIntArray(int[] a) { for (int i=0; i<a.length; i++) { if (i != 0) print(" "); print(a[i]); } println(""); } public static void printLongArray(long[] a) { for (int i=0; i<a.length; i++) { if (i != 0) print(" "); print(a[i]); } println(""); } public static void printBooleanArray (boolean[] a) { for (int i=0; i<a.length; i++) { char c = a[i]==true? 'o' : 'x'; print(c); } println(""); } public static void printCharTable(char[][] a) { for (int i=0; i<a.length; i++) { for (int j=0; j<a[0].length; j++) { print(a[i][j]); } println(""); } } public static void printIntTable(int[][] a) { for (int i=0; i<a.length; i++) { for (int j=0; j<a[0].length; j++) { if (j != 0) print(" "); print(a[i][j]); } println(""); } } public static void printBooleanTable(boolean[][] b) { for (int i=0; i<b.length; i++) { for (int j=0; j<b[0].length; j++) { print(b[i][j]? "o" : "x"); } println(""); } } public static void printLongTable(long[][] a) { for (int i=0; i<a.length; i++) { for (int j=0; j<a[0].length; j++) { print(a[i][j]==-infl? "# " : a[i][j]+" "); } println(""); } } ///////////////////////////////////////////////////////////////////////////////////////////////// // main method ///////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { new Thread(null, new Main(), "", 64 * 1024 * 1024).start(); } public void run() { solve(); out.close(); } } import java.io.*; import java.math.*; import java.time.*; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.Map.Entry; import java.util.regex.Pattern; import java.util.stream.Collectors; class Main implements Runnable { public static void solve () { int n = nextInt(), s = nextInt(); int[] a = new int[n+1], b = new int[n+1]; for (int i=1; i<=n; i++) { a[i] = nextInt(); b[i] = nextInt(); } //dp[i][j] i番目までのカードを使って和をjにできるか boolean[][] dp = new boolean[n+1][s+1]; dp[0][0] = true; for (int i=1; i<=n; i++) { //表を使う場合 for (int j=s; j>=a[i]; j--) { dp[i][j] |= dp[i-1][j - a[i]]; } //裏を使う場合 for (int j=s; j>=b[i]; j--) { dp[i][j] |= dp[i-1][j - b[i]]; } } println(dp[n][s]==true? "Yes" : "No"); if (dp[n][s] == false) return; int now = s; StringBuilder ans = new StringBuilder(); for (int i=n; i>=1; i--) { if (now >= a[i] && dp[i-1][now - a[i]] == true) { now -= a[i]; ans.append('H'); } else { now -= b[i]; ans.append('T'); } } println(ans.reverse()); } ///////////////////////////////////////////////////////////////////////////////////////////////// // useful methods, useful fields, useful static inner class ///////////////////////////////////////////////////////////////////////////////////////////////// public static final int infi = (int)1e9; public static final long infl = (long)1e18; public static final int modi = (int)1e9 + 7; public static final long modl = (long)1e18 + 7; public static int[] dy = {-1, 0, 1, 0}; public static int[] dx = {0, 1, 0, -1}; // public static int[] dy = {-1, 0, -1, 1, 0, 1}; // public static int[] dx = {-1, -1, 0, 0, 1, 1}; // public static int[] dy = {-1, -1, -1, 0, 1, 1, 1, 0}; // public static int[] dx = {-1, 0, 1, 1, 1, 0, -1, -1}; public static class Edge { int id, from, to, cost; Edge(int to, int cost) { //基本コレ this.to = to; this.cost = cost; } Edge(int from, int to, int cost) { this.from = from; this.to = to; this.cost = cost; } Edge(int id, int from, int to, int cost) { this.id = id; this.from = from; this.to = to; this.cost = cost; } int getCost() {return this.cost;} } ///////////////////////////////////////////////////////////////////////////////////////////////// // input ///////////////////////////////////////////////////////////////////////////////////////////////// public static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 32768); public static StringTokenizer tokenizer = null; public static String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public static String[] nextArray(int n) { String[] a = new String[n]; for (int i=0; i<n; i++) a[i] = next(); return a; } public static int nextInt() {return Integer.parseInt(next());}; public static int[] nextIntArray(int n) { int[] a = new int[n]; for (int i=0; i<n; i++) a[i] = nextInt(); return a; } public static int[][] nextIntTable(int n, int m) { int[][] a = new int[n][m]; for (int i=0; i<n; i++) { for (int j=0; j<m; j++) a[i][j] = nextInt(); } return a; } public static long nextLong() {return Long.parseLong(next());} public static long[] nextLongArray(int n) { long[] a = new long[n]; for (int i=0; i<n; i++) a[i] = nextLong(); return a; } public static double nextDouble() {return Double.parseDouble(next());} public static char nextChar() {return next().charAt(0);} public static char[] nextCharArray() {return next().toCharArray();} public static char[][] nextCharTable(int n, int m) { char[][] a = new char[n][m]; for (int i=0; i<n; i++) { a[i] = next().toCharArray(); } return a; } ///////////////////////////////////////////////////////////////////////////////////////////////// // output ///////////////////////////////////////////////////////////////////////////////////////////////// static PrintWriter out = new PrintWriter(System.out); public static void print(Object o) {out.print(o);} public static void println(Object o) {out.println(o);} public static void printStringArray(String[] a) { for (int i=0; i<a.length; i++) { if (i != 0) print(" "); print(a[i]); } println(""); } public static void printIntArray(int[] a) { for (int i=0; i<a.length; i++) { if (i != 0) print(" "); print(a[i]); } println(""); } public static void printLongArray(long[] a) { for (int i=0; i<a.length; i++) { if (i != 0) print(" "); print(a[i]); } println(""); } public static void printBooleanArray (boolean[] a) { for (int i=0; i<a.length; i++) { char c = a[i]==true? 'o' : 'x'; print(c); } println(""); } public static void printCharTable(char[][] a) { for (int i=0; i<a.length; i++) { for (int j=0; j<a[0].length; j++) { print(a[i][j]); } println(""); } } public static void printIntTable(int[][] a) { for (int i=0; i<a.length; i++) { for (int j=0; j<a[0].length; j++) { if (j != 0) print(" "); print(a[i][j]); } println(""); } } public static void printBooleanTable(boolean[][] b) { for (int i=0; i<b.length; i++) { for (int j=0; j<b[0].length; j++) { print(b[i][j]? "o" : "x"); } println(""); } } public static void printLongTable(long[][] a) { for (int i=0; i<a.length; i++) { for (int j=0; j<a[0].length; j++) { print(a[i][j]==-infl? "# " : a[i][j]+" "); } println(""); } } ///////////////////////////////////////////////////////////////////////////////////////////////// // main method ///////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { new Thread(null, new Main(), "", 64 * 1024 * 1024).start(); } public void run() { solve(); out.close(); } }
ConDefects/ConDefects/Code/abc271_d/Java/39516131
condefects-java_data_644
import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); int n = scanner.nextInt(); int m = scanner.nextInt(); int k = scanner.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); } System.out.println(solve(n, m, k, a)); } private static final int MAX_N = 5010; private static final int MOD = 998244353; private static final long[][] binom = new long[MAX_N][MAX_N]; static { for (int i = 0; i < MAX_N; i++) { binom[i][0] = 1; for (int j = 1; j <= i; j++) { binom[i][j] = (binom[i - 1][j - 1] + binom[i - 1][j]) % MOD; } } } private static String solve(int n, int m, int k, int[] a) { long ans = 0L; for (int i = 1; i <= m; i++) { int rem = n + 1 - k; int zero = 0; for (int j : a) { if (j >= i) rem--; if (j == 0) zero++; } if (rem < 0 || rem > zero) { ans += (rem < 0 ? 1 : 0); continue; } // 逆元 long p = (m + 1 - i) / m; long p = (m + 1 - i) * quickPow(m, MOD - 2); long[] pPow = new long[zero + 1]; long[] qPow = new long[zero + 1]; Arrays.fill(pPow, 1); Arrays.fill(qPow, 1); for (int j = 0; j < zero; j++) { pPow[j + 1] = (pPow[j] * p % MOD + MOD) % MOD; qPow[j + 1] = (qPow[j] * (1 - p) % MOD + MOD) % MOD; } for (int j = rem; j <= zero; j++) { long x = binom[zero][j] * pPow[j] % MOD * qPow[zero - j] % MOD; ans = (ans + x) % MOD; } } return String.valueOf(ans); } // 模下的 a^b private static long quickPow(long a, long b) { long res = 1L; while (b > 0) { if ((b & 1) == 1) { res = res * a % MOD; } a = a * a % MOD; b >>= 1; } return res; } } /* E - Kth Number https://atcoder.jp/contests/abc295/tasks/abc295_e 题目大意: 我们有一个长度为 N 的序列,由 0 到 M 之间的整数组成,包括:A=(A1, A2,...,AN)。Snuke 将依次执行以下操作 1 和 2。 - 对于每一个 i,使得 A[i] = 0,分别在 1 到 M 之间(含 M)选择一个统一的随机整数,并用该整数替换 A[i]。 - 按升序对 A 排序。 对 998244353 进行模运算后,输出 A[K] 的期望值。 概率 DP。 ====== Input 3 5 2 2 0 4 Output 3 Input 2 3 1 0 0 Output 221832080 Input 10 20 7 6 5 0 2 0 0 0 15 0 0 Output 617586310 */ import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); int n = scanner.nextInt(); int m = scanner.nextInt(); int k = scanner.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); } System.out.println(solve(n, m, k, a)); } private static final int MAX_N = 5010; private static final int MOD = 998244353; private static final long[][] binom = new long[MAX_N][MAX_N]; static { for (int i = 0; i < MAX_N; i++) { binom[i][0] = 1; for (int j = 1; j <= i; j++) { binom[i][j] = (binom[i - 1][j - 1] + binom[i - 1][j]) % MOD; } } } private static String solve(int n, int m, int k, int[] a) { long ans = 0L; for (int i = 1; i <= m; i++) { int rem = n + 1 - k; int zero = 0; for (int j : a) { if (j >= i) rem--; if (j == 0) zero++; } if (rem < 0 || rem > zero) { ans += (rem < 0 ? 1 : 0); continue; } // 逆元 long p = (m + 1 - i) / m; long p = (m + 1 - i) * quickPow(m, MOD - 2) % MOD; long[] pPow = new long[zero + 1]; long[] qPow = new long[zero + 1]; Arrays.fill(pPow, 1); Arrays.fill(qPow, 1); for (int j = 0; j < zero; j++) { pPow[j + 1] = (pPow[j] * p % MOD + MOD) % MOD; qPow[j + 1] = (qPow[j] * (1 - p) % MOD + MOD) % MOD; } for (int j = rem; j <= zero; j++) { long x = binom[zero][j] * pPow[j] % MOD * qPow[zero - j] % MOD; ans = (ans + x) % MOD; } } return String.valueOf(ans); } // 模下的 a^b private static long quickPow(long a, long b) { long res = 1L; while (b > 0) { if ((b & 1) == 1) { res = res * a % MOD; } a = a * a % MOD; b >>= 1; } return res; } } /* E - Kth Number https://atcoder.jp/contests/abc295/tasks/abc295_e 题目大意: 我们有一个长度为 N 的序列,由 0 到 M 之间的整数组成,包括:A=(A1, A2,...,AN)。Snuke 将依次执行以下操作 1 和 2。 - 对于每一个 i,使得 A[i] = 0,分别在 1 到 M 之间(含 M)选择一个统一的随机整数,并用该整数替换 A[i]。 - 按升序对 A 排序。 对 998244353 进行模运算后,输出 A[K] 的期望值。 概率 DP。 ====== Input 3 5 2 2 0 4 Output 3 Input 2 3 1 0 0 Output 221832080 Input 10 20 7 6 5 0 2 0 0 0 15 0 0 Output 617586310 */
ConDefects/ConDefects/Code/abc295_e/Java/40080202
condefects-java_data_645
import static java.lang.Math.*; import static java.util.Arrays.*; import java.io.*; import java.lang.reflect.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; class Solver extends BaseSolver{ public Solver(MyReader in,MyWriter out,MyWriter log){ super(in,out,log); } public static boolean multi = false; public Object solve(){ int N = in.it(); int M = in.it(); int K = in.it(); int[] A = in.it(N); long ans = 0; Combin cm = new Combin(); for (int i = 1;i <= M;i++) { int rem = N +1 -K; int zero = 0; for (int j:A) { if (j >= i) --rem; if (j == 0) ++zero; } if (rem < 0 || rem > zero) { ans += rem < 0 ? 1 : 0; continue; } long p = (M +1 -i) *inv(M); long[] p_pow = new long[zero +1]; long[] q_pow = new long[zero +1]; p_pow[0] = 1; q_pow[0] = 1; for (int pi = 0;pi < zero;pi++) { p_pow[pi +1] = p_pow[pi] *p %mod; q_pow[pi +1] = q_pow[pi] *(1 -p +mod) %mod; } for (int j = rem;j <= zero;j++) ans += cm.nCr(zero,j) *p_pow[j] %mod *q_pow[zero -j] %mod; } return ans %mod; } } class Combin{ int n = 2; long[] f,fi; long mod = Util.mod; public Combin(int n){ this(); grow(n); } public Combin(){ f = fi = new long[]{1, 1}; } public void grow(int n){ n = min((int) mod,n); f = copyOf(f,n); fi = copyOf(fi,n); for (int i = this.n;i < n;i++) f[i] = f[i -1] *i %mod; fi[n -1] = pow(f[n -1],mod -2); for (int i = n;--i > this.n;) fi[i -1] = fi[i] *i %mod; this.n = n; } private long pow(long x,long n){ long ret = 1; for (x %= mod;0 < n;x = x *x %mod,n >>= 1) if ((n &1) == 1) ret = ret *x %mod; return ret; } public long nHr(int n,int r){ return r < 0 ? 0 : nCr(n +r -1,r); } public long nCr(int n,int r){ if (r < 0 || n -r < 0) return 0; if (this.n <= n) grow(max(this.n <<1,n +1)); return f[n] *(fi[r] *fi[n -r] %mod) %mod; } } class UnionFind{ int num; protected int[] dat; protected int[] nxt; public UnionFind(int n){ dat = new int[n]; nxt = new int[n]; setAll(nxt,i -> i); fill(dat,-1); num = n; } public int root(int x){ return dat[x] < 0 ? x : (dat[x] = root(dat[x])); } public boolean same(int u,int v){ return root(u) == root(v); } public boolean unite(int u,int v){ if ((u = root(u)) == (v = root(v))) return false; if (dat[u] > dat[v]) { u ^= v; v ^= u; u ^= v; } dat[u] += dat[v]; dat[v] = u; num--; nxt[u] ^= nxt[v]; nxt[v] ^= nxt[u]; nxt[u] ^= nxt[v]; return true; } public int size(int x){ return -dat[root(x)]; } public int[] getGroup(int x){ int[] ret = new int[size(x)]; for (int i = 0,c = root(x);i < ret.length;i++) ret[i] = c = nxt[c]; return ret; } } abstract class ReRootingDp<L, D, A> extends Graph<L>{ private D[] dp; private A[] ans; public ReRootingDp(int N){ super(N,false); dp = Util.cast(new Object[2 *N]); ans = Util.cast(Array.newInstance(ans(0,e()).getClass(),n)); } protected abstract D e(); protected abstract D agg(D a,D b); protected abstract D adj(D v,Edge<L> e); protected abstract A ans(int u,D sum); protected MyList<D> sur(int u){ return go(u).map(e -> dp[e.id]); } public A[] calc(){ for (var e:es) e.re.id = e.id +n; var stk = new MyStack<Edge<L>>(); var se = new Edge<L>(n -1,-1,0,null); stk.add(se); while (!stk.isEmpty()) { var e = stk.pop(); if (dp[e.id] == null) { dp[e.id] = e(); for (var ee:go(e.v)) if (ee != e.re) { stk.add(ee); stk.add(ee); } } else { for (var ee:go(e.v)) if (ee != e.re) dp[e.id] = agg(dp[e.id],dp[ee.id]); if (e.u > -1) dp[e.id] = adj(dp[e.id],e); } } stk.add(se); while (!stk.isEmpty()) { var e = stk.pop(); var es = go(e.v); int n = es.size(); D[] pre = Util.cast(new Object[n +1]),suf = Util.cast(new Object[n +1]); pre[0] = e(); suf[n] = e(); for (int i = 0;i < n;i++) { pre[i +1] = agg(pre[i],dp[es.get(i).id]); suf[n -1 -i] = agg(dp[es.get(n -1 -i).id],suf[n -i]); } ans[e.v] = ans(e.v,suf[0]); for (int i = 0;i < n;i++) { Edge<L> ee = es.get(i); if (ee != e.re) { dp[ee.re.id] = adj(agg(pre[i],suf[i +1]),ee.re); stk.add(ee); } } } return ans; } } class Edge<L> { public int id,u,v; public L val; public Edge<L> re; public Edge(int id,int u,int v,L val){ this.id = id; this.u = u; this.v = v; this.val = val; } } class Graph<L> { public int n; public MyList<Edge<L>> es; private MyList<Edge<L>>[] go,bk; public Graph(int n,boolean dir){ this.n = n; go = Util.cast(new MyList[n]); bk = dir ? Util.cast(new MyList[n]) : go; for (int i = 0;i < n;i++) { go[i] = new MyList<>(); bk[i] = new MyList<>(); } es = new MyList<>(); } protected L inv(L l){ return l; } public void addEdge(int u,int v){ addEdge(u,v,null); } public void addEdge(int u,int v,L l){ var e = new Edge<>(es.size(),u,v,l); var re = new Edge<>(e.id,e.v,e.u,inv(e.val)); es.add(e); go[u].add(re.re = e); bk[v].add(e.re = re); } public MyList<Edge<L>> go(int u){ return go[u]; } public MyList<Edge<L>> bk(int u){ return bk[u]; } } abstract class AVLSegmentTree<V extends BaseV, F> { private V e = e(),t = e(); private Node root; public AVLSegmentTree(int n){ root = new Node(e(),n); } public AVLSegmentTree(){} public void build(int n,IntFunction<V> init){ root = build(0,n,init); } private Node build(int i,int n,IntFunction<V> init){ if (n < 2) return n < 1 ? null : new Node(init.apply(i),1); var ret = new Node(e(),n); ret.cld(-1,build(i,n /2,init)); ret.cld(1,build(i +n /2,n -n /2,init)); return ret.merge(); } public void add(V v){ add(v,1); } public void add(V v,int k){ ins(size(),v,k); } public void ins(int i,V v){ ins(i,v,1); } public void ins(int i,V v,int k){ root = root == null ? new Node(v,k) : ins(root,i,v,k); } private Node ins(Node nd,int i,V v,int k){ if (nd.lft == null && (i == 0 || i == nd.sz)) { split(nd,i == 0 ? 1 : -1,v,k,nd.sz +k); return nd.merge(); } if (nd.lft == null) split(nd,1,ag(e(),e,nd.val),i,nd.sz); else nd.push(); if (i < nd.lft.sz) nd.cld(-1,ins(nd.lft,i,v,k)); else nd.cld(1,ins(nd.rht,i -nd.lft.sz,v,k)); return balance(nd); } public V del(int i){ var ret = e(); root = del(ret,root,i); return ret; } private Node del(V ret,Node nd,int i){ if (nd.lft == null) { nd.sz--; ag(ret,e,nd.val); return 0 < nd.sz ? nd : null; } nd.push(); int c = i < nd.lft.sz ? -1 : 1; Node del = c < 0 ? del(ret,nd.lft,i) : del(ret,nd.rht,i -nd.lft.sz); if (del == null) return nd.cld(-c); nd.cld(c,del); return balance(nd); } public void upd(int i,F f){ upd(i,i +1,f); } public void upd(int l,int r,F f){ if (l == r) return; if (size() < r) add(e(),r -size()); root = upd(root,l,r,f); } private Node upd(Node nd,int l,int r,F f){ if (l == 0 && r == nd.sz) return nd.prop(f); if (nd.lft == null) split(nd,1,ag(e(),e,nd.val),0 < l ? l : r,nd.sz); else nd.push(); if (l < nd.lft.sz) nd.cld(-1,upd(nd.lft,l,min(nd.lft.sz,r),f)); if (nd.lft.sz < r) nd.cld(1,upd(nd.rht,max(0,l -nd.lft.sz),r -nd.lft.sz,f)); return balance(nd); } public void toggle(int l,int r){ root = l < r ? toggle(root,l,r) : root; } private Node toggle(Node nd,int l,int r){ nd.push(); if (0 < l) { split(nd,l); return merge(nd.lft,nd,toggle(nd.rht,0,r -l)); } if (r < nd.sz) { split(nd,r); return merge(toggle(nd.lft,l,r),nd,nd.rht); } return nd.toggle(); } private void split(Node nd,int i){ if (nd.lft == null) split(nd,1,ag(e(),e,nd.val),i,nd.sz); else { nd.push(); if (i < nd.lft.sz) { split(nd.lft,i); var lft = nd.lft; nd.cld(-1,lft.lft); nd.cld(1,merge(lft.rht,lft,nd.rht)); } else if (nd.lft.sz < i) { split(nd.rht,i -nd.lft.sz); var rht = nd.rht; nd.cld(1,rht.rht); nd.cld(-1,merge(nd.lft,rht,rht.lft)); } } } private Node merge(Node lft,Node nd,Node rht){ if (abs(lft.rnk -rht.rnk) < 2) { nd.cld(-1,lft); nd.cld(1,rht); } else if (lft.rnk > rht.rnk) { lft.push().cld(1,merge(lft.rht,nd,rht)); nd = lft; } else if (lft.rnk < rht.rnk) { rht.push().cld(-1,merge(lft,nd,rht.lft)); nd = rht; } return balance(nd); } public V get(int i){ return get(i,i +1); } public V get(int l,int r){ V ret = e(); if (root != null) get(ret,root,l,min(r,size())); return ret; } private void get(V ret,Node nd,int l,int r){ if (l == 0 && r == nd.sz) ag(ret,ret,nd.val()); else if (nd.lft == null) ag(ret,ret,pw(nd.val,r -l)); else { nd.push(); if (l < nd.lft.sz) get(ret,nd.lft,l,min(nd.lft.sz,r)); if (nd.lft.sz < r) get(ret,nd.rht,max(0,l -nd.lft.sz),r -nd.lft.sz); } } public V all(){ return root == null ? e : root.val(); } public int size(){ return root == null ? 0 : root.sz; } protected abstract V e(); protected abstract void agg(V v,V a,V b); protected abstract void map(V v,F f); protected abstract F comp(F f,F g); protected abstract void tog(V v); private V ag(V v,V a,V b){ agg(v,a,b); v.sz = a.sz +b.sz; return v; } protected void pow(V v,V a,int n){ for (ag(t,e,a);0 < n;n >>= 1,ag(t,t,t)) if (0 < (n &1)) ag(v,v,t); } private V pw(V a,int n){ V ret = e(); pow(ret,a,n); ret.sz = n; return ret; } private void split(Node nd,int c,V vl,int i,int sz){ nd.cld(-c,new Node(vl,i)); nd.cld(c,new Node(nd.val,sz -i)); nd.val = e(); } private Node balance(Node nd){ return (1 < abs(nd.bis = nd.rht.rnk -nd.lft.rnk) ? (nd = rotate(nd)) : nd).merge(); } private Node rotate(Node u){ var v = u.cld(u.bis).push(); if (u.bis *v.bis < -1) v = rotate(v); u.cld(u.bis,v.cld(-u.bis)); v.cld(-u.bis,u); u.merge(); return v; } private class Node{ private int sz,bis,rnk,tog; private V val; private F laz; private Node lft,rht; private Node(V val,int sz){ this.sz = sz; this.val = val; val.sz = 1; } private Node merge(){ bis = rht.rnk -lft.rnk; rnk = max(lft.rnk,rht.rnk) +1; ag(val,lft.val(),rht.val()); sz = val.sz; return this; } private Node push(){ if (laz != null) { lft.prop(laz); rht.prop(laz); laz = null; } if (0 < tog) { lft.toggle(); rht.toggle(); tog = 0; } return this; } private Node prop(F f){ map(val,f); if (lft != null) laz = laz == null ? f : comp(laz,f); return this; } private Node toggle(){ bis *= -1; var tn = lft; lft = rht; rht = tn; tog(val); if (lft != null) tog ^= 1; return this; } private Node cld(int c){ return c < 0 ? lft : rht; } private void cld(int c,Node nd){ nd = c < 0 ? (lft = nd) : (rht = nd); } private V val(){ return lft == null && 1 < sz ? pw(val,sz) : val; } } } abstract class SparseTable2D{ int h,w,hl,wl; long[][][][] tbl; SparseTable2D(int h,int w){ hl = max(1,32 -Integer.numberOfLeadingZeros((this.h = h) -1)); wl = max(1,32 -Integer.numberOfLeadingZeros((this.w = w) -1)); tbl = new long[hl][wl][][]; for (int hi = 0;hi < hl;hi++) for (int wi = 0;wi < wl;wi++) { int hhl = h -(1 <<hi) +1; int wwl = w -(1 <<wi) +1; tbl[hi][wi] = new long[hhl][wwl]; for (int i = 0;i < hhl;i++) for (int j = 0;j < wwl;j++) if ((hi |wi) == 0) tbl[0][0][i][j] = init(i,j); else if (0 < hi) tbl[hi][wi][i][j] = agg(tbl[hi -1][wi][i][j],tbl[hi -1][wi][i +(1 <<hi -1)][j]); else tbl[hi][wi][i][j] = agg(tbl[hi][wi -1][i][j],tbl[hi][wi -1][i][j +(1 <<wi -1)]); } } abstract protected long init(int i,int j); abstract protected long agg(long a,long b); long get(int i0,int j0,int i1,int j1){ int il = max(0,31 -Integer.numberOfLeadingZeros(i1 -i0 -1)); int jl = max(0,31 -Integer.numberOfLeadingZeros(j1 -j0 -1)); i1 = max(0,i1 -(1 <<il)); j1 = max(0,j1 -(1 <<jl)); long[][] tmp = tbl[il][jl]; long ret = agg(tmp[i0][j0],tmp[i0][j1]); ret = agg(ret,tmp[i1][j0]); ret = agg(ret,tmp[i1][j1]); return ret; } } abstract class SparseTable{ int n; long[] tbl; SparseTable(int n){ int K = max(1,32 -Integer.numberOfLeadingZeros(n -1)); this.n = 1 <<K; tbl = new long[K *this.n]; for (int i = 0;i < this.n;i++) tbl[i] = i < n ? init(i) : 0; for (int k = 1;k < K;k++) for (int s = 1 <<k;s < this.n;s += 2 <<k) { int b = k *this.n; tbl[b +s] = s < n ? init(s) : 0; tbl[b +s -1] = s < n ? init(s -1) : 0; for (int i = 1;i < 1 <<k;i++) { tbl[b +s +i] = agg(tbl[b +s +i -1],tbl[s +i]); tbl[b +s -1 -i] = agg(tbl[b +s -i],tbl[s -1 -i]); } } } abstract protected long init(int i); abstract protected long agg(long a,long b); long get(int l,int r){ r--; if (l == r) return tbl[l]; int k = 31 -Integer.numberOfLeadingZeros(l ^r); return agg(tbl[k *n +l],tbl[k *n +r]); } } abstract class Sum2D{ private long[] sum; private int w; public Sum2D(int h,int w){ this.w = w; sum = new long[(h +1) *(w +1)]; for (int i = 0;i < h;i++) for (int j = 0;j < w;j++) sum[top(i +1,j +1)] = a(i,j) +sum[top(i +1,j)] +sum[top(i,j +1)] -sum[top(i,j)]; } abstract long a(int i,int j); private int top(int i,int j){ return i *(w +1) +j; } long get(int il,int ir,int jl,int jr){ return sum[top(ir,jr)] -sum[top(il,jr)] -sum[top(ir,jl)] +sum[top(il,jl)]; } } class Data extends BaseV{ long v; public Data(long v){ this.v = v; } @Override public String toString(){ return "" +v; } } abstract class BaseV{ public int sz; public boolean fail; } class MyStack<T> extends MyList<T>{ public T pop(){ return remove(size() -1); } public T peek(){ return get(size() -1); } } class MyList<T> implements Iterable<T>{ private T[] arr; private int sz; public MyList(){ this(16); } public MyList(int n){ arr = Util.cast(new Object[n]); } public boolean isEmpty(){ return sz == 0; } public int size(){ return sz; } public T get(int i){ return arr[i]; } public void add(T t){ (arr = sz < arr.length ? arr : copyOf(arr,sz *5 >>2))[sz++] = t; } public T remove(int i){ var ret = arr[i]; sz--; for (int j = i;j < sz;j++) arr[j] = arr[j +1]; return ret; } public T removeFast(int i){ var ret = arr[i]; arr[i] = arr[--sz]; return ret; } public void sort(){ sort(Util.cast(Comparator.naturalOrder())); } public void sort(Comparator<T> cmp){ Arrays.sort(arr,0,sz,cmp); } @Override public Iterator<T> iterator(){ return new Iterator<>(){ int i = 0; @Override public boolean hasNext(){ return i < sz; } @Override public T next(){ return arr[i++]; } }; } public <U> MyList<U> map(Function<T, U> func){ MyList<U> ret = new MyList<>(sz); forEach(t -> ret.add(func.apply(t))); return ret; } public T[] toArray(){ return copyOf(arr,sz); } public void swap(int i,int j){ var t = arr[i]; arr[i] = arr[j]; arr[j] = t; } public void set(int i,T t){ arr[i] = t; } } class BaseSolver extends Util{ public MyReader in; public MyWriter out,log; public BaseSolver(MyReader in,MyWriter out,MyWriter log){ this.in = in; this.out = out; this.log = log; } protected long inv(long x){ return pow(x,mod -2); } protected long pow(long x,long n){ return pow(x,n,Util.mod); } protected long pow(long x,long n,long mod){ long ret = 1; for (x %= mod;0 < n;x = x *x %mod,n >>= 1) if ((n &1) == 1) ret = ret *x %mod; return ret; } protected int bSearchI(int o,int n,IntPredicate judge){ if (!judge.test(o)) return o -Integer.signum(n -o); for (int m = 0;1 < abs(n -o);) m = judge.test(m = o +n >>1) ? (o = m) : (n = m); return o; } protected long bSearchL(long o,long n,LongPredicate judge){ for (long m = 0;1 < abs(n -o);) m = judge.test(m = o +n >>1) ? (o = m) : (n = m); return o; } protected double bSearchD(double o,double n,DoublePredicate judge){ for (double m,c = 0;c < 100;c++) m = judge.test(m = (o +n) /2) ? (o = m) : (n = m); return o; } protected long gcd(long a,long b){ while (0 < b) { long t = a; a = b; b = t %b; } return a; } public long lcm(long a,long b){ return b /gcd(a,b) *a; } protected long ceil(long a,long b){ return (a +b -1) /b; } } class Util{ public static String yes = "Yes",no = "No"; public static int infI = (1 <<30) -1; public static long infL = (1L <<61 |1 <<30) -1, mod = 998244353; public static Random rd = ThreadLocalRandom.current(); private long st = System.currentTimeMillis(); protected long elapsed(){ return System.currentTimeMillis() -st; } protected void reset(){ st = System.currentTimeMillis(); } public static int[] arrI(int N,IntUnaryOperator f){ int[] ret = new int[N]; setAll(ret,f); return ret; } public static long[] arrL(int N,IntToLongFunction f){ long[] ret = new long[N]; setAll(ret,f); return ret; } public static double[] arrD(int N,IntToDoubleFunction f){ double[] ret = new double[N]; setAll(ret,f); return ret; } public static <T> T[] arr(T[] arr,IntFunction<T> f){ setAll(arr,f); return arr; } public int[][] addId(int[][] T){ return arr(new int[T.length][],i -> { int[] t = copyOf(T[i],T[i].length +1); t[t.length -1] = i; return t; }); } @SuppressWarnings("unchecked") public static <T> T cast(Object obj){ return (T) obj; } } class MyReader{ private byte[] buf = new byte[1 <<16]; private int ptr,tail; private InputStream in; public MyReader(InputStream in){ this.in = in; } private byte read(){ if (ptr == tail) try { tail = in.read(buf); ptr = 0; } catch (IOException e) {} return buf[ptr++]; } private boolean isPrintable(byte c){ return 32 < c && c < 127; } private byte nextPrintable(){ byte ret = read(); while (!isPrintable(ret)) ret = read(); return ret; } public int it(){ return toIntExact(lg()); } public int[] it(int N){ return Util.arrI(N,i -> it()); } public int[][] it(int H,int W){ return Util.arr(new int[H][],i -> it(W)); } public int idx(){ return it() -1; } public int[] idx(int N){ return Util.arrI(N,i -> idx()); } public int[][] idx(int H,int W){ return Util.arr(new int[H][],i -> idx(W)); } public long lg(){ byte i = nextPrintable(); boolean negative = i == 45; long n = negative ? 0 : i -'0'; while (isPrintable(i = read())) n = 10 *n +i -'0'; return negative ? -n : n; } public long[] lg(int N){ return Util.arrL(N,i -> lg()); } public long[][] lg(int H,int W){ return Util.arr(new long[H][],i -> lg(W)); } public double dbl(){ return Double.parseDouble(str()); } public double[] dbl(int N){ return Util.arrD(N,i -> dbl()); } public double[][] dbl(int H,int W){ return Util.arr(new double[H][],i -> dbl(W)); } public char[] ch(){ return str().toCharArray(); } public char[][] ch(int H){ return Util.arr(new char[H][],i -> ch()); } public String line(){ StringBuilder sb = new StringBuilder(); for (byte c;(c = read()) != '\n';) sb.append((char) c); return sb.toString(); } public String str(){ StringBuilder sb = new StringBuilder(); sb.append((char) nextPrintable()); for (byte c;isPrintable(c = read());) sb.append((char) c); return sb.toString(); } public String[] str(int N){ return Util.arr(new String[N],i -> str()); } } class MyWriter{ private OutputStream out; private byte[] buf = new byte[1 <<16],ibuf = new byte[20]; private int tail; private boolean autoflush; public MyWriter(OutputStream out,boolean autoflush){ this.out = out; this.autoflush = autoflush; } public void flush(){ try { out.write(buf,0,tail); tail = 0; } catch (IOException e) { e.printStackTrace(); } } private void ln(){ write((byte) '\n'); if (autoflush) flush(); } private void write(byte b){ buf[tail++] = b; if (tail == buf.length) flush(); } private void write(long n){ if (n < 0) { n = -n; write((byte) '-'); } int i = ibuf.length; do { ibuf[--i] = (byte) (n %10 +'0'); n /= 10; } while (n > 0); while (i < ibuf.length) write(ibuf[i++]); } private void print(Object obj){ if (obj instanceof Boolean) print((boolean) obj ? Util.yes : Util.no); else if (obj instanceof Integer) write((int) obj); else if (obj instanceof Long) write((long) obj); else if (obj instanceof char[]) for (char b:(char[]) obj) write((byte) b); else if (obj.getClass().isArray()) { int l = Array.getLength(obj); for (int i = 0;i < l;i++) { print(Array.get(obj,i)); if (i +1 < l) write((byte) ' '); } } else print(Objects.toString(obj).toCharArray()); } public void println(Object obj){ if (obj == null) obj = "null"; if (obj instanceof Iterable<?>) for (Object e:(Iterable<?>) obj) println(e); else if (obj.getClass().isArray() && Array.getLength(obj) > 0 && Array.get(obj,0).getClass().isArray()) { int l = Array.getLength(obj); for (int i = 0;i < l;i++) println(Array.get(obj,i)); } else { print(obj); ln(); } } public void printlns(Object... o){ print(o); ln(); } } class Main{ public static void main(String[] args) throws Exception{ var in = new MyReader(System.in); var out = new MyWriter(System.out,false); var log = new MyWriter(System.err,true); int T = Solver.multi ? in.it() : 1; while (T-- > 0) Optional.ofNullable(new Solver(in,out,log) .solve()).ifPresent(out::println); out.flush(); } } import static java.lang.Math.*; import static java.util.Arrays.*; import java.io.*; import java.lang.reflect.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; class Solver extends BaseSolver{ public Solver(MyReader in,MyWriter out,MyWriter log){ super(in,out,log); } public static boolean multi = false; public Object solve(){ int N = in.it(); int M = in.it(); int K = in.it(); int[] A = in.it(N); long ans = 0; Combin cm = new Combin(); for (int i = 1;i <= M;i++) { int rem = N +1 -K; int zero = 0; for (int j:A) { if (j >= i) --rem; if (j == 0) ++zero; } if (rem < 0 || rem > zero) { ans += rem < 0 ? 1 : 0; continue; } long p = (M +1 -i) *inv(M) %mod; long[] p_pow = new long[zero +1]; long[] q_pow = new long[zero +1]; p_pow[0] = 1; q_pow[0] = 1; for (int pi = 0;pi < zero;pi++) { p_pow[pi +1] = p_pow[pi] *p %mod; q_pow[pi +1] = q_pow[pi] *(1 -p +mod) %mod; } for (int j = rem;j <= zero;j++) ans += cm.nCr(zero,j) *p_pow[j] %mod *q_pow[zero -j] %mod; } return ans %mod; } } class Combin{ int n = 2; long[] f,fi; long mod = Util.mod; public Combin(int n){ this(); grow(n); } public Combin(){ f = fi = new long[]{1, 1}; } public void grow(int n){ n = min((int) mod,n); f = copyOf(f,n); fi = copyOf(fi,n); for (int i = this.n;i < n;i++) f[i] = f[i -1] *i %mod; fi[n -1] = pow(f[n -1],mod -2); for (int i = n;--i > this.n;) fi[i -1] = fi[i] *i %mod; this.n = n; } private long pow(long x,long n){ long ret = 1; for (x %= mod;0 < n;x = x *x %mod,n >>= 1) if ((n &1) == 1) ret = ret *x %mod; return ret; } public long nHr(int n,int r){ return r < 0 ? 0 : nCr(n +r -1,r); } public long nCr(int n,int r){ if (r < 0 || n -r < 0) return 0; if (this.n <= n) grow(max(this.n <<1,n +1)); return f[n] *(fi[r] *fi[n -r] %mod) %mod; } } class UnionFind{ int num; protected int[] dat; protected int[] nxt; public UnionFind(int n){ dat = new int[n]; nxt = new int[n]; setAll(nxt,i -> i); fill(dat,-1); num = n; } public int root(int x){ return dat[x] < 0 ? x : (dat[x] = root(dat[x])); } public boolean same(int u,int v){ return root(u) == root(v); } public boolean unite(int u,int v){ if ((u = root(u)) == (v = root(v))) return false; if (dat[u] > dat[v]) { u ^= v; v ^= u; u ^= v; } dat[u] += dat[v]; dat[v] = u; num--; nxt[u] ^= nxt[v]; nxt[v] ^= nxt[u]; nxt[u] ^= nxt[v]; return true; } public int size(int x){ return -dat[root(x)]; } public int[] getGroup(int x){ int[] ret = new int[size(x)]; for (int i = 0,c = root(x);i < ret.length;i++) ret[i] = c = nxt[c]; return ret; } } abstract class ReRootingDp<L, D, A> extends Graph<L>{ private D[] dp; private A[] ans; public ReRootingDp(int N){ super(N,false); dp = Util.cast(new Object[2 *N]); ans = Util.cast(Array.newInstance(ans(0,e()).getClass(),n)); } protected abstract D e(); protected abstract D agg(D a,D b); protected abstract D adj(D v,Edge<L> e); protected abstract A ans(int u,D sum); protected MyList<D> sur(int u){ return go(u).map(e -> dp[e.id]); } public A[] calc(){ for (var e:es) e.re.id = e.id +n; var stk = new MyStack<Edge<L>>(); var se = new Edge<L>(n -1,-1,0,null); stk.add(se); while (!stk.isEmpty()) { var e = stk.pop(); if (dp[e.id] == null) { dp[e.id] = e(); for (var ee:go(e.v)) if (ee != e.re) { stk.add(ee); stk.add(ee); } } else { for (var ee:go(e.v)) if (ee != e.re) dp[e.id] = agg(dp[e.id],dp[ee.id]); if (e.u > -1) dp[e.id] = adj(dp[e.id],e); } } stk.add(se); while (!stk.isEmpty()) { var e = stk.pop(); var es = go(e.v); int n = es.size(); D[] pre = Util.cast(new Object[n +1]),suf = Util.cast(new Object[n +1]); pre[0] = e(); suf[n] = e(); for (int i = 0;i < n;i++) { pre[i +1] = agg(pre[i],dp[es.get(i).id]); suf[n -1 -i] = agg(dp[es.get(n -1 -i).id],suf[n -i]); } ans[e.v] = ans(e.v,suf[0]); for (int i = 0;i < n;i++) { Edge<L> ee = es.get(i); if (ee != e.re) { dp[ee.re.id] = adj(agg(pre[i],suf[i +1]),ee.re); stk.add(ee); } } } return ans; } } class Edge<L> { public int id,u,v; public L val; public Edge<L> re; public Edge(int id,int u,int v,L val){ this.id = id; this.u = u; this.v = v; this.val = val; } } class Graph<L> { public int n; public MyList<Edge<L>> es; private MyList<Edge<L>>[] go,bk; public Graph(int n,boolean dir){ this.n = n; go = Util.cast(new MyList[n]); bk = dir ? Util.cast(new MyList[n]) : go; for (int i = 0;i < n;i++) { go[i] = new MyList<>(); bk[i] = new MyList<>(); } es = new MyList<>(); } protected L inv(L l){ return l; } public void addEdge(int u,int v){ addEdge(u,v,null); } public void addEdge(int u,int v,L l){ var e = new Edge<>(es.size(),u,v,l); var re = new Edge<>(e.id,e.v,e.u,inv(e.val)); es.add(e); go[u].add(re.re = e); bk[v].add(e.re = re); } public MyList<Edge<L>> go(int u){ return go[u]; } public MyList<Edge<L>> bk(int u){ return bk[u]; } } abstract class AVLSegmentTree<V extends BaseV, F> { private V e = e(),t = e(); private Node root; public AVLSegmentTree(int n){ root = new Node(e(),n); } public AVLSegmentTree(){} public void build(int n,IntFunction<V> init){ root = build(0,n,init); } private Node build(int i,int n,IntFunction<V> init){ if (n < 2) return n < 1 ? null : new Node(init.apply(i),1); var ret = new Node(e(),n); ret.cld(-1,build(i,n /2,init)); ret.cld(1,build(i +n /2,n -n /2,init)); return ret.merge(); } public void add(V v){ add(v,1); } public void add(V v,int k){ ins(size(),v,k); } public void ins(int i,V v){ ins(i,v,1); } public void ins(int i,V v,int k){ root = root == null ? new Node(v,k) : ins(root,i,v,k); } private Node ins(Node nd,int i,V v,int k){ if (nd.lft == null && (i == 0 || i == nd.sz)) { split(nd,i == 0 ? 1 : -1,v,k,nd.sz +k); return nd.merge(); } if (nd.lft == null) split(nd,1,ag(e(),e,nd.val),i,nd.sz); else nd.push(); if (i < nd.lft.sz) nd.cld(-1,ins(nd.lft,i,v,k)); else nd.cld(1,ins(nd.rht,i -nd.lft.sz,v,k)); return balance(nd); } public V del(int i){ var ret = e(); root = del(ret,root,i); return ret; } private Node del(V ret,Node nd,int i){ if (nd.lft == null) { nd.sz--; ag(ret,e,nd.val); return 0 < nd.sz ? nd : null; } nd.push(); int c = i < nd.lft.sz ? -1 : 1; Node del = c < 0 ? del(ret,nd.lft,i) : del(ret,nd.rht,i -nd.lft.sz); if (del == null) return nd.cld(-c); nd.cld(c,del); return balance(nd); } public void upd(int i,F f){ upd(i,i +1,f); } public void upd(int l,int r,F f){ if (l == r) return; if (size() < r) add(e(),r -size()); root = upd(root,l,r,f); } private Node upd(Node nd,int l,int r,F f){ if (l == 0 && r == nd.sz) return nd.prop(f); if (nd.lft == null) split(nd,1,ag(e(),e,nd.val),0 < l ? l : r,nd.sz); else nd.push(); if (l < nd.lft.sz) nd.cld(-1,upd(nd.lft,l,min(nd.lft.sz,r),f)); if (nd.lft.sz < r) nd.cld(1,upd(nd.rht,max(0,l -nd.lft.sz),r -nd.lft.sz,f)); return balance(nd); } public void toggle(int l,int r){ root = l < r ? toggle(root,l,r) : root; } private Node toggle(Node nd,int l,int r){ nd.push(); if (0 < l) { split(nd,l); return merge(nd.lft,nd,toggle(nd.rht,0,r -l)); } if (r < nd.sz) { split(nd,r); return merge(toggle(nd.lft,l,r),nd,nd.rht); } return nd.toggle(); } private void split(Node nd,int i){ if (nd.lft == null) split(nd,1,ag(e(),e,nd.val),i,nd.sz); else { nd.push(); if (i < nd.lft.sz) { split(nd.lft,i); var lft = nd.lft; nd.cld(-1,lft.lft); nd.cld(1,merge(lft.rht,lft,nd.rht)); } else if (nd.lft.sz < i) { split(nd.rht,i -nd.lft.sz); var rht = nd.rht; nd.cld(1,rht.rht); nd.cld(-1,merge(nd.lft,rht,rht.lft)); } } } private Node merge(Node lft,Node nd,Node rht){ if (abs(lft.rnk -rht.rnk) < 2) { nd.cld(-1,lft); nd.cld(1,rht); } else if (lft.rnk > rht.rnk) { lft.push().cld(1,merge(lft.rht,nd,rht)); nd = lft; } else if (lft.rnk < rht.rnk) { rht.push().cld(-1,merge(lft,nd,rht.lft)); nd = rht; } return balance(nd); } public V get(int i){ return get(i,i +1); } public V get(int l,int r){ V ret = e(); if (root != null) get(ret,root,l,min(r,size())); return ret; } private void get(V ret,Node nd,int l,int r){ if (l == 0 && r == nd.sz) ag(ret,ret,nd.val()); else if (nd.lft == null) ag(ret,ret,pw(nd.val,r -l)); else { nd.push(); if (l < nd.lft.sz) get(ret,nd.lft,l,min(nd.lft.sz,r)); if (nd.lft.sz < r) get(ret,nd.rht,max(0,l -nd.lft.sz),r -nd.lft.sz); } } public V all(){ return root == null ? e : root.val(); } public int size(){ return root == null ? 0 : root.sz; } protected abstract V e(); protected abstract void agg(V v,V a,V b); protected abstract void map(V v,F f); protected abstract F comp(F f,F g); protected abstract void tog(V v); private V ag(V v,V a,V b){ agg(v,a,b); v.sz = a.sz +b.sz; return v; } protected void pow(V v,V a,int n){ for (ag(t,e,a);0 < n;n >>= 1,ag(t,t,t)) if (0 < (n &1)) ag(v,v,t); } private V pw(V a,int n){ V ret = e(); pow(ret,a,n); ret.sz = n; return ret; } private void split(Node nd,int c,V vl,int i,int sz){ nd.cld(-c,new Node(vl,i)); nd.cld(c,new Node(nd.val,sz -i)); nd.val = e(); } private Node balance(Node nd){ return (1 < abs(nd.bis = nd.rht.rnk -nd.lft.rnk) ? (nd = rotate(nd)) : nd).merge(); } private Node rotate(Node u){ var v = u.cld(u.bis).push(); if (u.bis *v.bis < -1) v = rotate(v); u.cld(u.bis,v.cld(-u.bis)); v.cld(-u.bis,u); u.merge(); return v; } private class Node{ private int sz,bis,rnk,tog; private V val; private F laz; private Node lft,rht; private Node(V val,int sz){ this.sz = sz; this.val = val; val.sz = 1; } private Node merge(){ bis = rht.rnk -lft.rnk; rnk = max(lft.rnk,rht.rnk) +1; ag(val,lft.val(),rht.val()); sz = val.sz; return this; } private Node push(){ if (laz != null) { lft.prop(laz); rht.prop(laz); laz = null; } if (0 < tog) { lft.toggle(); rht.toggle(); tog = 0; } return this; } private Node prop(F f){ map(val,f); if (lft != null) laz = laz == null ? f : comp(laz,f); return this; } private Node toggle(){ bis *= -1; var tn = lft; lft = rht; rht = tn; tog(val); if (lft != null) tog ^= 1; return this; } private Node cld(int c){ return c < 0 ? lft : rht; } private void cld(int c,Node nd){ nd = c < 0 ? (lft = nd) : (rht = nd); } private V val(){ return lft == null && 1 < sz ? pw(val,sz) : val; } } } abstract class SparseTable2D{ int h,w,hl,wl; long[][][][] tbl; SparseTable2D(int h,int w){ hl = max(1,32 -Integer.numberOfLeadingZeros((this.h = h) -1)); wl = max(1,32 -Integer.numberOfLeadingZeros((this.w = w) -1)); tbl = new long[hl][wl][][]; for (int hi = 0;hi < hl;hi++) for (int wi = 0;wi < wl;wi++) { int hhl = h -(1 <<hi) +1; int wwl = w -(1 <<wi) +1; tbl[hi][wi] = new long[hhl][wwl]; for (int i = 0;i < hhl;i++) for (int j = 0;j < wwl;j++) if ((hi |wi) == 0) tbl[0][0][i][j] = init(i,j); else if (0 < hi) tbl[hi][wi][i][j] = agg(tbl[hi -1][wi][i][j],tbl[hi -1][wi][i +(1 <<hi -1)][j]); else tbl[hi][wi][i][j] = agg(tbl[hi][wi -1][i][j],tbl[hi][wi -1][i][j +(1 <<wi -1)]); } } abstract protected long init(int i,int j); abstract protected long agg(long a,long b); long get(int i0,int j0,int i1,int j1){ int il = max(0,31 -Integer.numberOfLeadingZeros(i1 -i0 -1)); int jl = max(0,31 -Integer.numberOfLeadingZeros(j1 -j0 -1)); i1 = max(0,i1 -(1 <<il)); j1 = max(0,j1 -(1 <<jl)); long[][] tmp = tbl[il][jl]; long ret = agg(tmp[i0][j0],tmp[i0][j1]); ret = agg(ret,tmp[i1][j0]); ret = agg(ret,tmp[i1][j1]); return ret; } } abstract class SparseTable{ int n; long[] tbl; SparseTable(int n){ int K = max(1,32 -Integer.numberOfLeadingZeros(n -1)); this.n = 1 <<K; tbl = new long[K *this.n]; for (int i = 0;i < this.n;i++) tbl[i] = i < n ? init(i) : 0; for (int k = 1;k < K;k++) for (int s = 1 <<k;s < this.n;s += 2 <<k) { int b = k *this.n; tbl[b +s] = s < n ? init(s) : 0; tbl[b +s -1] = s < n ? init(s -1) : 0; for (int i = 1;i < 1 <<k;i++) { tbl[b +s +i] = agg(tbl[b +s +i -1],tbl[s +i]); tbl[b +s -1 -i] = agg(tbl[b +s -i],tbl[s -1 -i]); } } } abstract protected long init(int i); abstract protected long agg(long a,long b); long get(int l,int r){ r--; if (l == r) return tbl[l]; int k = 31 -Integer.numberOfLeadingZeros(l ^r); return agg(tbl[k *n +l],tbl[k *n +r]); } } abstract class Sum2D{ private long[] sum; private int w; public Sum2D(int h,int w){ this.w = w; sum = new long[(h +1) *(w +1)]; for (int i = 0;i < h;i++) for (int j = 0;j < w;j++) sum[top(i +1,j +1)] = a(i,j) +sum[top(i +1,j)] +sum[top(i,j +1)] -sum[top(i,j)]; } abstract long a(int i,int j); private int top(int i,int j){ return i *(w +1) +j; } long get(int il,int ir,int jl,int jr){ return sum[top(ir,jr)] -sum[top(il,jr)] -sum[top(ir,jl)] +sum[top(il,jl)]; } } class Data extends BaseV{ long v; public Data(long v){ this.v = v; } @Override public String toString(){ return "" +v; } } abstract class BaseV{ public int sz; public boolean fail; } class MyStack<T> extends MyList<T>{ public T pop(){ return remove(size() -1); } public T peek(){ return get(size() -1); } } class MyList<T> implements Iterable<T>{ private T[] arr; private int sz; public MyList(){ this(16); } public MyList(int n){ arr = Util.cast(new Object[n]); } public boolean isEmpty(){ return sz == 0; } public int size(){ return sz; } public T get(int i){ return arr[i]; } public void add(T t){ (arr = sz < arr.length ? arr : copyOf(arr,sz *5 >>2))[sz++] = t; } public T remove(int i){ var ret = arr[i]; sz--; for (int j = i;j < sz;j++) arr[j] = arr[j +1]; return ret; } public T removeFast(int i){ var ret = arr[i]; arr[i] = arr[--sz]; return ret; } public void sort(){ sort(Util.cast(Comparator.naturalOrder())); } public void sort(Comparator<T> cmp){ Arrays.sort(arr,0,sz,cmp); } @Override public Iterator<T> iterator(){ return new Iterator<>(){ int i = 0; @Override public boolean hasNext(){ return i < sz; } @Override public T next(){ return arr[i++]; } }; } public <U> MyList<U> map(Function<T, U> func){ MyList<U> ret = new MyList<>(sz); forEach(t -> ret.add(func.apply(t))); return ret; } public T[] toArray(){ return copyOf(arr,sz); } public void swap(int i,int j){ var t = arr[i]; arr[i] = arr[j]; arr[j] = t; } public void set(int i,T t){ arr[i] = t; } } class BaseSolver extends Util{ public MyReader in; public MyWriter out,log; public BaseSolver(MyReader in,MyWriter out,MyWriter log){ this.in = in; this.out = out; this.log = log; } protected long inv(long x){ return pow(x,mod -2); } protected long pow(long x,long n){ return pow(x,n,Util.mod); } protected long pow(long x,long n,long mod){ long ret = 1; for (x %= mod;0 < n;x = x *x %mod,n >>= 1) if ((n &1) == 1) ret = ret *x %mod; return ret; } protected int bSearchI(int o,int n,IntPredicate judge){ if (!judge.test(o)) return o -Integer.signum(n -o); for (int m = 0;1 < abs(n -o);) m = judge.test(m = o +n >>1) ? (o = m) : (n = m); return o; } protected long bSearchL(long o,long n,LongPredicate judge){ for (long m = 0;1 < abs(n -o);) m = judge.test(m = o +n >>1) ? (o = m) : (n = m); return o; } protected double bSearchD(double o,double n,DoublePredicate judge){ for (double m,c = 0;c < 100;c++) m = judge.test(m = (o +n) /2) ? (o = m) : (n = m); return o; } protected long gcd(long a,long b){ while (0 < b) { long t = a; a = b; b = t %b; } return a; } public long lcm(long a,long b){ return b /gcd(a,b) *a; } protected long ceil(long a,long b){ return (a +b -1) /b; } } class Util{ public static String yes = "Yes",no = "No"; public static int infI = (1 <<30) -1; public static long infL = (1L <<61 |1 <<30) -1, mod = 998244353; public static Random rd = ThreadLocalRandom.current(); private long st = System.currentTimeMillis(); protected long elapsed(){ return System.currentTimeMillis() -st; } protected void reset(){ st = System.currentTimeMillis(); } public static int[] arrI(int N,IntUnaryOperator f){ int[] ret = new int[N]; setAll(ret,f); return ret; } public static long[] arrL(int N,IntToLongFunction f){ long[] ret = new long[N]; setAll(ret,f); return ret; } public static double[] arrD(int N,IntToDoubleFunction f){ double[] ret = new double[N]; setAll(ret,f); return ret; } public static <T> T[] arr(T[] arr,IntFunction<T> f){ setAll(arr,f); return arr; } public int[][] addId(int[][] T){ return arr(new int[T.length][],i -> { int[] t = copyOf(T[i],T[i].length +1); t[t.length -1] = i; return t; }); } @SuppressWarnings("unchecked") public static <T> T cast(Object obj){ return (T) obj; } } class MyReader{ private byte[] buf = new byte[1 <<16]; private int ptr,tail; private InputStream in; public MyReader(InputStream in){ this.in = in; } private byte read(){ if (ptr == tail) try { tail = in.read(buf); ptr = 0; } catch (IOException e) {} return buf[ptr++]; } private boolean isPrintable(byte c){ return 32 < c && c < 127; } private byte nextPrintable(){ byte ret = read(); while (!isPrintable(ret)) ret = read(); return ret; } public int it(){ return toIntExact(lg()); } public int[] it(int N){ return Util.arrI(N,i -> it()); } public int[][] it(int H,int W){ return Util.arr(new int[H][],i -> it(W)); } public int idx(){ return it() -1; } public int[] idx(int N){ return Util.arrI(N,i -> idx()); } public int[][] idx(int H,int W){ return Util.arr(new int[H][],i -> idx(W)); } public long lg(){ byte i = nextPrintable(); boolean negative = i == 45; long n = negative ? 0 : i -'0'; while (isPrintable(i = read())) n = 10 *n +i -'0'; return negative ? -n : n; } public long[] lg(int N){ return Util.arrL(N,i -> lg()); } public long[][] lg(int H,int W){ return Util.arr(new long[H][],i -> lg(W)); } public double dbl(){ return Double.parseDouble(str()); } public double[] dbl(int N){ return Util.arrD(N,i -> dbl()); } public double[][] dbl(int H,int W){ return Util.arr(new double[H][],i -> dbl(W)); } public char[] ch(){ return str().toCharArray(); } public char[][] ch(int H){ return Util.arr(new char[H][],i -> ch()); } public String line(){ StringBuilder sb = new StringBuilder(); for (byte c;(c = read()) != '\n';) sb.append((char) c); return sb.toString(); } public String str(){ StringBuilder sb = new StringBuilder(); sb.append((char) nextPrintable()); for (byte c;isPrintable(c = read());) sb.append((char) c); return sb.toString(); } public String[] str(int N){ return Util.arr(new String[N],i -> str()); } } class MyWriter{ private OutputStream out; private byte[] buf = new byte[1 <<16],ibuf = new byte[20]; private int tail; private boolean autoflush; public MyWriter(OutputStream out,boolean autoflush){ this.out = out; this.autoflush = autoflush; } public void flush(){ try { out.write(buf,0,tail); tail = 0; } catch (IOException e) { e.printStackTrace(); } } private void ln(){ write((byte) '\n'); if (autoflush) flush(); } private void write(byte b){ buf[tail++] = b; if (tail == buf.length) flush(); } private void write(long n){ if (n < 0) { n = -n; write((byte) '-'); } int i = ibuf.length; do { ibuf[--i] = (byte) (n %10 +'0'); n /= 10; } while (n > 0); while (i < ibuf.length) write(ibuf[i++]); } private void print(Object obj){ if (obj instanceof Boolean) print((boolean) obj ? Util.yes : Util.no); else if (obj instanceof Integer) write((int) obj); else if (obj instanceof Long) write((long) obj); else if (obj instanceof char[]) for (char b:(char[]) obj) write((byte) b); else if (obj.getClass().isArray()) { int l = Array.getLength(obj); for (int i = 0;i < l;i++) { print(Array.get(obj,i)); if (i +1 < l) write((byte) ' '); } } else print(Objects.toString(obj).toCharArray()); } public void println(Object obj){ if (obj == null) obj = "null"; if (obj instanceof Iterable<?>) for (Object e:(Iterable<?>) obj) println(e); else if (obj.getClass().isArray() && Array.getLength(obj) > 0 && Array.get(obj,0).getClass().isArray()) { int l = Array.getLength(obj); for (int i = 0;i < l;i++) println(Array.get(obj,i)); } else { print(obj); ln(); } } public void printlns(Object... o){ print(o); ln(); } } class Main{ public static void main(String[] args) throws Exception{ var in = new MyReader(System.in); var out = new MyWriter(System.out,false); var log = new MyWriter(System.err,true); int T = Solver.multi ? in.it() : 1; while (T-- > 0) Optional.ofNullable(new Solver(in,out,log) .solve()).ifPresent(out::println); out.flush(); } }
ConDefects/ConDefects/Code/abc295_e/Java/52221082
condefects-java_data_646
// package Codeforce; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static Reader in = new Reader(); public static void main(String[] args) { // int t = in.nextInt(); // while (t-- > 0) { // solve(); // } solve(); out.close(); } static long MOD = 998244353; static int[][] dirs = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}}; static void solve() { int m = in.nextInt(); int n = in.nextInt(); int k = in.nextInt(); int sx = in.nextInt() - 1, sy = in.nextInt() - 1; long[][] grid = new long[m][n]; for (int i = 0; i < m; i++) { grid[i] = in.nextLongArray(n); } long ans = 0; queue.offer(new Node(sx, sy, 0, 0)); while (!queue.isEmpty()) { Node node = queue.poll(); int x = node.x, y = node.y; for (int[] d : dirs) { int nx = x + d[0], ny = y + d[1]; if (node.k == k) { continue; } if (nx >= 0 && nx < m && ny >= 0 && ny < n) { long cur = node.s + grid[nx][ny] * (k - node.k); if (cur > dp[nx][ny]) { dp[nx][ny] = cur; ans = Math.max(ans, cur); queue.offer(new Node(nx, ny, node.k + 1, node.s + grid[nx][ny])); } } } } out.println(ans); } static Deque<Node> queue = new ArrayDeque<>(); record Node(int x, int y, int k, long s) { } static long[][] dp = new long[1001][1001]; } class Reader { private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer st; boolean hasNext() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } } catch (Exception e) { return false; } return true; } String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } } catch (Exception ignored) { } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } long nextLong() { return java.lang.Long.parseLong(next()); } long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } String nextLine() { String s = ""; try { s = br.readLine(); } catch (Exception ignored) { } return s; } } // package Codeforce; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static Reader in = new Reader(); public static void main(String[] args) { // int t = in.nextInt(); // while (t-- > 0) { // solve(); // } solve(); out.close(); } static long MOD = 998244353; static int[][] dirs = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}}; static void solve() { int m = in.nextInt(); int n = in.nextInt(); int k = in.nextInt(); int sx = in.nextInt() - 1, sy = in.nextInt() - 1; long[][] grid = new long[m][n]; for (int i = 0; i < m; i++) { grid[i] = in.nextLongArray(n); } long ans = grid[sx][sy] * k; queue.offer(new Node(sx, sy, 0, 0)); while (!queue.isEmpty()) { Node node = queue.poll(); int x = node.x, y = node.y; for (int[] d : dirs) { int nx = x + d[0], ny = y + d[1]; if (node.k == k) { continue; } if (nx >= 0 && nx < m && ny >= 0 && ny < n) { long cur = node.s + grid[nx][ny] * (k - node.k); if (cur > dp[nx][ny]) { dp[nx][ny] = cur; ans = Math.max(ans, cur); queue.offer(new Node(nx, ny, node.k + 1, node.s + grid[nx][ny])); } } } } out.println(ans); } static Deque<Node> queue = new ArrayDeque<>(); record Node(int x, int y, int k, long s) { } static long[][] dp = new long[1001][1001]; } class Reader { private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer st; boolean hasNext() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } } catch (Exception e) { return false; } return true; } String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } } catch (Exception ignored) { } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } long nextLong() { return java.lang.Long.parseLong(next()); } long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } String nextLine() { String s = ""; try { s = br.readLine(); } catch (Exception ignored) { } return s; } }
ConDefects/ConDefects/Code/abc358_g/Java/54618156
condefects-java_data_647
import java.util.*; 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 k = sc.nextInt(); int sx = sc.nextInt(); sx -= 1; int sy = sc.nextInt(); sy -= 1; long res = 0; /* 尽可能在 k 步以内走到尽可能大的格子,如果步数还有剩余就一直停留在原地,容易想到在到达最大值的格子之前不会在路径上某个格子做停留,因为这样会更劣 记 dp[i][j][l] 表示到 (i,j) 为止已经走了l步时的最大愉悦值 */ int move = Math.min(k+1,h*w+1); long[][][] dp = new long[h][w][move]; for(int x = 0;x < move;x++) { for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { dp[i][j][x] = Long.MIN_VALUE; } } } dp[sx][sy][0] = 0; long[][] grid = new long[h][w]; for (int i = 0; i < h; i++) { for(int j = 0;j < w;j++) { grid[i][j] = sc.nextLong(); } } int[][] direction = {{1,0},{-1,0},{0,1},{0,-1}}; for(int x = 1;x < move;x++){ for(int i = 0; i < h;i++){ for(int j = 0;j < w;j++){ for(int m = 0; m < 4;m++){ int x1 = direction[m][0] + i; int y1 = direction[m][1] + j; if (x1 >= 0 && x1 < h && y1 >=0 && y1 < w){ dp[x1][y1][x] = Math.max(dp[x1][y1][x],dp[i][j][x-1] + grid[x1][y1]); } } } } } for(int i = 0; i < h;i++){ for(int j = 0;j < w;j++){ for(int x = 1;x < move;x++){ res = Math.max(res,dp[i][j][x]); int diff = k - x; if (diff > 0){ res = Math.max(res, dp[i][j][x] + (long) diff * grid[i][j]); } } } } // Arrays.sort(arr); System.out.println(res); sc.close(); } } import java.util.*; 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 k = sc.nextInt(); int sx = sc.nextInt(); sx -= 1; int sy = sc.nextInt(); sy -= 1; /* 尽可能在 k 步以内走到尽可能大的格子,如果步数还有剩余就一直停留在原地,容易想到在到达最大值的格子之前不会在路径上某个格子做停留,因为这样会更劣 记 dp[i][j][l] 表示到 (i,j) 为止已经走了l步时的最大愉悦值 */ int move = Math.min(k+1,h*w+1); long[][][] dp = new long[h][w][move]; for(int x = 0;x < move;x++) { for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { dp[i][j][x] = Long.MIN_VALUE; } } } dp[sx][sy][0] = 0; long[][] grid = new long[h][w]; for (int i = 0; i < h; i++) { for(int j = 0;j < w;j++) { grid[i][j] = sc.nextLong(); } } long res = grid[sx][sy] * k; int[][] direction = {{1,0},{-1,0},{0,1},{0,-1}}; for(int x = 1;x < move;x++){ for(int i = 0; i < h;i++){ for(int j = 0;j < w;j++){ for(int m = 0; m < 4;m++){ int x1 = direction[m][0] + i; int y1 = direction[m][1] + j; if (x1 >= 0 && x1 < h && y1 >=0 && y1 < w){ dp[x1][y1][x] = Math.max(dp[x1][y1][x],dp[i][j][x-1] + grid[x1][y1]); } } } } } for(int i = 0; i < h;i++){ for(int j = 0;j < w;j++){ for(int x = 1;x < move;x++){ res = Math.max(res,dp[i][j][x]); int diff = k - x; if (diff > 0){ res = Math.max(res, dp[i][j][x] + (long) diff * grid[i][j]); } } } } // Arrays.sort(arr); System.out.println(res); sc.close(); } }
ConDefects/ConDefects/Code/abc358_g/Java/54692260
condefects-java_data_648
import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.NoSuchElementException; public class Main { public static void main(String[] args) { Main o = new Main(); o.solve(); } public void solve() { FastScanner sc = new FastScanner(System.in); int N = sc.nextInt(); int M = sc.nextInt(); long[] B = new long[N]; long[] C = new long[M]; for (int i = 0; i < N; i++) { B[i] = -sc.nextLong(); } for (int i = 0; i < M; i++) { C[i] = sc.nextLong(); } Arrays.sort(B); for (int i = 0; i < N; i++) B[i] = -B[i]; Line[] line = new Line[N]; int li = 0; line[li++] = new Line(1, B[0]); for (int i = 1; i < N; i++) { Line l = new Line(i + 1, B[i]); int min = -1; int max = li; while ( max - min > 1 ) { int mid = (min + max) / 2; long c0 = l.intersection(line[mid]); if ( c0 < line[mid].c0 ) { max = mid; } else { min = mid; } } if ( max > 0 ) { l.c0 = l.intersection(line[max - 1]); } line[max] = l; li = max + 1; } StringBuilder ans = new StringBuilder(); for (int i = 0; i < M; i++) { int ii = search(line, li, C[i]); long a = (B[line[ii].k - 1] + C[i]) * line[ii].k; ans.append(a); ans.append(" "); } ans.deleteCharAt(ans.length() - 1); System.out.println(ans.toString()); } int search(Line[] line, int li, long c) { int min = 0; int max = li; while ( max - min > 1 ) { int mid = (min + max) / 2; if ( c >= line[mid].c0 ) { min = mid; } else { max = mid; } } return min; } class Line { int k = 0; long b = 0; long c0 = 0; Line(int k, long b) { this.k = k; this.b = b; } long intersection(Line o) { return (long)Math.ceil((o.b * o.k - b * k) / (k - o.k)); } long val(long c) { return (b + c) * k; } } class FastScanner { private final InputStream in; private final byte[] buf = new byte[1024]; private int ptr = 0; private int buflen = 0; FastScanner( InputStream source ) { this.in = source; } private boolean hasNextByte() { if ( ptr < buflen ) return true; else { ptr = 0; try { buflen = in.read(buf); } catch (IOException e) { e.printStackTrace(); } if ( buflen <= 0 ) return false; } return true; } private int readByte() { if ( hasNextByte() ) return buf[ptr++]; else return -1; } private boolean isPrintableChar( int c ) { return 33 <= c && c <= 126; } private boolean isNumeric( int c ) { return '0' <= c && c <= '9'; } private void skipToNextPrintableChar() { while ( hasNextByte() && !isPrintableChar(buf[ptr]) ) ptr++; } public boolean hasNext() { skipToNextPrintableChar(); return hasNextByte(); } public String next() { if ( !hasNext() ) throw new NoSuchElementException(); StringBuilder ret = new StringBuilder(); int b = readByte(); while ( isPrintableChar(b) ) { ret.appendCodePoint(b); b = readByte(); } return ret.toString(); } public long nextLong() { if ( !hasNext() ) throw new NoSuchElementException(); long ret = 0; int b = readByte(); boolean negative = false; if ( b == '-' ) { negative = true; if ( hasNextByte() ) b = readByte(); } if ( !isNumeric(b) ) throw new NumberFormatException(); while ( true ) { if ( isNumeric(b) ) ret = ret * 10 + b - '0'; else if ( b == -1 || !isPrintableChar(b) ) return negative ? -ret : ret; else throw new NumberFormatException(); b = readByte(); } } public int nextInt() { return (int)nextLong(); } public double nextDouble() { return Double.parseDouble(next()); } } } import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.NoSuchElementException; public class Main { public static void main(String[] args) { Main o = new Main(); o.solve(); } public void solve() { FastScanner sc = new FastScanner(System.in); int N = sc.nextInt(); int M = sc.nextInt(); long[] B = new long[N]; long[] C = new long[M]; for (int i = 0; i < N; i++) { B[i] = -sc.nextLong(); } for (int i = 0; i < M; i++) { C[i] = sc.nextLong(); } Arrays.sort(B); for (int i = 0; i < N; i++) B[i] = -B[i]; Line[] line = new Line[N]; int li = 0; line[li++] = new Line(1, B[0]); for (int i = 1; i < N; i++) { Line l = new Line(i + 1, B[i]); int min = -1; int max = li; while ( max - min > 1 ) { int mid = (min + max) / 2; long c0 = l.intersection(line[mid]); if ( c0 < line[mid].c0 ) { max = mid; } else { min = mid; } } if ( max > 0 ) { l.c0 = l.intersection(line[max - 1]); } line[max] = l; li = max + 1; } StringBuilder ans = new StringBuilder(); for (int i = 0; i < M; i++) { int ii = search(line, li, C[i]); long a = (B[line[ii].k - 1] + C[i]) * line[ii].k; ans.append(a); ans.append(" "); } ans.deleteCharAt(ans.length() - 1); System.out.println(ans.toString()); } int search(Line[] line, int li, long c) { int min = 0; int max = li; while ( max - min > 1 ) { int mid = (min + max) / 2; if ( c >= line[mid].c0 ) { min = mid; } else { max = mid; } } return min; } class Line { int k = 0; long b = 0; long c0 = 0; Line(int k, long b) { this.k = k; this.b = b; } long intersection(Line o) { return (long)Math.ceil((((double)o.b) * o.k - b * k) / (k - o.k)); } long val(long c) { return (b + c) * k; } } class FastScanner { private final InputStream in; private final byte[] buf = new byte[1024]; private int ptr = 0; private int buflen = 0; FastScanner( InputStream source ) { this.in = source; } private boolean hasNextByte() { if ( ptr < buflen ) return true; else { ptr = 0; try { buflen = in.read(buf); } catch (IOException e) { e.printStackTrace(); } if ( buflen <= 0 ) return false; } return true; } private int readByte() { if ( hasNextByte() ) return buf[ptr++]; else return -1; } private boolean isPrintableChar( int c ) { return 33 <= c && c <= 126; } private boolean isNumeric( int c ) { return '0' <= c && c <= '9'; } private void skipToNextPrintableChar() { while ( hasNextByte() && !isPrintableChar(buf[ptr]) ) ptr++; } public boolean hasNext() { skipToNextPrintableChar(); return hasNextByte(); } public String next() { if ( !hasNext() ) throw new NoSuchElementException(); StringBuilder ret = new StringBuilder(); int b = readByte(); while ( isPrintableChar(b) ) { ret.appendCodePoint(b); b = readByte(); } return ret.toString(); } public long nextLong() { if ( !hasNext() ) throw new NoSuchElementException(); long ret = 0; int b = readByte(); boolean negative = false; if ( b == '-' ) { negative = true; if ( hasNextByte() ) b = readByte(); } if ( !isNumeric(b) ) throw new NumberFormatException(); while ( true ) { if ( isNumeric(b) ) ret = ret * 10 + b - '0'; else if ( b == -1 || !isPrintableChar(b) ) return negative ? -ret : ret; else throw new NumberFormatException(); b = readByte(); } } public int nextInt() { return (int)nextLong(); } public double nextDouble() { return Double.parseDouble(next()); } } }
ConDefects/ConDefects/Code/abc289_g/Java/46032112
condefects-java_data_649
import java.util.Scanner; public class Main implements Runnable { public static void main(String[] args) { new Thread(null, new Main(), "", Runtime.getRuntime().maxMemory()).start(); } public long count(int r, int c) { long ret = (long) (r / N) * (c / N) * sums[N][N]; ret += (long) (r / N) * sums[N][c % N + 1]; ret += (long) (c / N) * sums[r % N + 1][N]; ret += sums[r % N + 1][c % N + 1]; return ret; } static int[][] sums; static int N; @Override public void run() { Scanner sc = new Scanner(System.in); N = sc.nextInt(); int Q = sc.nextInt(); char[][] table = new char[N][N]; for (int i = 0; i < N; i++) { String S = sc.next(); table[i] = S.toCharArray(); } sums = new int[N + 1][N + 1]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { sums[i][j] = sums[i][j - 1] + (table[i - 1][j - 1] == 'B' ? 1 : 0); } } for (int j = 1; j <= N; j++) { for (int i = 1; i <= N; i++) { sums[i][j] += sums[i - 1][j]; } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < Q; i++) { int A = sc.nextInt(); int B = sc.nextInt(); int C = sc.nextInt(); int D = sc.nextInt(); long ans = count(C + 1, D + 1); ans -= count(A, D + 1); ans -= count(C + 1, B); ans += count(A, B); sb.append(ans).append("\n"); } System.out.println(sb); } } import java.util.Scanner; public class Main implements Runnable { public static void main(String[] args) { new Thread(null, new Main(), "", Runtime.getRuntime().maxMemory()).start(); } public long count(int r, int c) { r--; c--; long ret = (long) (r / N) * (c / N) * sums[N][N]; ret += (long) (r / N) * sums[N][c % N + 1]; ret += (long) (c / N) * sums[r % N + 1][N]; ret += sums[r % N + 1][c % N + 1]; return ret; } static int[][] sums; static int N; @Override public void run() { Scanner sc = new Scanner(System.in); N = sc.nextInt(); int Q = sc.nextInt(); char[][] table = new char[N][N]; for (int i = 0; i < N; i++) { String S = sc.next(); table[i] = S.toCharArray(); } sums = new int[N + 1][N + 1]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { sums[i][j] = sums[i][j - 1] + (table[i - 1][j - 1] == 'B' ? 1 : 0); } } for (int j = 1; j <= N; j++) { for (int i = 1; i <= N; i++) { sums[i][j] += sums[i - 1][j]; } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < Q; i++) { int A = sc.nextInt(); int B = sc.nextInt(); int C = sc.nextInt(); int D = sc.nextInt(); long ans = count(C + 1, D + 1); ans -= count(A, D + 1); ans -= count(C + 1, B); ans += count(A, B); sb.append(ans).append("\n"); } System.out.println(sb); } }
ConDefects/ConDefects/Code/abc331_d/Java/48171356
condefects-java_data_650
//package atcoder.abc331; import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); //solve(in.nextInt()); solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; 6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial. If getting stuck, skip it and solve other similar level problems. Wait for 1 week then try to solve again. Only read editorial after you solved a problem. 7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already. 8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you rushed to coding! */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a thorough idea steps! 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? */ static int n, q; static char[][] p; static int[][] ps; static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { n = in.nextInt(); q = in.nextInt(); p = new char[n][]; for(int i = 0; i < n; i++) { p[i] = in.next().toCharArray(); } ps = new int[n][n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { ps[i][j] = (p[i][j] == 'B' ? 1 : 0) + (i > 0 ? ps[i - 1][j] : 0) + (j > 0 ? ps[i][j - 1] : 0) - (i > 0 && j > 0 ? ps[i - 1][j - 1] : 0); } } for(int i = 0; i < q; i++) { int a = in.nextInt(), b = in.nextInt(), c = in.nextInt(), d = in.nextInt(); long ans = compute(c, d) - compute(a - 1, d) - compute(c, b - 1) + compute(a - 1, b - 1); out.println(ans); } } out.close(); } static long compute(int x, int y) { if(x < 0 || y < 0) { return 0; } //first compute horizontally long base = ps[min(n - 1, x)][min(n - 1, y)]; int cnt1 = (y + 1) / n; int rem1 = (y + 1) % n; long perRow = base * cnt1 + (rem1 > 0 ? ps[min(n - 1, x)][rem1 - 1] : 0); long rowCnt = (x + 1) / n; int rem2 = (x + 1) % n; long sum = 0; if(rowCnt == 0) { sum = perRow; } else { sum = perRow * rowCnt; if(rem2 > 0) { sum += ps[rem2 - 1][min(n - 1, y)] * cnt1 + (rem1 > 0 ? ps[rem2 - 1][rem1 - 1] : 0); } } return sum; } static long addWithMod(long x, long y, long mod) { return (x + y) % mod; } static long subtractWithMod(long x, long y, long mod) { return ((x - y) % mod + mod) % mod; } static long multiplyWithMod(long x, long y, long mod) { x %= mod; y %= mod; return x * y % mod; } static long modInv(long x, long mod) { return fastPowMod(x, mod - 2, mod); } static long fastPowMod(long x, long n, long mod) { if (n == 0) return 1; long half = fastPowMod(x, n / 2, mod); if (n % 2 == 0) return half * half % mod; return half * half % mod * x % mod; } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("input.in")); out = new PrintWriter(new FileOutputStream("output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) g[i] = next(); return g; } List<Integer>[] readUnWeightedGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphOneIndexed(int n, int m) { List<int[]>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } List<Integer>[] readUnWeightedGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphZeroIndexed(int n, int m) { List<int[]>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building an undirected weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildUndirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]][0] = end2[i]; adj[end1[i]][idxForEachNode[end1[i]]][1] = weight[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]][0] = end1[i]; adj[end2[i]][idxForEachNode[end2[i]]][1] = weight[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } /* A more efficient way of building a directed weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildDirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]][0] = to[i]; adj[from[i]][idxForEachNode[from[i]]][1] = weight[i]; idxForEachNode[from[i]]++; } return adj; } } } //package atcoder.abc331; import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); //solve(in.nextInt()); solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; 6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial. If getting stuck, skip it and solve other similar level problems. Wait for 1 week then try to solve again. Only read editorial after you solved a problem. 7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already. 8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you rushed to coding! */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a thorough idea steps! 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? */ static int n, q; static char[][] p; static int[][] ps; static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { n = in.nextInt(); q = in.nextInt(); p = new char[n][]; for(int i = 0; i < n; i++) { p[i] = in.next().toCharArray(); } ps = new int[n][n]; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { ps[i][j] = (p[i][j] == 'B' ? 1 : 0) + (i > 0 ? ps[i - 1][j] : 0) + (j > 0 ? ps[i][j - 1] : 0) - (i > 0 && j > 0 ? ps[i - 1][j - 1] : 0); } } for(int i = 0; i < q; i++) { int a = in.nextInt(), b = in.nextInt(), c = in.nextInt(), d = in.nextInt(); long ans = compute(c, d) - compute(a - 1, d) - compute(c, b - 1) + compute(a - 1, b - 1); out.println(ans); } } out.close(); } static long compute(int x, int y) { if(x < 0 || y < 0) { return 0; } //first compute horizontally long base = ps[min(n - 1, x)][min(n - 1, y)]; int cnt1 = (y + 1) / n; int rem1 = (y + 1) % n; long perRow = base * cnt1 + (rem1 > 0 ? ps[min(n - 1, x)][rem1 - 1] : 0); long rowCnt = (x + 1) / n; int rem2 = (x + 1) % n; long sum = 0; if(rowCnt == 0) { sum = perRow; } else { sum = perRow * rowCnt; if(rem2 > 0) { sum += 1l * ps[rem2 - 1][min(n - 1, y)] * cnt1 + (rem1 > 0 ? ps[rem2 - 1][rem1 - 1] : 0); } } return sum; } static long addWithMod(long x, long y, long mod) { return (x + y) % mod; } static long subtractWithMod(long x, long y, long mod) { return ((x - y) % mod + mod) % mod; } static long multiplyWithMod(long x, long y, long mod) { x %= mod; y %= mod; return x * y % mod; } static long modInv(long x, long mod) { return fastPowMod(x, mod - 2, mod); } static long fastPowMod(long x, long n, long mod) { if (n == 0) return 1; long half = fastPowMod(x, n / 2, mod); if (n % 2 == 0) return half * half % mod; return half * half % mod * x % mod; } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("input.in")); out = new PrintWriter(new FileOutputStream("output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) g[i] = next(); return g; } List<Integer>[] readUnWeightedGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphOneIndexed(int n, int m) { List<int[]>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } List<Integer>[] readUnWeightedGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphZeroIndexed(int n, int m) { List<int[]>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building an undirected weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildUndirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]][0] = end2[i]; adj[end1[i]][idxForEachNode[end1[i]]][1] = weight[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]][0] = end1[i]; adj[end2[i]][idxForEachNode[end2[i]]][1] = weight[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } /* A more efficient way of building a directed weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildDirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]][0] = to[i]; adj[from[i]][idxForEachNode[from[i]]][1] = weight[i]; idxForEachNode[from[i]]++; } return adj; } } }
ConDefects/ConDefects/Code/abc331_d/Java/48155601
condefects-java_data_651
import java.io.*; public class Main { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); static StreamTokenizer stmInput = new StreamTokenizer(br); static int N = 1010; static long s[][] = new long[N][N]; static int n, m; public static String readString() throws IOException{ stmInput.nextToken(); return stmInput.sval; } public static int readInt() throws IOException { stmInput.nextToken(); return (int) stmInput.nval; } public static long f(int c, int d){ long ans = 0; ans = (c / n) * (d / n) * s[n][n] + (d / n) * s[c % n][n] + (c / n) * s[n][d % n] + s[c % n][d % n]; return ans; } public static void solve() throws IOException{ n = readInt(); m = readInt(); for(int i = 1; i <= n; i++){ String str = readString(); for(int j = 1; j <= n; j++){ if (str.charAt(j - 1) == 'B') s[i][j] = 1; } } for(int i = 1; i <= n; i++){ for (int j = 1; j <= n; j++){ s[i][j] += s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1]; } } while(m-- != 0){ int a = readInt() + 1, b = readInt() + 1, c = readInt() + 1, d = readInt() + 1; pw.println(f(c, d) - f(c, b - 1) - f(a - 1, d) + f(a - 1, b - 1)); } } public static void main(String[] args) throws IOException { // 按照ascii码范围设置为普通字符 stmInput.ordinaryChars('A', 'Z'); stmInput.wordChars('A', 'Z'); // 处理多组测试数据 // while(stmInput.nextToken() != StreamTokenizer.TT_EOF){ // n = (int) stmInput.nval; // m = readInt(); // solve(); // } int T = 1; while(T-- != 0){ solve(); } pw.flush(); pw.close(); br.close(); } } import java.io.*; public class Main { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); static StreamTokenizer stmInput = new StreamTokenizer(br); static int N = 1010; static long s[][] = new long[N][N]; static int n, m; public static String readString() throws IOException{ stmInput.nextToken(); return stmInput.sval; } public static int readInt() throws IOException { stmInput.nextToken(); return (int) stmInput.nval; } public static long f(int c, int d){ long ans = 0; ans = ((long)c / n) * (d / n) * s[n][n] + (d / n) * s[c % n][n] + (c / n) * s[n][d % n] + s[c % n][d % n]; return ans; } public static void solve() throws IOException{ n = readInt(); m = readInt(); for(int i = 1; i <= n; i++){ String str = readString(); for(int j = 1; j <= n; j++){ if (str.charAt(j - 1) == 'B') s[i][j] = 1; } } for(int i = 1; i <= n; i++){ for (int j = 1; j <= n; j++){ s[i][j] += s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1]; } } while(m-- != 0){ int a = readInt() + 1, b = readInt() + 1, c = readInt() + 1, d = readInt() + 1; pw.println(f(c, d) - f(c, b - 1) - f(a - 1, d) + f(a - 1, b - 1)); } } public static void main(String[] args) throws IOException { // 按照ascii码范围设置为普通字符 stmInput.ordinaryChars('A', 'Z'); stmInput.wordChars('A', 'Z'); // 处理多组测试数据 // while(stmInput.nextToken() != StreamTokenizer.TT_EOF){ // n = (int) stmInput.nval; // m = readInt(); // solve(); // } int T = 1; while(T-- != 0){ solve(); } pw.flush(); pw.close(); br.close(); } }
ConDefects/ConDefects/Code/abc331_d/Java/48172812
condefects-java_data_652
import java.util.*; class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n =scanner.nextInt(); int K =scanner.nextInt(); int[]a=new int[n]; int[]b=new int[n]; for(int i=0;i<n;i++){ a[i]=scanner.nextInt(); } for(int i=0;i<n;i++){ b[i]=scanner.nextInt(); } int[]dp=new int[n+1]; int[]ep=new int[n+1]; dp[1]=1; ep[1]=1; for(int i=2;i<=n;i++){ if(dp[i-1]==1 && Math.abs(a[i-1] - a[i-2]) <= K){ dp[i]=1; } if(ep[i-1]==1 && Math.abs(b[i-1] - a[i-2]) <= K){ dp[i]=1; } if(dp[i-1]==1 && Math.abs(b[i-1] - a[i-2]) <= K){ ep[i]=1; } if(ep[i-1]==1 && Math.abs(b[i-1] - b[i-2]) <= K){ ep[i]=1; } } if(dp[n]==1 || ep[n]==1){ System.out.println("Yes"); } else{ System.out.println("No"); } } } import java.util.*; class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n =scanner.nextInt(); int K =scanner.nextInt(); int[]a=new int[n]; int[]b=new int[n]; for(int i=0;i<n;i++){ a[i]=scanner.nextInt(); } for(int i=0;i<n;i++){ b[i]=scanner.nextInt(); } int[]dp=new int[n+1]; int[]ep=new int[n+1]; dp[1]=1; ep[1]=1; for(int i=2;i<=n;i++){ if(dp[i-1]==1 && Math.abs(a[i-1] - a[i-2]) <= K){ dp[i]=1; } if(ep[i-1]==1 && Math.abs(a[i-1] - b[i-2]) <= K){ dp[i]=1; } if(dp[i-1]==1 && Math.abs(b[i-1] - a[i-2]) <= K){ ep[i]=1; } if(ep[i-1]==1 && Math.abs(b[i-1] - b[i-2]) <= K){ ep[i]=1; } } if(dp[n]==1 || ep[n]==1){ System.out.println("Yes"); } else{ System.out.println("No"); } } }
ConDefects/ConDefects/Code/abc245_c/Java/41927847
condefects-java_data_653
import java.util.*; import java.io.*; import static java.lang.System.out; public class Main { static long mod = 998244353; public static void main(String[] args){ ContestScanner sc = new ContestScanner(); int n = sc.nextInt(); long k = sc.nextLong(); long a[] = sc.nextLongArray(n); long b[] = sc.nextLongArray(n); long c1 = a[0]; long c2 = b[0]; for(int i = 1;i < n;i++){ boolean d1 = false; boolean d2 = false; if(c1 != 0){ if(Math.abs(c1 - a[i]) <= k)d1 = true; if(Math.abs(c1 - b[i]) <= k)d2 = true; } if(c2 != 0){ if(Math.abs(c2 - b[i]) <= k)d1 = true; if(Math.abs(c2 - b[i]) <= k)d2 = true; } if(d1)c1 = a[i]; else c1 = 0; if(d2)c2 = b[i]; else c2 = 0; } if(c1 == 0 && c2 == 0){ out.println("No"); } else{ out.println("Yes"); } } } class ContestScanner { private final java.io.InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public ContestScanner(java.io.InputStream in){ this.in = in; } public ContestScanner(java.io.File file) throws java.io.FileNotFoundException { this(new java.io.BufferedInputStream(new java.io.FileInputStream(file))); } public ContestScanner(){ this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (java.io.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 java.util.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 java.util.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') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit) ); } n = n * 10 + digit; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(int length){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = this.nextInt(); return array; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width){ long[][] mat = new long[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width){ int[][] mat = new int[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width){ double[][] mat = new double[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width){ char[][] mat = new char[height][width]; for(int h=0; h<height; h++){ String s = this.next(); for(int w=0; w<width; w++){ mat[h][w] = s.charAt(w); } } return mat; } } import java.util.*; import java.io.*; import static java.lang.System.out; public class Main { static long mod = 998244353; public static void main(String[] args){ ContestScanner sc = new ContestScanner(); int n = sc.nextInt(); long k = sc.nextLong(); long a[] = sc.nextLongArray(n); long b[] = sc.nextLongArray(n); long c1 = a[0]; long c2 = b[0]; for(int i = 1;i < n;i++){ boolean d1 = false; boolean d2 = false; if(c1 != 0){ if(Math.abs(c1 - a[i]) <= k)d1 = true; if(Math.abs(c1 - b[i]) <= k)d2 = true; } if(c2 != 0){ if(Math.abs(c2 - a[i]) <= k)d1 = true; if(Math.abs(c2 - b[i]) <= k)d2 = true; } if(d1)c1 = a[i]; else c1 = 0; if(d2)c2 = b[i]; else c2 = 0; } if(c1 == 0 && c2 == 0){ out.println("No"); } else{ out.println("Yes"); } } } class ContestScanner { private final java.io.InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public ContestScanner(java.io.InputStream in){ this.in = in; } public ContestScanner(java.io.File file) throws java.io.FileNotFoundException { this(new java.io.BufferedInputStream(new java.io.FileInputStream(file))); } public ContestScanner(){ this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (java.io.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 java.util.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 java.util.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') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit) ); } n = n * 10 + digit; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(int length){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = this.nextInt(); return array; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width){ long[][] mat = new long[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width){ int[][] mat = new int[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width){ double[][] mat = new double[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width){ char[][] mat = new char[height][width]; for(int h=0; h<height; h++){ String s = this.next(); for(int w=0; w<width; w++){ mat[h][w] = s.charAt(w); } } return mat; } }
ConDefects/ConDefects/Code/abc245_c/Java/35857346
condefects-java_data_654
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int[][] arr = new int[n][2]; for (int i = 0; i < 1; i++) { for (int j = 0; j < n; j++) { arr[j][i] = sc.nextInt(); } } boolean[][] dp = new boolean[n][2]; dp[0][0] = true; dp[0][1] = true; for (int i = 1; i < n; i++) { dp[i][0] = dp[i-1][0] && Math.abs(arr[i][0] - arr[i-1][0]) <= k || dp[i-1][1] && Math.abs(arr[i][0] - arr[i-1][1]) <= k; dp[i][1] = dp[i-1][0] && Math.abs(arr[i][1] - arr[i-1][0]) <= k || dp[i-1][1] && Math.abs(arr[i][1] - arr[i-1][1]) <= k; } if(dp[n-1][0] || dp[n-1][1]) System.out.println("Yes"); else System.out.println("No"); } } import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int[][] arr = new int[n][2]; for (int i = 0; i < 2; i++) { for (int j = 0; j < n; j++) { arr[j][i] = sc.nextInt(); } } boolean[][] dp = new boolean[n][2]; dp[0][0] = true; dp[0][1] = true; for (int i = 1; i < n; i++) { dp[i][0] = dp[i-1][0] && Math.abs(arr[i][0] - arr[i-1][0]) <= k || dp[i-1][1] && Math.abs(arr[i][0] - arr[i-1][1]) <= k; dp[i][1] = dp[i-1][0] && Math.abs(arr[i][1] - arr[i-1][0]) <= k || dp[i-1][1] && Math.abs(arr[i][1] - arr[i-1][1]) <= k; } if(dp[n-1][0] || dp[n-1][1]) System.out.println("Yes"); else System.out.println("No"); } }
ConDefects/ConDefects/Code/abc245_c/Java/42091640
condefects-java_data_655
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] sa = br.readLine().split(" "); int n = Integer.parseInt(sa[0]); long m = Long.parseLong(sa[1]); br.close(); int[] a = new int[n]; Set<Integer> set = new HashSet<>(); set.add(0); int x = 1; int next = 1; int cnt = 0; for (int i = 1; i < n; i++) { while (true) { boolean flg = true; for (int j = i - 1; j >= 0; j--) { int val = a[j] - (x - a[j]); if (val < 0) { break; } if (set.contains(val)) { flg = false; break; } } if (flg) { a[i] = x; set.add(a[i]); break; } x++; } cnt++; if (cnt == next) { x *= 2; cnt = 0; next *= 2; } } long sum = 0; for (int i = 0; i < n; i++) { sum += a[i]; } // System.out.println(Arrays.toString(a)); // System.out.println(sum); long g = m - x * 4; long g2 = (g - sum + n - 1) / n; long sum2 = 0; for (int i = 0; i < n; i++) { a[i] -= g2; sum2 += a[i]; } long add = m - sum2; a[n - 1] += add; StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.append(a[i]).append(' '); } sb.deleteCharAt(sb.length() - 1); System.out.println(sb.toString()); } } import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] sa = br.readLine().split(" "); int n = Integer.parseInt(sa[0]); long m = Long.parseLong(sa[1]); br.close(); int[] a = new int[n]; Set<Integer> set = new HashSet<>(); set.add(0); int x = 1; int next = 1; int cnt = 0; for (int i = 1; i < n; i++) { while (true) { boolean flg = true; for (int j = i - 1; j >= 0; j--) { int val = a[j] - (x - a[j]); if (val < 0) { break; } if (set.contains(val)) { flg = false; break; } } if (flg) { a[i] = x; set.add(a[i]); break; } x++; } cnt++; if (cnt == next) { x *= 2; cnt = 0; next *= 2; } } long sum = 0; for (int i = 0; i < n; i++) { sum += a[i]; } // System.out.println(Arrays.toString(a)); // System.out.println(sum); long g = m - x * 4; long g2 = (g - sum + n - 1) / n; long sum2 = 0; for (int i = 0; i < n; i++) { a[i] += g2; sum2 += a[i]; } long add = m - sum2; a[n - 1] += add; StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.append(a[i]).append(' '); } sb.deleteCharAt(sb.length() - 1); System.out.println(sb.toString()); } }
ConDefects/ConDefects/Code/arc145_d/Java/33635775
condefects-java_data_656
import java.io.*; import java.util.*; public class Main { public static int INF = 0x3f3f3f3f, mod = 1000000007, mod9 = 998244353; public static void main(String args[]){ try { PrintWriter o = new PrintWriter(System.out); boolean multiTest = false; // init if(multiTest) { int t = fReader.nextInt(), loop = 0; while (loop < t) {loop++;solve(o);} } else solve(o); o.close(); } catch (Exception e) {e.printStackTrace();} } static int[] a; static int[] u; static int[] f; static void solve(PrintWriter o) { try { int n = fReader.nextInt(), q = fReader.nextInt(); a = new int[n+1]; u = new int[n+1]; f = new int[4*n]; for(int i=1;i<=n;i++) { a[i] = fReader.nextInt(); u[a[i]]++; } buildTree(1, 0, n); for(int i=0;i<q;i++) { int x = fReader.nextInt(), y = fReader.nextInt(); if(a[x] <= n) update(1, 0, n, a[x], -1); a[x] = y; if(a[x] <= n) update(1, 0, n, a[x], 1); o.println(f[1]); } } catch (Exception e) { e.printStackTrace(); } } static void buildTree(int k, int l, int r) { if(l == r) { if(u[l] > 0) f[k] = 1; else f[k] = 0; return; } int m = (l+r)>>1; buildTree(2*k, l, m); buildTree(2*k+1, m+1, r); pushUp(k, l, r); } static void update(int k, int l, int r, int x, int y) { if(l == r) { u[l] += y; if(u[l] > 0) f[k] = 1; else f[k] = 0; return; } int m = (l+r)>>1; if(x <= m) update(2*k, l, m, x, y); else update(2*k+1, m+1, r, x, y); pushUp(k, l, r); } static void pushUp(int k, int l, int r) { int m = (l+r)>>1; if(f[2*k] < (m-l+1)) f[k] = f[2*k]; else f[k] = f[2*k] + f[2*k+1]; } public static int upper_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) <= val) l = mid + 1; else r = mid; } return l; } public static int lower_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) < val) l = mid + 1; else r = mid; } return l; } public static long gcd(long a, long b){ return b == 0 ? a : gcd(b, a%b); } public static long lcm(long a, long b){ return a / gcd(a,b)*b; } public static long qpow(long a, long n, int md){ a %= md; long ret = 1l; while(n > 0){ if((n & 1) == 1){ ret = ret * a % md; } n >>= 1; a = a * a % md; } return ret; } public static class FenWick { int n; long[] a; long[] tree; public FenWick(int n){ this.n = n; a = new long[n+1]; tree = new long[n+1]; } private void add(int x, long val){ while(x <= n){ tree[x] += val; x += x&-x; } } private void addMx(int x, long val) { a[x] += val; tree[x] = a[x]; while(x <= n) { for(int i=1;i<(x&-x);i<<=1) { tree[x] = Math.max(tree[x], tree[x-i]); } x += x&-x; } } private long query(int x){ long ret = 0l; while(x > 0){ ret += tree[x]; x -= x&-x; } return ret; } private long queryMx(int l, int r) { long res = 0l; while(l <= r) { if(r-(r&-r) >= l) { res = Math.max(res, tree[r]); r -= r&-r; } else { res = Math.max(res, a[r]); r--; } } return res; } } public static class Pair{ Integer c1; String str; public Pair(Integer c1, String str) { this.c1 = c1; this.str = str; } @Override public int hashCode() { int prime = 31, ret = 1; ret = ret*prime + c1.hashCode(); return ret; } @Override public boolean equals(Object obj) { if(obj instanceof Pair) { return c1.equals(((Pair) obj).c1); } return false; } } public static class fReader { private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tokenizer = new StringTokenizer(""); private static String next() throws IOException{ while(!tokenizer.hasMoreTokens()){tokenizer = new StringTokenizer(reader.readLine());} return tokenizer.nextToken(); } public static int nextInt() throws IOException {return Integer.parseInt(next());} public static Long nextLong() throws IOException {return Long.parseLong(next());} public static double nextDouble() throws IOException {return Double.parseDouble(next());} public static char nextChar() throws IOException {return next().toCharArray()[0];} public static String nextString() throws IOException {return next();} public static String nextLine() throws IOException {return reader.readLine();} } } import java.io.*; import java.util.*; public class Main { public static int INF = 0x3f3f3f3f, mod = 1000000007, mod9 = 998244353; public static void main(String args[]){ try { PrintWriter o = new PrintWriter(System.out); boolean multiTest = false; // init if(multiTest) { int t = fReader.nextInt(), loop = 0; while (loop < t) {loop++;solve(o);} } else solve(o); o.close(); } catch (Exception e) {e.printStackTrace();} } static int[] a; static int[] u; static int[] f; static void solve(PrintWriter o) { try { int n = fReader.nextInt(), q = fReader.nextInt(); a = new int[n+1]; u = new int[n+1]; f = new int[4*n]; for(int i=1;i<=n;i++) { a[i] = fReader.nextInt(); if(a[i] <= n) u[a[i]]++; } buildTree(1, 0, n); for(int i=0;i<q;i++) { int x = fReader.nextInt(), y = fReader.nextInt(); if(a[x] <= n) update(1, 0, n, a[x], -1); a[x] = y; if(a[x] <= n) update(1, 0, n, a[x], 1); o.println(f[1]); } } catch (Exception e) { e.printStackTrace(); } } static void buildTree(int k, int l, int r) { if(l == r) { if(u[l] > 0) f[k] = 1; else f[k] = 0; return; } int m = (l+r)>>1; buildTree(2*k, l, m); buildTree(2*k+1, m+1, r); pushUp(k, l, r); } static void update(int k, int l, int r, int x, int y) { if(l == r) { u[l] += y; if(u[l] > 0) f[k] = 1; else f[k] = 0; return; } int m = (l+r)>>1; if(x <= m) update(2*k, l, m, x, y); else update(2*k+1, m+1, r, x, y); pushUp(k, l, r); } static void pushUp(int k, int l, int r) { int m = (l+r)>>1; if(f[2*k] < (m-l+1)) f[k] = f[2*k]; else f[k] = f[2*k] + f[2*k+1]; } public static int upper_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) <= val) l = mid + 1; else r = mid; } return l; } public static int lower_bound(List<Integer> a, int val){ int l = 0, r = a.size(); while(l < r){ int mid = l + (r - l) / 2; if(a.get(mid) < val) l = mid + 1; else r = mid; } return l; } public static long gcd(long a, long b){ return b == 0 ? a : gcd(b, a%b); } public static long lcm(long a, long b){ return a / gcd(a,b)*b; } public static long qpow(long a, long n, int md){ a %= md; long ret = 1l; while(n > 0){ if((n & 1) == 1){ ret = ret * a % md; } n >>= 1; a = a * a % md; } return ret; } public static class FenWick { int n; long[] a; long[] tree; public FenWick(int n){ this.n = n; a = new long[n+1]; tree = new long[n+1]; } private void add(int x, long val){ while(x <= n){ tree[x] += val; x += x&-x; } } private void addMx(int x, long val) { a[x] += val; tree[x] = a[x]; while(x <= n) { for(int i=1;i<(x&-x);i<<=1) { tree[x] = Math.max(tree[x], tree[x-i]); } x += x&-x; } } private long query(int x){ long ret = 0l; while(x > 0){ ret += tree[x]; x -= x&-x; } return ret; } private long queryMx(int l, int r) { long res = 0l; while(l <= r) { if(r-(r&-r) >= l) { res = Math.max(res, tree[r]); r -= r&-r; } else { res = Math.max(res, a[r]); r--; } } return res; } } public static class Pair{ Integer c1; String str; public Pair(Integer c1, String str) { this.c1 = c1; this.str = str; } @Override public int hashCode() { int prime = 31, ret = 1; ret = ret*prime + c1.hashCode(); return ret; } @Override public boolean equals(Object obj) { if(obj instanceof Pair) { return c1.equals(((Pair) obj).c1); } return false; } } public static class fReader { private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer tokenizer = new StringTokenizer(""); private static String next() throws IOException{ while(!tokenizer.hasMoreTokens()){tokenizer = new StringTokenizer(reader.readLine());} return tokenizer.nextToken(); } public static int nextInt() throws IOException {return Integer.parseInt(next());} public static Long nextLong() throws IOException {return Long.parseLong(next());} public static double nextDouble() throws IOException {return Double.parseDouble(next());} public static char nextChar() throws IOException {return next().toCharArray()[0];} public static String nextString() throws IOException {return next();} public static String nextLine() throws IOException {return reader.readLine();} } }
ConDefects/ConDefects/Code/abc330_e/Java/48656315
condefects-java_data_657
//package atcoder.abc255; import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); //solve(in.nextInt()); solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; 6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial. If getting stuck, skip it and solve other similar level problems. Wait for 1 week then try to solve again. Only read editorial after you solved a problem. 7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already. 8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you rushed to coding! */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a thorough idea steps! 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? */ static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { int n = in.nextInt(), q = in.nextInt(); Integer[] a = in.nextIntArray(n); Arrays.sort(a); int[][] qq = new int[q][2]; for(int i = 0; i < q; i++) { qq[i][0] = in.nextInt(); qq[i][1] = i; } long[] ans = new long[q]; long sum = 0; for(int x : a) sum += x; Arrays.sort(qq, Comparator.comparingInt(e->e[0])); int idx = 0, smaller = 0; long smallerSum = 0; for(int[] b : qq) { while(idx < n && a[idx] < b[0]) { smallerSum += a[idx]; idx++; smaller++; } ans[b[1]] = 1l * smaller * b[0] - smallerSum + sum - smallerSum - (n - smaller) * b[0]; } for(long v : ans) { out.println(v); } } out.close(); } static long addWithMod(long x, long y, long mod) { return (x + y) % mod; } static long subtractWithMod(long x, long y, long mod) { return ((x - y) % mod + mod) % mod; } static long multiplyWithMod(long x, long y, long mod) { return x * y % mod; } static long modInv(long x, long mod) { return fastPowMod(x, mod - 2, mod); } static long fastPowMod(long x, long n, long mod) { if (n == 0) { return 1; } long half = fastPowMod(x, n / 2, mod); if (n % 2 == 0) { return half * half % mod; } return half * half % mod * x % mod; } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("src/input.in")); out = new PrintWriter(new FileOutputStream("src/output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = nextInt(); } return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) { a[i] = nextLong(); } return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) { g[i] = next(); } return g; } List<Integer>[] readUnWeightedGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphOneIndexed(int n, int m) { List<int[]>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } List<Integer>[] readUnWeightedGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphZeroIndexed(int n, int m) { List<int[]>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building an undirected weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildUndirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]][0] = end2[i]; adj[end1[i]][idxForEachNode[end1[i]]][1] = weight[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]][0] = end1[i]; adj[end2[i]][idxForEachNode[end2[i]]][1] = weight[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } /* A more efficient way of building a directed weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildDirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]][0] = to[i]; adj[from[i]][idxForEachNode[from[i]]][1] = weight[i]; idxForEachNode[from[i]]++; } return adj; } } } //package atcoder.abc255; import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); //solve(in.nextInt()); solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; 6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial. If getting stuck, skip it and solve other similar level problems. Wait for 1 week then try to solve again. Only read editorial after you solved a problem. 7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already. 8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you rushed to coding! */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a thorough idea steps! 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? */ static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { int n = in.nextInt(), q = in.nextInt(); Integer[] a = in.nextIntArray(n); Arrays.sort(a); int[][] qq = new int[q][2]; for(int i = 0; i < q; i++) { qq[i][0] = in.nextInt(); qq[i][1] = i; } long[] ans = new long[q]; long sum = 0; for(int x : a) sum += x; Arrays.sort(qq, Comparator.comparingInt(e->e[0])); int idx = 0, smaller = 0; long smallerSum = 0; for(int[] b : qq) { while(idx < n && a[idx] < b[0]) { smallerSum += a[idx]; idx++; smaller++; } ans[b[1]] = 1l * smaller * b[0] - smallerSum + sum - smallerSum - 1l * (n - smaller) * b[0]; } for(long v : ans) { out.println(v); } } out.close(); } static long addWithMod(long x, long y, long mod) { return (x + y) % mod; } static long subtractWithMod(long x, long y, long mod) { return ((x - y) % mod + mod) % mod; } static long multiplyWithMod(long x, long y, long mod) { return x * y % mod; } static long modInv(long x, long mod) { return fastPowMod(x, mod - 2, mod); } static long fastPowMod(long x, long n, long mod) { if (n == 0) { return 1; } long half = fastPowMod(x, n / 2, mod); if (n % 2 == 0) { return half * half % mod; } return half * half % mod * x % mod; } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("src/input.in")); out = new PrintWriter(new FileOutputStream("src/output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = nextInt(); } return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) { a[i] = nextLong(); } return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) { g[i] = next(); } return g; } List<Integer>[] readUnWeightedGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphOneIndexed(int n, int m) { List<int[]>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } List<Integer>[] readUnWeightedGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphZeroIndexed(int n, int m) { List<int[]>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building an undirected weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildUndirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]][0] = end2[i]; adj[end1[i]][idxForEachNode[end1[i]]][1] = weight[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]][0] = end1[i]; adj[end2[i]][idxForEachNode[end2[i]]][1] = weight[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } /* A more efficient way of building a directed weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildDirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]][0] = to[i]; adj[from[i]][idxForEachNode[from[i]]][1] = weight[i]; idxForEachNode[from[i]]++; } return adj; } } }
ConDefects/ConDefects/Code/abc255_d/Java/39997860
condefects-java_data_658
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); final int N = sc.nextInt(); final int Q = sc.nextInt(); ArrayList<Long> A = new ArrayList<Long>(N); ArrayList<Long> partialSumA = new ArrayList<Long>(N); Long X; int idx; long ans; for(int i=0;i<N;i++){ A.add(Long.parseLong(sc.next())); } Collections.sort(A); partialSumA.add(A.get(0)); for(int i=1; i<N; i++){ partialSumA.add(partialSumA.get(i-1) + A.get(i)); } // System.out.println(A.toString()); // System.out.println(partialSumA.toString()); for(int j=0;j<Q;j++){ X = Long.parseLong(sc.next()); idx = Collections.binarySearch(A, X); idx = (idx >= 0) ? idx : ~idx -1; if(idx == -1){ ans = partialSumA.get(N-1); } else if(idx == N){ ans = X*N - partialSumA.get(N-1); } else{ ans = (partialSumA.get(N-1) - partialSumA.get(idx)) - X*(N-idx-1) + ( X*(idx+1) - partialSumA.get(idx)); } System.out.println(ans); } } } import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); final int N = sc.nextInt(); final int Q = sc.nextInt(); ArrayList<Long> A = new ArrayList<Long>(N); ArrayList<Long> partialSumA = new ArrayList<Long>(N); Long X; int idx; long ans; for(int i=0;i<N;i++){ A.add(Long.parseLong(sc.next())); } Collections.sort(A); partialSumA.add(A.get(0)); for(int i=1; i<N; i++){ partialSumA.add(partialSumA.get(i-1) + A.get(i)); } // System.out.println(A.toString()); // System.out.println(partialSumA.toString()); for(int j=0;j<Q;j++){ X = Long.parseLong(sc.next()); idx = Collections.binarySearch(A, X); idx = (idx >= 0) ? idx : ~idx -1; if(idx == -1){ ans = partialSumA.get(N-1)-X*N; } else if(idx == N){ ans = X*N - partialSumA.get(N-1); } else{ ans = (partialSumA.get(N-1) - partialSumA.get(idx)) - X*(N-idx-1) + ( X*(idx+1) - partialSumA.get(idx)); } System.out.println(ans); } } }
ConDefects/ConDefects/Code/abc255_d/Java/34048575
condefects-java_data_659
import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); String s = sc.next(); boolean flag = false; if(s.length() == 8){ if(s.charAt(0) >= 'A' && s.charAt(7) <= 'Z'){ if(s.substring(1,7).matches("[+-]?\\d*(\\.\\d+)?")){ int tmp = Integer.valueOf(s.substring(1,7)); if(tmp >= 100000 && tmp <= 999999) flag = true; } } } if(flag) System.out.println("Yes"); else System.out.println("No"); sc.close(); } } import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); String s = sc.next(); boolean flag = false; if(s.length() == 8){ if(s.charAt(0) >= 'A' && s.charAt(7) <= 'Z' && s.charAt(7) >= 'A' && s.charAt(0) <= 'Z'){ if(s.substring(1,7).matches("[+-]?\\d*(\\.\\d+)?")){ int tmp = Integer.valueOf(s.substring(1,7)); if(tmp >= 100000 && tmp <= 999999) flag = true; } } } if(flag) System.out.println("Yes"); else System.out.println("No"); sc.close(); } }
ConDefects/ConDefects/Code/abc281_b/Java/39730841
condefects-java_data_660
import java.util.*; import static java.lang.Character.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); int slen = s.length(); int index = 6; if(slen != 8) { System.out.println("No"); } else if (isUpperCase(s.charAt(0)) && isUpperCase(s.charAt(7))) { String x = ""; for(int i = 1; i < 7; i ++) { if(isDigit(s.charAt(i))) { x = x.concat(String.valueOf(s.charAt(i))); index --; } } if(index == 0) { int ii = Integer.parseInt(x); if(ii > 99999 && ii < 1000000) { System.out.println("Yes"); } else { System.out.println("No"); } } else { System.out.println("No"); } } } } import java.util.*; import static java.lang.Character.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); int slen = s.length(); int index = 6; if(slen != 8) { System.out.println("No"); } else if (isUpperCase(s.charAt(0)) && isUpperCase(s.charAt(7))) { String x = ""; for(int i = 1; i < 7; i ++) { if(isDigit(s.charAt(i))) { x = x.concat(String.valueOf(s.charAt(i))); index --; } } if(index == 0) { int ii = Integer.parseInt(x); if(ii > 99999 && ii < 1000000) { System.out.println("Yes"); } else { System.out.println("No"); } } else { System.out.println("No"); } } else { System.out.println("No"); } } }
ConDefects/ConDefects/Code/abc281_b/Java/39098757
condefects-java_data_661
import java.util.Scanner; public class Main { public static void main(final String[] args) { try (final Scanner sc = new Scanner(System.in)) { final String S = sc.next(); if (S.length() != 8) { System.out.println("No"); return; } if (Character.isDigit(S.charAt(0)) || Character.isDigit(S.charAt(S.length() - 1))) { System.out.println("No"); return; } if (Character.isDigit(S.charAt(1)) && Character.isDigit(S.charAt(S.length() - 2))) { System.out.println("No"); return; } try { final int numS = Integer.parseInt(S.substring(1, S.length() - 1)); if (100000 > numS || numS > 999999) { System.out.println("No"); return; } } catch (final NumberFormatException e) { System.out.println("No"); return; } System.out.println("Yes"); } } } import java.util.Scanner; public class Main { public static void main(final String[] args) { try (final Scanner sc = new Scanner(System.in)) { final String S = sc.next(); if (S.length() != 8) { System.out.println("No"); return; } if (Character.isDigit(S.charAt(0)) || Character.isDigit(S.charAt(S.length() - 1))) { System.out.println("No"); return; } if (!(Character.isDigit(S.charAt(1)) && Character.isDigit(S.charAt(S.length() - 2)))) { System.out.println("No"); return; } try { final int numS = Integer.parseInt(S.substring(1, S.length() - 1)); if (100000 > numS || numS > 999999) { System.out.println("No"); return; } } catch (final NumberFormatException e) { System.out.println("No"); return; } System.out.println("Yes"); } } }
ConDefects/ConDefects/Code/abc281_b/Java/44835970
condefects-java_data_662
import java.util.*; public class Main { public static String Sandwich(String str){ //A100000K if(str.length() != 8){ return "No"; } int upperCase = 0; int numberCount = 0; for(int i = 0 ; i < str.length(); i++){ if(str.charAt(i) >= 'A' && str.charAt(i) <= 'Z'){ if(i==0 || i == 7) upperCase++; } if(str.charAt(i) >= '0' && str.charAt(i) <= '9'){ numberCount = numberCount*10 + str.charAt(i) - '0'; } } System.out.println(numberCount); if(upperCase == 2 && (numberCount >= 100000 && numberCount <= 999999)) return "Yes"; return "No"; } public static void main(String[] args) { Scanner san = new Scanner(System.in); String str= san.next(); System.out.println(Sandwich(str)); } } import java.util.*; public class Main { public static String Sandwich(String str){ //A100000K if(str.length() != 8){ return "No"; } int upperCase = 0; int numberCount = 0; for(int i = 0 ; i < str.length(); i++){ if(str.charAt(i) >= 'A' && str.charAt(i) <= 'Z'){ if(i==0 || i == 7) upperCase++; } if(str.charAt(i) >= '0' && str.charAt(i) <= '9'){ numberCount = numberCount*10 + str.charAt(i) - '0'; } } //System.out.println(numberCount); if(upperCase == 2 && (numberCount >= 100000 && numberCount <= 999999)) return "Yes"; return "No"; } public static void main(String[] args) { Scanner san = new Scanner(System.in); String str= san.next(); System.out.println(Sandwich(str)); } }
ConDefects/ConDefects/Code/abc281_b/Java/38993379
condefects-java_data_663
import java.util.*; public class Main{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); String S=sc.next(); int l=0; if(S.length()!=8){ System.out.println("No"); } else{ for(int i=0;i<=7;i++){ if(i==0||i==7){ int k=(int)S.charAt(i); if(65<=k&&k<=90){ l++; } else{ System.out.println("No"); break; } }else if(i==1){ int M=(int)S.charAt(i); if(M>=49&&M<=57){ l++; }else{ System.out.println("No"); break; } }else{ int M=(int)S.charAt(i); if(M>=48&&M<=57){ l++; }else{ System.out.println("No"); break; } } } if(l==8){ System.out.println("yes"); } } } } import java.util.*; public class Main{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); String S=sc.next(); int l=0; if(S.length()!=8){ System.out.println("No"); } else{ for(int i=0;i<=7;i++){ if(i==0||i==7){ int k=(int)S.charAt(i); if(65<=k&&k<=90){ l++; } else{ System.out.println("No"); break; } }else if(i==1){ int M=(int)S.charAt(i); if(M>=49&&M<=57){ l++; }else{ System.out.println("No"); break; } }else{ int M=(int)S.charAt(i); if(M>=48&&M<=57){ l++; }else{ System.out.println("No"); break; } } } if(l==8){ System.out.println("Yes"); } } } }
ConDefects/ConDefects/Code/abc281_b/Java/41462949
condefects-java_data_664
import java.io.*; import java.util.*; public class Main { public static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); public static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); public static int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } //如果数字太大会有精度丢失 public static long nextLong() throws IOException { in.nextToken(); return (long) in.nval; } //如果数字太大会有精度丢失 public static double nextDouble() throws IOException { in.nextToken(); return in.nval; } //字符串不能以数字开头,字符串不能是特殊符号,空格(| _ % ^..... ) public static String next() throws IOException { in.nextToken(); return in.sval; } static int N = 200010; static int mod = 998244353; static int[] arr = new int[N]; static long[] offset = {0,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000,10000000000L}; static int count(int num){ int res = 0; while(num > 0){ num /= 10; res++; } return res; } public static void main(String[] args) throws IOException { int n = nextInt(); for (int i = 0; i < n; i++) { arr[i] = nextInt(); } long ans = 0; long sum = arr[0]; //求第 i 个数字对答案的贡献 for (int i = 1,num,len; i < n; i++) { num = arr[i]; len = count(num); ans = (ans + sum * offset[len] % mod + (long)num * i % mod) % mod; sum = (sum + num) % mod; } pw.println(ans); pw.flush(); } } import java.io.*; import java.util.*; public class Main { public static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); public static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); public static int nextInt() throws IOException { in.nextToken(); return (int) in.nval; } //如果数字太大会有精度丢失 public static long nextLong() throws IOException { in.nextToken(); return (long) in.nval; } //如果数字太大会有精度丢失 public static double nextDouble() throws IOException { in.nextToken(); return in.nval; } //字符串不能以数字开头,字符串不能是特殊符号,空格(| _ % ^..... ) public static String next() throws IOException { in.nextToken(); return in.sval; } static int N = 200010; static int mod = 998244353; static int[] arr = new int[N]; static long[] offset = {0,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000 % mod,10000000000L % mod}; static int count(int num){ int res = 0; while(num > 0){ num /= 10; res++; } return res; } public static void main(String[] args) throws IOException { int n = nextInt(); for (int i = 0; i < n; i++) { arr[i] = nextInt(); } long ans = 0; long sum = arr[0]; //求第 i 个数字对答案的贡献 for (int i = 1,num,len; i < n; i++) { num = arr[i]; len = count(num); ans = (ans + sum * offset[len] % mod + (long)num * i % mod) % mod; sum = (sum + num) % mod; } pw.println(ans); pw.flush(); } }
ConDefects/ConDefects/Code/abc353_d/Java/53446063
condefects-java_data_665
import java.io.BufferedReader; import java.io.InputStreamReader; // ABC353D // https://atcoder.jp/contests/abc353/tasks/abc353_d public class Main { private static final long MOD = 998244353L; private static final int M = 11; // 制約上与えられるA[i]の最大桁数 public static void main(String[] args) throws Exception { /* --- Input --- */ var br = new BufferedReader(new InputStreamReader(System.in)); var N = Integer.parseInt(br.readLine()); var sa = br.readLine().split(" "); var A = new long[N]; for (var i = 0; i < N; i++) A[i] = Long.parseLong(sa[i]); br.close(); /* --- Process --- */ // Arrays.sort(A); // f(x,y)はxyの順序を入れ替えると結果が変わるためソートNG // (1)yに指定されて等倍で加算される分を計算:i番目はi-1回加算される(0-indexedならi回) var ans = 0L; for (var i = 1; i < N; i++) ans += A[i] * i % MOD; // (2)xに指定されて10^*倍で加算される分を計算:i番目はi番目より後ろの要素の桁数だけ10^*倍して加算される // pow[i]:10^i var pow = new long[M + 1]; pow[1] = 1L; for (var i = 2; i < M + 1; i++) pow[i] = pow[i - 1] * 10L; // K[i][j]:i番目までのj桁の要素の数 var K = new int[N][M]; for (var i = 0; i < N; i++) { if (i != 0) System.arraycopy(K[i - 1], 0, K[i], 0, M); for (var j = 2; j < pow.length; j++) { if (A[i] < pow[j]) { K[i][j - 1]++; break; } } } // K[N - 1][j] - K[i][j]:i番目より後ろのj桁の要素の数 for (var i = 0; i < N; i++) { for (var j = 1; j < M; j++) { var add = A[i] * pow[j + 1] % MOD; // A[i]を10^(j+1)倍した値が加算される add = add * (K[N - 1][j] - K[i][j]) % MOD; // i番目より後ろのj桁の要素の数だけ繰り返し加算される ans = (ans + add) % MOD; } } /* --- Output --- */ System.out.println(ans); System.out.flush(); } } import java.io.BufferedReader; import java.io.InputStreamReader; // ABC353D // https://atcoder.jp/contests/abc353/tasks/abc353_d public class Main { private static final long MOD = 998244353L; private static final int M = 11; // 制約上与えられるA[i]の最大桁数 public static void main(String[] args) throws Exception { /* --- Input --- */ var br = new BufferedReader(new InputStreamReader(System.in)); var N = Integer.parseInt(br.readLine()); var sa = br.readLine().split(" "); var A = new long[N]; for (var i = 0; i < N; i++) A[i] = Long.parseLong(sa[i]); br.close(); /* --- Process --- */ // Arrays.sort(A); // f(x,y)はxyの順序を入れ替えると結果が変わるためソートNG // (1)yに指定されて等倍で加算される分を計算:i番目はi-1回加算される(0-indexedならi回) var ans = 0L; for (var i = 1; i < N; i++) ans += A[i] * i % MOD; // (2)xに指定されて10^*倍で加算される分を計算:i番目はi番目より後ろの要素の桁数だけ10^*倍して加算される // pow[i]:10^i var pow = new long[M + 1]; pow[1] = 1L; for (var i = 2; i < M + 1; i++) pow[i] = pow[i - 1] * 10L; // K[i][j]:i番目までのj桁の要素の数 var K = new int[N][M]; for (var i = 0; i < N; i++) { if (i != 0) System.arraycopy(K[i - 1], 0, K[i], 0, M); for (var j = 2; j < pow.length; j++) { if (A[i] < pow[j]) { K[i][j - 1]++; break; } } } // K[N - 1][j] - K[i][j]:i番目より後ろのj桁の要素の数 for (var i = 0; i < N; i++) { for (var j = 1; j < M; j++) { var add = (A[i] % MOD) * (pow[j + 1] % MOD) % MOD; // A[i]を10^(j+1)倍した値が加算される add = add * (K[N - 1][j] - K[i][j]) % MOD; // i番目より後ろのj桁の要素の数だけ繰り返し加算される ans = (ans + add) % MOD; } } /* --- Output --- */ System.out.println(ans); System.out.flush(); } }
ConDefects/ConDefects/Code/abc353_d/Java/53412750
condefects-java_data_666
import java.util.*; public class Main { public static int digitsCount(int n){ int count=0; while(n>0){ count++; n=n/10; } return count; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int mod = 998244353; int[] arr = new int[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); } long[] prefix=new long[n]; long total=0; for(int i=0;i<n;i++){ prefix[i]=total; total=(total + (long)arr[i])%mod; } long ans=0; for(int i=1;i<n;i++){ long temp = (i*(long)arr[i])%mod; int digits = digitsCount(arr[i]); long temp2 = ((long)Math.pow(10,digits)*(prefix[i])) %mod ; ans = (ans%mod + temp%mod + temp2%mod)%mod; } System.out.println(ans); } } import java.util.*; public class Main { public static int digitsCount(int n){ int count=0; while(n>0){ count++; n=n/10; } return count; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int mod = 998244353; int[] arr = new int[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); } long[] prefix=new long[n]; long total=0; for(int i=0;i<n;i++){ prefix[i]=total; total=(total + (long)arr[i])%mod; } long ans=0; for(int i=1;i<n;i++){ long temp = (i*(long)arr[i])%mod; int digits = digitsCount(arr[i]); long temp2 = ((long)Math.pow(10,digits)%mod*(prefix[i])) %mod ; ans = (ans%mod + temp%mod + temp2%mod)%mod; } System.out.println(ans); } }
ConDefects/ConDefects/Code/abc353_d/Java/55123507
condefects-java_data_667
import java.util.Scanner; class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] array = new String[n]; for(int i = 0; i < n; i++){ array[i] = sc.next(); } String result = "No"; for(int i = 0; i < n-1; i++){ if(result.equals("Yes")){ break; } String a = array[i]; for(int j = i+1; j < n; j++){ String b = array[j]; String c = a+b; String d = b+a; System.out.println(c); System.out.println(d); int cCnt = 0; int dCnt = 0; for(int k = 0; k < c.length(); k++){ if(c.charAt(k) == c.charAt(c.length()-1-k)){ cCnt+=1; } } for(int l = 0; l < d.length(); l++){ if(d.charAt(l) == d.charAt(d.length()-1-l)){ dCnt+=1; } } if(c.length() == cCnt || d.length() == dCnt){ result = "Yes"; break; } } } System.out.println(result); } } import java.util.Scanner; class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] array = new String[n]; for(int i = 0; i < n; i++){ array[i] = sc.next(); } String result = "No"; for(int i = 0; i < n-1; i++){ if(result.equals("Yes")){ break; } String a = array[i]; for(int j = i+1; j < n; j++){ String b = array[j]; String c = a+b; String d = b+a; int cCnt = 0; int dCnt = 0; for(int k = 0; k < c.length(); k++){ if(c.charAt(k) == c.charAt(c.length()-1-k)){ cCnt+=1; } } for(int l = 0; l < d.length(); l++){ if(d.charAt(l) == d.charAt(d.length()-1-l)){ dCnt+=1; } } if(c.length() == cCnt || d.length() == dCnt){ result = "Yes"; break; } } } System.out.println(result); } }
ConDefects/ConDefects/Code/abc307_b/Java/43486887
condefects-java_data_668
import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String s[] = new String[n]; for(int i = 0; i < n; i++){ s[i] = sc.next(); } for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(i != 0){ boolean flag = true; String[] strs = (s[i] + s[j]).split(""); for(int k = 0; k <= strs.length / 2; k++){ if(!(strs[k].equals(strs[strs.length -1 - k]))){ flag = false; break; } } if(flag){ System.out.println("Yes"); return; } } } } System.out.println("No"); } } import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String s[] = new String[n]; for(int i = 0; i < n; i++){ s[i] = sc.next(); } for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(i != j){ boolean flag = true; String[] strs = (s[i] + s[j]).split(""); for(int k = 0; k <= strs.length / 2; k++){ if(!(strs[k].equals(strs[strs.length -1 - k]))){ flag = false; break; } } if(flag){ System.out.println("Yes"); return; } } } } System.out.println("No"); } }
ConDefects/ConDefects/Code/abc307_b/Java/43167508
condefects-java_data_669
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Queue; class Main { public static void solve(Read br, Write out) { long x = br.readL(); long min = 1000000000000000000L; if (x < 10) { out.pl(x); return; } int k = 0; long t = 1; while (t <= x) { t *= 10; k++; } for (int i = 1; i <= 9; i++) { for (int d = -9; d <= 9; d++) { long a = 0; for (int w = 0; w < k; w++) { int q = i + d * w; if (q < 0 || q > 9) { a = x + 1; break; } a = a * 10 + q; } if (a >= x && a < min) { min = a; } } } out.pl(min); } public static boolean func(int a[], int b[]) { for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } static class PermuT { int n; public int a[]; boolean flg; public PermuT(int n) { this.n = n; flg = true; a = new int[n]; for (int i = 0; i < n; i++) { a[i] = i + 1; } } public boolean next() { for (int i = n - 2; i >= 0; i--) { if (a[i] >= a[i + 1]) { continue; } for (int j = n - 1;; j--) { if (a[i] >= a[j]) { continue; } int temp = a[i]; a[i] = a[j]; a[j] = temp; i++; for (j = n - 1; i < j; i++, j--) { temp = a[i]; a[i] = a[j]; a[j] = temp; } return true; } } flg = false; return false; } } public static void main(String args[]) { Read br = new Read(); Write out = new Write(); solve(br, out); out.flush(); } static class Tree { int n; int root; int parent[]; int height[]; int maxh; ArrayList<ArrayList<Integer>> child; int lca[][]; public Tree(int nn, int r) { n = nn; root = r; parent = new int[n]; height = new int[n]; child = new ArrayList<>(); for (int i = 0; i < n; i++) { child.add(new ArrayList<>()); } } public Tree(int par[], int r) { n = par.length; root = r; parent = new int[n]; height = new int[n]; child = new ArrayList<>(); for (int i = 0; i < n; i++) { child.add(new ArrayList<>()); } for (int i = 0; i < n; i++) { parent[i] = par[i]; if (parent[i] != -1) { child.get(parent[i]).add(i); } } ArrayDeque<Integer> q = new ArrayDeque<>(); q.add(root); while (q.size() > 0) { int v = q.poll(); for (int u : child.get(v)) { height[u] = height[v] + 1; if (height[u] > maxh) { maxh = height[u]; } q.add(u); } } } public Tree(Graph g, int r) { this(g.n, r); construct(g); } public void construct(Graph g) { constructdfs(g, root, -1, 0, new boolean[n]); } public void constructdfs(Graph g, int now, int before, int h, boolean flg[]) { flg[now] = true; parent[now] = before; height[now] = h; if (h > maxh) { maxh = h; } for (Graph.Edge e : g.g.get(now)) { if (e.v != before) { constructdfs(g, e.v, now, h + 1, flg); child.get(now).add(e.v); } } } public void const_lowest_common_ancestor() { int k = 1; while ((1 << k) <= maxh) { k++; } lca = new int[k][n]; for (int i = 0; i < n; i++) { lca[0][i] = parent[i]; if (lca[0][i] == -1) { lca[0][i] = i; } } for (int i = 1; i < k; i++) { for (int v = 0; v < n; v++) { lca[i][v] = lca[i - 1][lca[i - 1][v]]; } } } public int get_anscestor(int u, int d) { int k = lca.length; for (int i = 0; i < k; i++) { if ((d >> i) % 2 > 0) { u = lca[i][u]; } } return u; } public int query_lowest_common_ancestor(int u, int v) { if (height[u] < height[v]) { return query_lowest_common_ancestor(v, u); } int k = lca.length; u = get_anscestor(u, height[u] - height[v]); if (u == v) { return u; } for (int i = k - 1; i >= 0; i--) { if (lca[i][u] != lca[i][v]) { u = lca[i][u]; v = lca[i][v]; } } return lca[0][u]; } } public static int comp(long a, long b) { return a > b ? 1 : a < b ? -1 : 0; } public static long fact(int i) { if (i == 1 || i == 0) { return 1L; } return i * fact(i - 1); } public static long gcd(long a, long b) { if (a < b) { return gcd(b, a); } long c = a % b; while (c != 0) { a = b; b = c; c = a % b; } return b; } public static long lcm(long a, long b) { return a / gcd(a, b) * b; } public static int gcd(int a, int b) { if (a < b) { return gcd(b, a); } int c = a % b; while (c != 0) { a = b; b = c; c = a % b; } return b; } public static int lcm(int a, int b) { return a / gcd(a, b) * b; } public static void sortA(int n[]) { Arrays.sort(n); } public static void sortD(int n[]) { Arrays.sort(n); rev(n); } public static void rev(int n[]) { int l = n.length; for (int i = 0; i < l / 2; i++) { int t = n[i]; n[i] = n[l - i - 1]; n[l - i - 1] = t; } } public static void sortA(ArrayList<Integer> n) { Collections.sort(n); } public static void sortD(ArrayList<Integer> n) { Collections.sort(n, Collections.reverseOrder()); } public static void sortA(int n[][], int k) { Arrays.sort(n, (a, b) -> Integer.compare(a[k], b[k])); } public static void sortD(int n[][], int k) { Arrays.sort(n, (a, b) -> Integer.compare(b[k], a[k])); } public static void mysort(int n[][], int k) { Arrays.sort(n, new Comparator<int[]>() { public int compare(int[] x, int[] y) { if (x[k] == y[k]) { return x[1] - y[1]; } return x[k] - y[k]; } }); } static class ModFunc { int n; long mod; long fact[], invfact[]; public ModFunc(int n, long mod) { this.n = n; this.mod = mod; fact = new long[n + 1]; invfact = new long[n + 1]; modfact(); modinvfact(); } public static long modfact(int n, long mod) { long k = 1; for (int i = 1; i <= n; i++) { k = k * i % mod; } return k; } public static long modinvfact(int n, long mod) { return modinv(modfact(n, mod), mod); } public static long modinv(long a, long mod) { long x1 = 1, x2 = 0; long p = a, q = mod, t; while (q != 0) { t = p / q; t = x1 - t * x2; x1 = x2; x2 = t; t = p % q; p = q; q = t; } return x1 < 0 ? x1 + mod : x1; } private void modfact() { fact[0] = 1; for (int i = 1; i <= n; i++) { fact[i] = fact[i - 1] * i % mod; } } private void modinvfact() { invfact[n] = modinv(fact[n], mod); for (int i = n - 1; i >= 0; i--) { invfact[i] = invfact[i + 1] * (i + 1) % mod; } } public long modConv(int n, int k) { return ((fact[n] * invfact[n - k]) % mod) * invfact[k] % mod; } public static long modpow(long x, long n, long pow) { long r = 1; while (n >= 1) { if (1 == (n & 1)) { r = r * x % pow; } x = x * x % pow; n /= 2; } return r; } } static class Permu { int n; public int a[]; boolean flg; public Permu(int n) { this.n = n; flg = true; a = new int[n]; for (int i = 0; i < n; i++) { a[i] = i; } } public Permu(int k[]) { this.n = k.length; flg = true; a = new int[n]; for (int i = 0; i < n; i++) { a[i] = k[i]; } } public boolean next() { for (int i = n - 2; i >= 0; i--) { if (a[i] >= a[i + 1]) { continue; } for (int j = n - 1;; j--) { if (a[i] >= a[j]) { continue; } int temp = a[i]; a[i] = a[j]; a[j] = temp; i++; for (j = n - 1; i < j; i++, j--) { temp = a[i]; a[i] = a[j]; a[j] = temp; } return true; } } flg = false; return false; } public boolean before() { for (int i = n - 2; i >= 0; i--) { if (a[i] <= a[i + 1]) { continue; } for (int j = n - 1;; j--) { if (a[i] <= a[j]) { continue; } int temp = a[i]; a[i] = a[j]; a[j] = temp; i++; for (j = n - 1; i < j; i++, j--) { temp = a[i]; a[i] = a[j]; a[j] = temp; } return true; } } flg = false; return false; } } static class Compress { ArrayList<Integer> a; HashMap<Integer, Integer> map; public Compress(int[] b) { HashSet<Integer> temp = new HashSet<>(); for (int i : b) { temp.add(i); } a = new ArrayList<Integer>(temp); setup(); } public Compress(ArrayList<Integer> b) { a = new ArrayList<Integer>(new HashSet<Integer>(b)); setup(); } private void setup() { map = new HashMap<>(); sortA(a); for (int i = 0; i < a.size(); i++) { map.put(a.get(i), i); } } public int get(int i) { return map.get(i); } } static class UnionFindTree { int parent[]; int size; int vol[]; public UnionFindTree(int s) { size = s; parent = new int[size]; vol = new int[size]; for (int i = 0; i < size; i++) { parent[i] = i; vol[i] = 1; } } public int root(int n) { if (parent[n] == n) { return n; } parent[n] = root(parent[n]); return parent[n]; } public void unite(int a, int b) { int ra = root(a), rb = root(b); if (ra == rb) { return; } if (vol[ra] < vol[rb]) { a = ra; ra = rb; rb = a; } parent[rb] = ra; vol[ra] += vol[rb]; } public boolean same(int a, int b) { return root(a) == root(b); } } static class WeightUnionFindTree { int parent[]; int size; int vol[]; int diff[]; public WeightUnionFindTree(int s) { size = s; parent = new int[size]; vol = new int[size]; diff = new int[size]; for (int i = 0; i < size; i++) { parent[i] = i; vol[i] = 1; diff[i] = 0; } } public int root(int n) { if (parent[n] == n) { return n; } int r = root(parent[n]); diff[n] += diff[parent[n]]; parent[n] = r; return parent[n]; } public int weight(int n) { root(n); return diff[n]; } public void unite(int a, int b, int w) { int ra = root(a), rb = root(b); if (ra == rb) { return; } w += weight(a); w -= weight(b); if (vol[ra] < vol[rb]) { a = ra; ra = rb; rb = a; w = -w; } parent[rb] = ra; vol[ra] += vol[rb]; diff[rb] = w; } public int differ(int a, int b) { return weight(a) - weight(b); } public boolean same(int a, int b) { return root(a) == root(b); } } static abstract class SegmentTree { int n, leafN; int ar[]; int lazy[]; int temp; public SegmentTree(int x, int temp) { leafN = x; this.temp = temp; n = twon(leafN); ar = new int[2 * n - 1]; lazy = new int[2 * n - 1]; for (int i = 0; i < n * 2 - 1; i++) { ar[i] = temp; lazy[i] = temp; } } public abstract int func(int a, int b); public void eval(int k) { if (lazy[k] == temp) { return; } if (k < n - 1) { lazy[k * 2 + 1] = lazy[k]; lazy[k * 2 + 2] = lazy[k]; } ar[k] = lazy[k]; lazy[k] = temp; } public void update(int i, int x) { int now = i + n - 1; ar[now] = x; while (now > 0) { now = (now - 1) / 2; ar[now] = func(ar[now * 2 + 1], ar[now * 2 + 2]); } } public void add(int i, int x) { update(i, ar[i + n - 1] + x); } public void update(int a, int b, int x) { update(a, b, x, 0, 0, n); } public void update(int a, int b, int x, int k, int l, int r) { eval(k); if (r <= a || b <= l) { return; } else if (a <= l && r <= b) { lazy[k] = x; eval(k); } update(a, b, x, k * 2 + 1, l, (l + r) / 2); update(a, b, x, k * 2 + 2, (l + r) / 2, r); ar[k] = func(ar[k * 2 + 1], ar[k * 2 + 2]); } public int get(int i) { return ar[i + n - 1]; } public int query(int a, int b) { return query(a, b, 0, 0, n); } public int query(int a, int b, int k, int l, int r) { eval(k); if (r <= a || b <= l) { return temp; } else if (a <= l && r <= b) { return ar[k]; } int t1 = query(a, b, k * 2 + 1, l, (l + r) / 2), t2 = query(a, b, k * 2 + 2, (l + r) / 2, r); return func(t1, t2); } private int twon(int x) { int i = 1; while (i < x) { i *= 2; } return i; } } static class SegmentTreeE extends SegmentTree { public SegmentTreeE(int x) { super(x, 0); } public int func(int a, int b) { return a ^ b; } } static class SegmentTreeMin extends SegmentTree { public SegmentTreeMin(int x) { super(x, Integer.MAX_VALUE); } public int func(int a, int b) { return Math.min(a, b); } } static class SegmentTreeS extends SegmentTree { public SegmentTreeS(int x) { super(x, 0); } public int func(int a, int b) { return a + b; } } static class BIT { int n; int ar[]; public BIT(int x) { n = x + 1; ar = new int[n]; for (int i = 0; i < n; i++) { ar[i] = 0; } } public void update(int i, int x) { i++; for (int ii = i; ii < n; ii += (ii & -ii)) { ar[ii] += x; } } public int sum(int i) { int k = 0; for (int ii = i; ii > 0; ii -= (ii & -ii)) { k += ar[ii]; } return k; } } static class Graph { int n; ArrayList<ArrayList<Edge>> g; public Graph(int nn) { n = nn; g = new ArrayList<ArrayList<Edge>>(); for (int i = 0; i < n; i++) { g.add(new ArrayList<Edge>()); } } public void add(int a, int b, int d) { g.get(a).add(new Edge(b, d)); g.get(b).add(new Edge(a, d)); } public void addY(int a, int b, int d) { g.get(a).add(new Edge(b, d)); } public void add(int a, int b) { g.get(a).add(new Edge(b, 1)); g.get(b).add(new Edge(a, 1)); } public void addY(int a, int b) { g.get(a).add(new Edge(b, 1)); } public int len(int a) { return g.get(a).size(); } public long[][] dijkstra(int s) { long dist[][] = new long[n][2]; for (int i = 0; i < n; i++) { dist[i][0] = Long.MAX_VALUE; dist[i][1] = -1; } dist[s][0] = 0; dist[s][1] = -1; PriorityQueue<long[]> q = new PriorityQueue<long[]>(new Comparator<long[]>() { public int compare(long[] x, long[] y) { return Long.compare(x[1], y[1]); } }); q.add(new long[] { s, 0L }); while (q.size() > 0) { long[] p = q.poll(); if (dist[(int) p[0]][0] != p[1]) { continue; } for (Edge e : g.get((int) p[0])) { if (dist[e.v][0] > dist[(int) p[0]][0] + e.d) { dist[e.v][0] = dist[(int) p[0]][0] + e.d; dist[e.v][1] = (int) p[0]; q.add(new long[] { e.v, dist[e.v][0] }); } } } return dist; } public static long[][] floydwarshall(int g[][]) { int n = g.length; long dist[][] = new long[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dist[i][j] = g[i][j]; if (dist[i][j] == 0) { dist[i][j] = Long.MAX_VALUE; } } } for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (dist[i][k] == Long.MAX_VALUE || dist[k][j] == Long.MAX_VALUE) { continue; } dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); } } } return dist; } public void dfs(int v) { ArrayDeque<Integer> q = new ArrayDeque<>(); boolean flg[] = new boolean[n]; q.addLast(v); flg[v] = true; while (q.size() > 0) { int now = q.pollLast(); for (Edge e : g.get(now)) { if (!flg[e.v]) { flg[e.v] = true; q.addLast(e.v); } } } } public void bfs(int s) { boolean flg[] = new boolean[n]; Queue<Integer> q = new ArrayDeque<Integer>(); q.add(s); while (q.size() > 0) { int v = q.poll(); flg[v] = true; for (Edge e : g.get(v)) { if (!flg[e.v]) { q.add(e.v); flg[e.v] = true; } } } } public int minspantree() { PriorityQueue<Edge> q = new PriorityQueue<Edge>(new Comparator<Edge>() { public int compare(Edge a, Edge b) { return a.d - b.d; } }); boolean flg[] = new boolean[n]; int c = 1, sum = 0; for (Edge e : g.get(0)) { q.add(e); } flg[0] = true; while (c < n) { Edge e = q.poll(); if (flg[e.v]) { continue; } flg[e.v] = true; sum += e.d; c++; for (Edge i : g.get(e.v)) { if (!flg[i.v]) { q.add(i); } } } return sum; } public int[] scc1_1() { Graph g2 = new Graph(n); for (int i = 0; i < n; i++) { for (Edge e : g.get(i)) { g2.addY(e.v, i); } } ArrayList<Integer> list = new ArrayList<Integer>(); boolean flg[] = new boolean[n]; boolean end[] = new boolean[n]; ArrayDeque<Integer> q = new ArrayDeque<>(); for (int i = 0; i < n; i++) { if (flg[i]) { continue; } q.addLast(-i - 1); q.addLast(i + 1); while (q.size() > 0) { int v = q.pollLast(); if (v < 0) { v = -v - 1; if (end[v]) { continue; } end[v] = true; list.add(v); continue; } v--; if (flg[v]) { continue; } flg[v] = true; for (Edge e : g.get(v)) { if (flg[e.v]) { continue; } q.addLast(-e.v - 1); q.addLast(e.v + 1); } } } return g2.scc1_2(list); } public int[] scc1_2(ArrayList<Integer> list) { boolean flg[] = new boolean[n]; int ren[] = new int[n]; ArrayDeque<Integer> q = new ArrayDeque<>(); int num = 0; for (int i = n - 1; i >= 0; i--) { int now = list.get(i); if (flg[now]) { continue; } q.add(now); flg[now] = true; while (q.size() > 0) { int v = q.poll(); ren[v] = num; for (Edge e : g.get(v)) { if (flg[e.v]) { continue; } flg[e.v] = true; q.add(e.v); } } num++; } return ren; } public int[] scc() { Graph g2 = new Graph(n); for (int i = 0; i < n; i++) { for (Edge e : g.get(i)) { g2.addY(e.v, i); } } ArrayList<Integer> list = new ArrayList<Integer>(); boolean flg[] = new boolean[n]; for (int i = 0; i < n; i++) { if (!flg[i]) { dfs_scc(i, flg, list); } } return g2.scc2(list); } public int[] scc2(ArrayList<Integer> list) { boolean flg[] = new boolean[n]; int ren[] = new int[n]; int num = 0; for (int i = n - 1; i >= 0; i--) { int now = list.get(i); if (!flg[now]) { dfs_scc2(now, flg, ren, num); num++; } } return ren; } private void dfs_scc(int v, boolean flg[], ArrayList<Integer> list) { flg[v] = true; for (Edge e : g.get(v)) { if (!flg[e.v]) { dfs_scc(e.v, flg, list); } } list.add(v); } private void dfs_scc2(int v, boolean flg[], int num[], int now) { flg[v] = true; num[v] = now; for (Edge e : g.get(v)) { if (!flg[e.v]) { dfs_scc2(e.v, flg, num, now); } } } public ArrayList<ArrayList<Integer>> two_Edge_connected() { int ord[] = new int[n], low[] = new int[n]; boolean flg[] = new boolean[n]; for (int i = 0; i < n; i++) { if (!flg[i]) { tecDfs(i, flg, ord, low, -1); } } flg = new boolean[n]; ArrayList<ArrayList<Integer>> list = new ArrayList<>(); int now = 0; for (int i = 0; i < n; i++) { if (!flg[i]) { list.add(new ArrayList<>()); tecDfs2(i, flg, ord, low, list.get(now)); now++; } } return list; } public void tecDfs(int v, boolean flg[], int ord[], int low[], int before) { flg[v] = true; if (before != -1) { ord[v] = ord[before] + 1; } else { ord[v] = 0; } low[v] = ord[v]; for (Edge e : g.get(v)) { if (e.v == before) { before = -1; continue; } if (flg[e.v]) { low[v] = Math.min(low[v], ord[e.v]); } else { tecDfs(e.v, flg, ord, low, v); low[v] = Math.min(low[v], low[e.v]); } } } public void tecDfs2(int v, boolean flg[], int ord[], int low[], ArrayList<Integer> list) { flg[v] = true; list.add(v); for (Edge e : g.get(v)) { if (flg[e.v]) { continue; } if (ord[v] < low[e.v] || ord[e.v] < low[v]) { continue; } tecDfs2(e.v, flg, ord, low, list); } } static class Edge { int v, d; public Edge(int v, int d) { this.v = v; this.d = d; } } } static class Read { BufferedReader br; public Read() { br = new BufferedReader(new InputStreamReader(System.in)); } private boolean canprint(int a) { return 33 <= a && a <= 126; } private int skipread() { int a = readC(); while (a != -1 && !canprint(a)) { a = readC(); } return a; } public char readC() { try { return (char) br.read(); } catch (IOException e) { e.printStackTrace(); return (char) -1; } } public String readLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return ""; } } public String readS() { StringBuilder sb = new StringBuilder(); int k = skipread(); while (true) { if (!canprint(k)) { break; } sb.append((char) k); k = readC(); } return sb.toString(); } public int readI() { int r = 0; int k = skipread(); int flg = 1; if (k == '-') { flg = -1; k = readC(); } while (true) { if (!canprint(k)) { break; } r = r * 10 + (k - '0'); k = readC(); } return flg * r; } public long readL() { long r = 0; int k = skipread(); int flg = 1; if (k == '-') { flg = -1; k = readC(); } while (true) { if (!canprint(k)) { break; } r = r * 10 + (k - '0'); k = readC(); } return flg * r; } public String[] readSs(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) { a[i] = readS(); } return a; } public int[] readIs(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = readI(); } return a; } public long[] readLs(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = readL(); } return a; } } static class Write { PrintWriter out; boolean debug; public Write() { out = new PrintWriter(System.out); debug = false; } public <T> void pr(T str) { out.print(str); } public <T> void pl(T str) { out.println(str); } public void pr(int[] a) { int t = a.length; if (t > 0) { pr(a[0]); } for (int i = 1; i < t; i++) { pr(" " + a[i]); } pl(""); } public void pr(int[][] a) { for (int i[] : a) { pr(i); } } public void pr(long[] a) { int t = a.length; if (t > 0) { pr(a[0]); } for (int i = 1; i < t; i++) { pr(" " + a[i]); } pl(""); } public void pr(long[][] a) { for (long i[] : a) { pr(i); } } public void pr(String[] a) { int t = a.length; if (t > 0) { pr(a[0]); } for (int i = 1; i < t; i++) { pr(" " + a[i]); } pl(""); } public void pr(String[][] a) { for (String i[] : a) { pr(i); } } public void yes() { pl("Yes"); } public void no() { pl("No"); } public void yn(boolean flg) { if (flg) { yes(); } else { no(); } } public void flush() { out.flush(); } public static <T> void prA(T str) { System.out.print(str); } public static <T> void plA(T str) { System.out.println(str); } public static void prA(int[] a) { int t = a.length; if (t > 0) { prA(a[0]); } for (int i = 1; i < t; i++) { prA(" " + a[i]); } plA(""); } public static void prA(int[][] a) { for (int i[] : a) { prA(i); } } public static void prA(long[] a) { int t = a.length; if (t > 0) { prA(a[0]); } for (int i = 1; i < t; i++) { prA(" " + a[i]); } plA(""); } public static void prA(long[][] a) { for (long i[] : a) { prA(i); } } public static void prA(String[] a) { int t = a.length; if (t > 0) { prA(a[0]); } for (int i = 1; i < t; i++) { prA(" " + a[i]); } plA(""); } public static void prA(String[][] a) { for (String i[] : a) { prA(i); } } public <T> void debugP(T str) { if (debug) { pl(str); } } } public static long stol(String s) { return Long.parseLong(s); } public static int stoi(String s) { return Integer.parseInt(s); } public static int[] stoi(String s[]) { int a[] = new int[s.length]; for (int i = 0; i < s.length; i++) { a[i] = stoi(s[i]); } return a; } public static String itos(int i) { return String.valueOf(i); } public static String[] itos(int[] a) { String s[] = new String[a.length]; for (int i = 0; i < a.length; i++) { s[i] = itos(a[i]); } return s; } public static String ctos(char c) { return String.valueOf(c); } public static String cstos(char[] c) { return new String(c); } public static char stoc(String s) { return s.charAt(0); } public static char stoc(String s, int i) { return s.charAt(i); } public static char[] stocs(String s) { return s.toCharArray(); } } import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Queue; class Main { public static void solve(Read br, Write out) { long x = br.readL(); long min = 1000000000000000000L; if (x < 10) { out.pl(x); return; } int k = 0; long t = 1; while (t <= x) { t *= 10; k++; } for (int i = 1; i <= 9; i++) { for (int d = -9; d <= 9; d++) { long a = 0; for (int w = 0; w < k; w++) { int q = i + d * w; if (q < 0 || q > 9) { a = x - 1; break; } a = a * 10 + q; } if (a >= x && a < min) { min = a; } } } out.pl(min); } public static boolean func(int a[], int b[]) { for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } static class PermuT { int n; public int a[]; boolean flg; public PermuT(int n) { this.n = n; flg = true; a = new int[n]; for (int i = 0; i < n; i++) { a[i] = i + 1; } } public boolean next() { for (int i = n - 2; i >= 0; i--) { if (a[i] >= a[i + 1]) { continue; } for (int j = n - 1;; j--) { if (a[i] >= a[j]) { continue; } int temp = a[i]; a[i] = a[j]; a[j] = temp; i++; for (j = n - 1; i < j; i++, j--) { temp = a[i]; a[i] = a[j]; a[j] = temp; } return true; } } flg = false; return false; } } public static void main(String args[]) { Read br = new Read(); Write out = new Write(); solve(br, out); out.flush(); } static class Tree { int n; int root; int parent[]; int height[]; int maxh; ArrayList<ArrayList<Integer>> child; int lca[][]; public Tree(int nn, int r) { n = nn; root = r; parent = new int[n]; height = new int[n]; child = new ArrayList<>(); for (int i = 0; i < n; i++) { child.add(new ArrayList<>()); } } public Tree(int par[], int r) { n = par.length; root = r; parent = new int[n]; height = new int[n]; child = new ArrayList<>(); for (int i = 0; i < n; i++) { child.add(new ArrayList<>()); } for (int i = 0; i < n; i++) { parent[i] = par[i]; if (parent[i] != -1) { child.get(parent[i]).add(i); } } ArrayDeque<Integer> q = new ArrayDeque<>(); q.add(root); while (q.size() > 0) { int v = q.poll(); for (int u : child.get(v)) { height[u] = height[v] + 1; if (height[u] > maxh) { maxh = height[u]; } q.add(u); } } } public Tree(Graph g, int r) { this(g.n, r); construct(g); } public void construct(Graph g) { constructdfs(g, root, -1, 0, new boolean[n]); } public void constructdfs(Graph g, int now, int before, int h, boolean flg[]) { flg[now] = true; parent[now] = before; height[now] = h; if (h > maxh) { maxh = h; } for (Graph.Edge e : g.g.get(now)) { if (e.v != before) { constructdfs(g, e.v, now, h + 1, flg); child.get(now).add(e.v); } } } public void const_lowest_common_ancestor() { int k = 1; while ((1 << k) <= maxh) { k++; } lca = new int[k][n]; for (int i = 0; i < n; i++) { lca[0][i] = parent[i]; if (lca[0][i] == -1) { lca[0][i] = i; } } for (int i = 1; i < k; i++) { for (int v = 0; v < n; v++) { lca[i][v] = lca[i - 1][lca[i - 1][v]]; } } } public int get_anscestor(int u, int d) { int k = lca.length; for (int i = 0; i < k; i++) { if ((d >> i) % 2 > 0) { u = lca[i][u]; } } return u; } public int query_lowest_common_ancestor(int u, int v) { if (height[u] < height[v]) { return query_lowest_common_ancestor(v, u); } int k = lca.length; u = get_anscestor(u, height[u] - height[v]); if (u == v) { return u; } for (int i = k - 1; i >= 0; i--) { if (lca[i][u] != lca[i][v]) { u = lca[i][u]; v = lca[i][v]; } } return lca[0][u]; } } public static int comp(long a, long b) { return a > b ? 1 : a < b ? -1 : 0; } public static long fact(int i) { if (i == 1 || i == 0) { return 1L; } return i * fact(i - 1); } public static long gcd(long a, long b) { if (a < b) { return gcd(b, a); } long c = a % b; while (c != 0) { a = b; b = c; c = a % b; } return b; } public static long lcm(long a, long b) { return a / gcd(a, b) * b; } public static int gcd(int a, int b) { if (a < b) { return gcd(b, a); } int c = a % b; while (c != 0) { a = b; b = c; c = a % b; } return b; } public static int lcm(int a, int b) { return a / gcd(a, b) * b; } public static void sortA(int n[]) { Arrays.sort(n); } public static void sortD(int n[]) { Arrays.sort(n); rev(n); } public static void rev(int n[]) { int l = n.length; for (int i = 0; i < l / 2; i++) { int t = n[i]; n[i] = n[l - i - 1]; n[l - i - 1] = t; } } public static void sortA(ArrayList<Integer> n) { Collections.sort(n); } public static void sortD(ArrayList<Integer> n) { Collections.sort(n, Collections.reverseOrder()); } public static void sortA(int n[][], int k) { Arrays.sort(n, (a, b) -> Integer.compare(a[k], b[k])); } public static void sortD(int n[][], int k) { Arrays.sort(n, (a, b) -> Integer.compare(b[k], a[k])); } public static void mysort(int n[][], int k) { Arrays.sort(n, new Comparator<int[]>() { public int compare(int[] x, int[] y) { if (x[k] == y[k]) { return x[1] - y[1]; } return x[k] - y[k]; } }); } static class ModFunc { int n; long mod; long fact[], invfact[]; public ModFunc(int n, long mod) { this.n = n; this.mod = mod; fact = new long[n + 1]; invfact = new long[n + 1]; modfact(); modinvfact(); } public static long modfact(int n, long mod) { long k = 1; for (int i = 1; i <= n; i++) { k = k * i % mod; } return k; } public static long modinvfact(int n, long mod) { return modinv(modfact(n, mod), mod); } public static long modinv(long a, long mod) { long x1 = 1, x2 = 0; long p = a, q = mod, t; while (q != 0) { t = p / q; t = x1 - t * x2; x1 = x2; x2 = t; t = p % q; p = q; q = t; } return x1 < 0 ? x1 + mod : x1; } private void modfact() { fact[0] = 1; for (int i = 1; i <= n; i++) { fact[i] = fact[i - 1] * i % mod; } } private void modinvfact() { invfact[n] = modinv(fact[n], mod); for (int i = n - 1; i >= 0; i--) { invfact[i] = invfact[i + 1] * (i + 1) % mod; } } public long modConv(int n, int k) { return ((fact[n] * invfact[n - k]) % mod) * invfact[k] % mod; } public static long modpow(long x, long n, long pow) { long r = 1; while (n >= 1) { if (1 == (n & 1)) { r = r * x % pow; } x = x * x % pow; n /= 2; } return r; } } static class Permu { int n; public int a[]; boolean flg; public Permu(int n) { this.n = n; flg = true; a = new int[n]; for (int i = 0; i < n; i++) { a[i] = i; } } public Permu(int k[]) { this.n = k.length; flg = true; a = new int[n]; for (int i = 0; i < n; i++) { a[i] = k[i]; } } public boolean next() { for (int i = n - 2; i >= 0; i--) { if (a[i] >= a[i + 1]) { continue; } for (int j = n - 1;; j--) { if (a[i] >= a[j]) { continue; } int temp = a[i]; a[i] = a[j]; a[j] = temp; i++; for (j = n - 1; i < j; i++, j--) { temp = a[i]; a[i] = a[j]; a[j] = temp; } return true; } } flg = false; return false; } public boolean before() { for (int i = n - 2; i >= 0; i--) { if (a[i] <= a[i + 1]) { continue; } for (int j = n - 1;; j--) { if (a[i] <= a[j]) { continue; } int temp = a[i]; a[i] = a[j]; a[j] = temp; i++; for (j = n - 1; i < j; i++, j--) { temp = a[i]; a[i] = a[j]; a[j] = temp; } return true; } } flg = false; return false; } } static class Compress { ArrayList<Integer> a; HashMap<Integer, Integer> map; public Compress(int[] b) { HashSet<Integer> temp = new HashSet<>(); for (int i : b) { temp.add(i); } a = new ArrayList<Integer>(temp); setup(); } public Compress(ArrayList<Integer> b) { a = new ArrayList<Integer>(new HashSet<Integer>(b)); setup(); } private void setup() { map = new HashMap<>(); sortA(a); for (int i = 0; i < a.size(); i++) { map.put(a.get(i), i); } } public int get(int i) { return map.get(i); } } static class UnionFindTree { int parent[]; int size; int vol[]; public UnionFindTree(int s) { size = s; parent = new int[size]; vol = new int[size]; for (int i = 0; i < size; i++) { parent[i] = i; vol[i] = 1; } } public int root(int n) { if (parent[n] == n) { return n; } parent[n] = root(parent[n]); return parent[n]; } public void unite(int a, int b) { int ra = root(a), rb = root(b); if (ra == rb) { return; } if (vol[ra] < vol[rb]) { a = ra; ra = rb; rb = a; } parent[rb] = ra; vol[ra] += vol[rb]; } public boolean same(int a, int b) { return root(a) == root(b); } } static class WeightUnionFindTree { int parent[]; int size; int vol[]; int diff[]; public WeightUnionFindTree(int s) { size = s; parent = new int[size]; vol = new int[size]; diff = new int[size]; for (int i = 0; i < size; i++) { parent[i] = i; vol[i] = 1; diff[i] = 0; } } public int root(int n) { if (parent[n] == n) { return n; } int r = root(parent[n]); diff[n] += diff[parent[n]]; parent[n] = r; return parent[n]; } public int weight(int n) { root(n); return diff[n]; } public void unite(int a, int b, int w) { int ra = root(a), rb = root(b); if (ra == rb) { return; } w += weight(a); w -= weight(b); if (vol[ra] < vol[rb]) { a = ra; ra = rb; rb = a; w = -w; } parent[rb] = ra; vol[ra] += vol[rb]; diff[rb] = w; } public int differ(int a, int b) { return weight(a) - weight(b); } public boolean same(int a, int b) { return root(a) == root(b); } } static abstract class SegmentTree { int n, leafN; int ar[]; int lazy[]; int temp; public SegmentTree(int x, int temp) { leafN = x; this.temp = temp; n = twon(leafN); ar = new int[2 * n - 1]; lazy = new int[2 * n - 1]; for (int i = 0; i < n * 2 - 1; i++) { ar[i] = temp; lazy[i] = temp; } } public abstract int func(int a, int b); public void eval(int k) { if (lazy[k] == temp) { return; } if (k < n - 1) { lazy[k * 2 + 1] = lazy[k]; lazy[k * 2 + 2] = lazy[k]; } ar[k] = lazy[k]; lazy[k] = temp; } public void update(int i, int x) { int now = i + n - 1; ar[now] = x; while (now > 0) { now = (now - 1) / 2; ar[now] = func(ar[now * 2 + 1], ar[now * 2 + 2]); } } public void add(int i, int x) { update(i, ar[i + n - 1] + x); } public void update(int a, int b, int x) { update(a, b, x, 0, 0, n); } public void update(int a, int b, int x, int k, int l, int r) { eval(k); if (r <= a || b <= l) { return; } else if (a <= l && r <= b) { lazy[k] = x; eval(k); } update(a, b, x, k * 2 + 1, l, (l + r) / 2); update(a, b, x, k * 2 + 2, (l + r) / 2, r); ar[k] = func(ar[k * 2 + 1], ar[k * 2 + 2]); } public int get(int i) { return ar[i + n - 1]; } public int query(int a, int b) { return query(a, b, 0, 0, n); } public int query(int a, int b, int k, int l, int r) { eval(k); if (r <= a || b <= l) { return temp; } else if (a <= l && r <= b) { return ar[k]; } int t1 = query(a, b, k * 2 + 1, l, (l + r) / 2), t2 = query(a, b, k * 2 + 2, (l + r) / 2, r); return func(t1, t2); } private int twon(int x) { int i = 1; while (i < x) { i *= 2; } return i; } } static class SegmentTreeE extends SegmentTree { public SegmentTreeE(int x) { super(x, 0); } public int func(int a, int b) { return a ^ b; } } static class SegmentTreeMin extends SegmentTree { public SegmentTreeMin(int x) { super(x, Integer.MAX_VALUE); } public int func(int a, int b) { return Math.min(a, b); } } static class SegmentTreeS extends SegmentTree { public SegmentTreeS(int x) { super(x, 0); } public int func(int a, int b) { return a + b; } } static class BIT { int n; int ar[]; public BIT(int x) { n = x + 1; ar = new int[n]; for (int i = 0; i < n; i++) { ar[i] = 0; } } public void update(int i, int x) { i++; for (int ii = i; ii < n; ii += (ii & -ii)) { ar[ii] += x; } } public int sum(int i) { int k = 0; for (int ii = i; ii > 0; ii -= (ii & -ii)) { k += ar[ii]; } return k; } } static class Graph { int n; ArrayList<ArrayList<Edge>> g; public Graph(int nn) { n = nn; g = new ArrayList<ArrayList<Edge>>(); for (int i = 0; i < n; i++) { g.add(new ArrayList<Edge>()); } } public void add(int a, int b, int d) { g.get(a).add(new Edge(b, d)); g.get(b).add(new Edge(a, d)); } public void addY(int a, int b, int d) { g.get(a).add(new Edge(b, d)); } public void add(int a, int b) { g.get(a).add(new Edge(b, 1)); g.get(b).add(new Edge(a, 1)); } public void addY(int a, int b) { g.get(a).add(new Edge(b, 1)); } public int len(int a) { return g.get(a).size(); } public long[][] dijkstra(int s) { long dist[][] = new long[n][2]; for (int i = 0; i < n; i++) { dist[i][0] = Long.MAX_VALUE; dist[i][1] = -1; } dist[s][0] = 0; dist[s][1] = -1; PriorityQueue<long[]> q = new PriorityQueue<long[]>(new Comparator<long[]>() { public int compare(long[] x, long[] y) { return Long.compare(x[1], y[1]); } }); q.add(new long[] { s, 0L }); while (q.size() > 0) { long[] p = q.poll(); if (dist[(int) p[0]][0] != p[1]) { continue; } for (Edge e : g.get((int) p[0])) { if (dist[e.v][0] > dist[(int) p[0]][0] + e.d) { dist[e.v][0] = dist[(int) p[0]][0] + e.d; dist[e.v][1] = (int) p[0]; q.add(new long[] { e.v, dist[e.v][0] }); } } } return dist; } public static long[][] floydwarshall(int g[][]) { int n = g.length; long dist[][] = new long[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dist[i][j] = g[i][j]; if (dist[i][j] == 0) { dist[i][j] = Long.MAX_VALUE; } } } for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (dist[i][k] == Long.MAX_VALUE || dist[k][j] == Long.MAX_VALUE) { continue; } dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); } } } return dist; } public void dfs(int v) { ArrayDeque<Integer> q = new ArrayDeque<>(); boolean flg[] = new boolean[n]; q.addLast(v); flg[v] = true; while (q.size() > 0) { int now = q.pollLast(); for (Edge e : g.get(now)) { if (!flg[e.v]) { flg[e.v] = true; q.addLast(e.v); } } } } public void bfs(int s) { boolean flg[] = new boolean[n]; Queue<Integer> q = new ArrayDeque<Integer>(); q.add(s); while (q.size() > 0) { int v = q.poll(); flg[v] = true; for (Edge e : g.get(v)) { if (!flg[e.v]) { q.add(e.v); flg[e.v] = true; } } } } public int minspantree() { PriorityQueue<Edge> q = new PriorityQueue<Edge>(new Comparator<Edge>() { public int compare(Edge a, Edge b) { return a.d - b.d; } }); boolean flg[] = new boolean[n]; int c = 1, sum = 0; for (Edge e : g.get(0)) { q.add(e); } flg[0] = true; while (c < n) { Edge e = q.poll(); if (flg[e.v]) { continue; } flg[e.v] = true; sum += e.d; c++; for (Edge i : g.get(e.v)) { if (!flg[i.v]) { q.add(i); } } } return sum; } public int[] scc1_1() { Graph g2 = new Graph(n); for (int i = 0; i < n; i++) { for (Edge e : g.get(i)) { g2.addY(e.v, i); } } ArrayList<Integer> list = new ArrayList<Integer>(); boolean flg[] = new boolean[n]; boolean end[] = new boolean[n]; ArrayDeque<Integer> q = new ArrayDeque<>(); for (int i = 0; i < n; i++) { if (flg[i]) { continue; } q.addLast(-i - 1); q.addLast(i + 1); while (q.size() > 0) { int v = q.pollLast(); if (v < 0) { v = -v - 1; if (end[v]) { continue; } end[v] = true; list.add(v); continue; } v--; if (flg[v]) { continue; } flg[v] = true; for (Edge e : g.get(v)) { if (flg[e.v]) { continue; } q.addLast(-e.v - 1); q.addLast(e.v + 1); } } } return g2.scc1_2(list); } public int[] scc1_2(ArrayList<Integer> list) { boolean flg[] = new boolean[n]; int ren[] = new int[n]; ArrayDeque<Integer> q = new ArrayDeque<>(); int num = 0; for (int i = n - 1; i >= 0; i--) { int now = list.get(i); if (flg[now]) { continue; } q.add(now); flg[now] = true; while (q.size() > 0) { int v = q.poll(); ren[v] = num; for (Edge e : g.get(v)) { if (flg[e.v]) { continue; } flg[e.v] = true; q.add(e.v); } } num++; } return ren; } public int[] scc() { Graph g2 = new Graph(n); for (int i = 0; i < n; i++) { for (Edge e : g.get(i)) { g2.addY(e.v, i); } } ArrayList<Integer> list = new ArrayList<Integer>(); boolean flg[] = new boolean[n]; for (int i = 0; i < n; i++) { if (!flg[i]) { dfs_scc(i, flg, list); } } return g2.scc2(list); } public int[] scc2(ArrayList<Integer> list) { boolean flg[] = new boolean[n]; int ren[] = new int[n]; int num = 0; for (int i = n - 1; i >= 0; i--) { int now = list.get(i); if (!flg[now]) { dfs_scc2(now, flg, ren, num); num++; } } return ren; } private void dfs_scc(int v, boolean flg[], ArrayList<Integer> list) { flg[v] = true; for (Edge e : g.get(v)) { if (!flg[e.v]) { dfs_scc(e.v, flg, list); } } list.add(v); } private void dfs_scc2(int v, boolean flg[], int num[], int now) { flg[v] = true; num[v] = now; for (Edge e : g.get(v)) { if (!flg[e.v]) { dfs_scc2(e.v, flg, num, now); } } } public ArrayList<ArrayList<Integer>> two_Edge_connected() { int ord[] = new int[n], low[] = new int[n]; boolean flg[] = new boolean[n]; for (int i = 0; i < n; i++) { if (!flg[i]) { tecDfs(i, flg, ord, low, -1); } } flg = new boolean[n]; ArrayList<ArrayList<Integer>> list = new ArrayList<>(); int now = 0; for (int i = 0; i < n; i++) { if (!flg[i]) { list.add(new ArrayList<>()); tecDfs2(i, flg, ord, low, list.get(now)); now++; } } return list; } public void tecDfs(int v, boolean flg[], int ord[], int low[], int before) { flg[v] = true; if (before != -1) { ord[v] = ord[before] + 1; } else { ord[v] = 0; } low[v] = ord[v]; for (Edge e : g.get(v)) { if (e.v == before) { before = -1; continue; } if (flg[e.v]) { low[v] = Math.min(low[v], ord[e.v]); } else { tecDfs(e.v, flg, ord, low, v); low[v] = Math.min(low[v], low[e.v]); } } } public void tecDfs2(int v, boolean flg[], int ord[], int low[], ArrayList<Integer> list) { flg[v] = true; list.add(v); for (Edge e : g.get(v)) { if (flg[e.v]) { continue; } if (ord[v] < low[e.v] || ord[e.v] < low[v]) { continue; } tecDfs2(e.v, flg, ord, low, list); } } static class Edge { int v, d; public Edge(int v, int d) { this.v = v; this.d = d; } } } static class Read { BufferedReader br; public Read() { br = new BufferedReader(new InputStreamReader(System.in)); } private boolean canprint(int a) { return 33 <= a && a <= 126; } private int skipread() { int a = readC(); while (a != -1 && !canprint(a)) { a = readC(); } return a; } public char readC() { try { return (char) br.read(); } catch (IOException e) { e.printStackTrace(); return (char) -1; } } public String readLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return ""; } } public String readS() { StringBuilder sb = new StringBuilder(); int k = skipread(); while (true) { if (!canprint(k)) { break; } sb.append((char) k); k = readC(); } return sb.toString(); } public int readI() { int r = 0; int k = skipread(); int flg = 1; if (k == '-') { flg = -1; k = readC(); } while (true) { if (!canprint(k)) { break; } r = r * 10 + (k - '0'); k = readC(); } return flg * r; } public long readL() { long r = 0; int k = skipread(); int flg = 1; if (k == '-') { flg = -1; k = readC(); } while (true) { if (!canprint(k)) { break; } r = r * 10 + (k - '0'); k = readC(); } return flg * r; } public String[] readSs(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) { a[i] = readS(); } return a; } public int[] readIs(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = readI(); } return a; } public long[] readLs(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = readL(); } return a; } } static class Write { PrintWriter out; boolean debug; public Write() { out = new PrintWriter(System.out); debug = false; } public <T> void pr(T str) { out.print(str); } public <T> void pl(T str) { out.println(str); } public void pr(int[] a) { int t = a.length; if (t > 0) { pr(a[0]); } for (int i = 1; i < t; i++) { pr(" " + a[i]); } pl(""); } public void pr(int[][] a) { for (int i[] : a) { pr(i); } } public void pr(long[] a) { int t = a.length; if (t > 0) { pr(a[0]); } for (int i = 1; i < t; i++) { pr(" " + a[i]); } pl(""); } public void pr(long[][] a) { for (long i[] : a) { pr(i); } } public void pr(String[] a) { int t = a.length; if (t > 0) { pr(a[0]); } for (int i = 1; i < t; i++) { pr(" " + a[i]); } pl(""); } public void pr(String[][] a) { for (String i[] : a) { pr(i); } } public void yes() { pl("Yes"); } public void no() { pl("No"); } public void yn(boolean flg) { if (flg) { yes(); } else { no(); } } public void flush() { out.flush(); } public static <T> void prA(T str) { System.out.print(str); } public static <T> void plA(T str) { System.out.println(str); } public static void prA(int[] a) { int t = a.length; if (t > 0) { prA(a[0]); } for (int i = 1; i < t; i++) { prA(" " + a[i]); } plA(""); } public static void prA(int[][] a) { for (int i[] : a) { prA(i); } } public static void prA(long[] a) { int t = a.length; if (t > 0) { prA(a[0]); } for (int i = 1; i < t; i++) { prA(" " + a[i]); } plA(""); } public static void prA(long[][] a) { for (long i[] : a) { prA(i); } } public static void prA(String[] a) { int t = a.length; if (t > 0) { prA(a[0]); } for (int i = 1; i < t; i++) { prA(" " + a[i]); } plA(""); } public static void prA(String[][] a) { for (String i[] : a) { prA(i); } } public <T> void debugP(T str) { if (debug) { pl(str); } } } public static long stol(String s) { return Long.parseLong(s); } public static int stoi(String s) { return Integer.parseInt(s); } public static int[] stoi(String s[]) { int a[] = new int[s.length]; for (int i = 0; i < s.length; i++) { a[i] = stoi(s[i]); } return a; } public static String itos(int i) { return String.valueOf(i); } public static String[] itos(int[] a) { String s[] = new String[a.length]; for (int i = 0; i < a.length; i++) { s[i] = itos(a[i]); } return s; } public static String ctos(char c) { return String.valueOf(c); } public static String cstos(char[] c) { return new String(c); } public static char stoc(String s) { return s.charAt(0); } public static char stoc(String s, int i) { return s.charAt(i); } public static char[] stocs(String s) { return s.toCharArray(); } }
ConDefects/ConDefects/Code/abc234_e/Java/42275804
condefects-java_data_670
//ここからimport文 import java.util.*; import java.io.*; import java.math.*; //import mylib.* ; //ここまでimport文 public class Main{ static FastScanner sc ; static PrintWriter pw ; static final int inf = Integer.MAX_VALUE / 2 ; // static final long inf = Long.MAX_VALUE / 2L ; static final String LF = "\n" ; static final int mod = 1000000007 ; // static final long mod = 4611686018427387847L ; // static ArrayList<ArrayList<Integer>> G ; public static void solve() { long X = nl() ; if ( X < 100 ) { pr( X ) ; return ; } int k = String.valueOf( X ).length() ; int l = (int)( X / pow( 10 , k - 1 ) ) ; long res = 99999999999999999L ; while ( true ) { for ( int i = -9 ; i <= 9 ; i++ ) { int n = l ; String str = String.valueOf( n ) ; for ( int j = 1 ; j < k ; j++ ) { n += i ; if ( n < 0 || n > 9 ) break ; str += String.valueOf( n ) ; } if ( str.length() < k ) continue ; if ( Long.parseLong( str ) < X ) continue ; res = Math.min( res , Long.parseLong( str ) ) ; str = "" ; } l++ ; if ( l > (int)( X / pow( 10 , k - 1 ) ) + 2 ) break ; } pr( res ) ; } public static long pow( int a , int b ) { long res = 1L ; for ( int i = 0 ; i < b ; i++ ) res *= a ; return res ; } public static void main(String[] args) { sc = new FastScanner() ; pw = new PrintWriter( System.out ) ; solve() ; pw.flush() ; pw.close() ; } static class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;} private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;} private void skipUnprintable() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;} public boolean hasNext() { skipUnprintable(); return hasNextByte();} public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } } public static int ni() { return Integer.parseInt( sc.next() ) ;} public static int[] nia( int N ) { int[] res = new int[N]; Arrays.setAll( res , i -> ni() ) ; return res ; } public static void pi( int n ) { pw.println( n ) ; } public static long nl() { return Long.parseLong( sc.next() ) ;} public static void pl( long l ) { pw.println( l ) ; } public static void pd( double d ) { pw.println( d ) ; } public static String ns() { return sc.next() ;} public static String[] nsa( int N ) { String[] res = new String[N]; Arrays.setAll( res , i -> ns() ) ; return res ; } public static void ps( String s ) { pw.println( s ) ; } public static void psb( StringBuilder sb ) { pw.println( sb.toString() ) ; } public static BigDecimal nbd() { return new BigDecimal( sc.next() ) ; } public static void pbd( BigDecimal bd ) { pw.println( bd.toPlainString() ) ; } public static void pr( Object o ) { pw.println( o ) ; } } //ここからimport文 import java.util.*; import java.io.*; import java.math.*; //import mylib.* ; //ここまでimport文 public class Main{ static FastScanner sc ; static PrintWriter pw ; static final int inf = Integer.MAX_VALUE / 2 ; // static final long inf = Long.MAX_VALUE / 2L ; static final String LF = "\n" ; static final int mod = 1000000007 ; // static final long mod = 4611686018427387847L ; // static ArrayList<ArrayList<Integer>> G ; public static void solve() { long X = nl() ; if ( X < 100 ) { pr( X ) ; return ; } int k = String.valueOf( X ).length() ; int l = (int)( X / pow( 10 , k - 1 ) ) ; long res = 999999999999999999L ; while ( true ) { for ( int i = -9 ; i <= 9 ; i++ ) { int n = l ; String str = String.valueOf( n ) ; for ( int j = 1 ; j < k ; j++ ) { n += i ; if ( n < 0 || n > 9 ) break ; str += String.valueOf( n ) ; } if ( str.length() < k ) continue ; if ( Long.parseLong( str ) < X ) continue ; res = Math.min( res , Long.parseLong( str ) ) ; str = "" ; } l++ ; if ( l > (int)( X / pow( 10 , k - 1 ) ) + 2 ) break ; } pr( res ) ; } public static long pow( int a , int b ) { long res = 1L ; for ( int i = 0 ; i < b ; i++ ) res *= a ; return res ; } public static void main(String[] args) { sc = new FastScanner() ; pw = new PrintWriter( System.out ) ; solve() ; pw.flush() ; pw.close() ; } static class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;} private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;} private void skipUnprintable() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;} public boolean hasNext() { skipUnprintable(); return hasNextByte();} public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while(isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } } public static int ni() { return Integer.parseInt( sc.next() ) ;} public static int[] nia( int N ) { int[] res = new int[N]; Arrays.setAll( res , i -> ni() ) ; return res ; } public static void pi( int n ) { pw.println( n ) ; } public static long nl() { return Long.parseLong( sc.next() ) ;} public static void pl( long l ) { pw.println( l ) ; } public static void pd( double d ) { pw.println( d ) ; } public static String ns() { return sc.next() ;} public static String[] nsa( int N ) { String[] res = new String[N]; Arrays.setAll( res , i -> ns() ) ; return res ; } public static void ps( String s ) { pw.println( s ) ; } public static void psb( StringBuilder sb ) { pw.println( sb.toString() ) ; } public static BigDecimal nbd() { return new BigDecimal( sc.next() ) ; } public static void pbd( BigDecimal bd ) { pw.println( bd.toPlainString() ) ; } public static void pr( Object o ) { pw.println( o ) ; } }
ConDefects/ConDefects/Code/abc234_e/Java/33036952
condefects-java_data_671
import java.io.IOException; import java.io.InputStream; import java.util.*; import java.lang.Math; public class Main { static long X; public static void main(String[] args) { FastScanner sc = new FastScanner(); X = sc.nextLong(); String s = String.valueOf(X); int len = s.length(); if (len > 10) { char f = s.charAt(0); if (s.charAt(0) >= s.charAt(1)) { long cur = 0L; for (int i = 0; i < len; i++) { cur = cur * 10 + (long) (f - '0'); } } else { long cur = 0L; if (f == '9') { for (int i = 0; i < len + 1; i++) { cur = cur * 10 + 1L; } } else { for (int i = 0; i < len; i++) { cur = cur * 10 + (long) (f - '0') + 1L; } } } } long ans = 11111111111111111L; for (int d = -9; d < 10; d++) { for (int f = 1; f < 10; f++) { long cur = f; if (cur >= X) { ans = Math.min(ans, cur); } for (int i = 0; i < len + 1; i++) { long next = cur % 10 + d; if (next < 0 || next > 9) break; cur = cur * 10 + next; if (cur >= X) { ans = Math.min(ans, cur); } } } } System.out.println(ans); } } // System.out.println(); // for(int i=0; i<N; i++) // for(int i=0; i<N; i++){ // for(int j=0; j<M; j++){ // // 添字に注意 // } // } // G = new char[N][N]; // for(int i=0; i<N; i++) G[i] = sc.next().toCharArray(); // for(Map.Entry<String, String> entry : m.entrySet()) { // System.out.println(entry.getKey()); // System.out.println(entry.getValue()); // } // TreeMap<Integer, Integer> map = new TreeMap<>(); // static char[] T; // static ArrayList<Integer> l = new ArrayList<>(); // static ArrayList<ArrayList<Integer>> l = new ArrayList<>(); // static LinkedList<Integer> l = new LinkedList<>(); // static TreeSet<Integer> set = new TreeSet<>(); // static HashMap<Integer, Integer> map = new HashMap<>(); // static TreeMap<Integer, Integer> map = new TreeMap<>(); // static char[][] G; // class Pair implements Comparable<Pair>{ // int x; // int y; // public Pair(int a, int b) { // this.x = a ; // this.y = b; // } // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Pair fraction = (Pair) o; // return x == fraction.x && y == fraction.y; // } // @Override // public int hashCode() { // return Objects.hash(x, y); // } // @Override // public int compareTo(Pair o) { // if (this.equals(o)) { // return 0; // } // if (this.x == 0) { // return this.y == -1 ? 1 : -1; // } // if (0 <= this.x * o.x) { // return 0 <= this.x * o.y - this.y * o.x ? 1 : -1; // } // return 0 <= this.x * o.y - this.y * o.x ? -1 : 1; // } // } 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.io.IOException; import java.io.InputStream; import java.util.*; import java.lang.Math; public class Main { static long X; public static void main(String[] args) { FastScanner sc = new FastScanner(); X = sc.nextLong(); String s = String.valueOf(X); int len = s.length(); if (len > 10) { char f = s.charAt(0); if (s.charAt(0) >= s.charAt(1)) { long cur = 0L; for (int i = 0; i < len; i++) { cur = cur * 10 + (long) (f - '0'); } } else { long cur = 0L; if (f == '9') { for (int i = 0; i < len + 1; i++) { cur = cur * 10 + 1L; } } else { for (int i = 0; i < len; i++) { cur = cur * 10 + (long) (f - '0') + 1L; } } } } long ans = Long.MAX_VALUE / 2; for (int d = -9; d < 10; d++) { for (int f = 1; f < 10; f++) { long cur = f; if (cur >= X) { ans = Math.min(ans, cur); } for (int i = 0; i < len + 1; i++) { long next = cur % 10 + d; if (next < 0 || next > 9) break; cur = cur * 10 + next; if (cur >= X) { ans = Math.min(ans, cur); } } } } System.out.println(ans); } } // System.out.println(); // for(int i=0; i<N; i++) // for(int i=0; i<N; i++){ // for(int j=0; j<M; j++){ // // 添字に注意 // } // } // G = new char[N][N]; // for(int i=0; i<N; i++) G[i] = sc.next().toCharArray(); // for(Map.Entry<String, String> entry : m.entrySet()) { // System.out.println(entry.getKey()); // System.out.println(entry.getValue()); // } // TreeMap<Integer, Integer> map = new TreeMap<>(); // static char[] T; // static ArrayList<Integer> l = new ArrayList<>(); // static ArrayList<ArrayList<Integer>> l = new ArrayList<>(); // static LinkedList<Integer> l = new LinkedList<>(); // static TreeSet<Integer> set = new TreeSet<>(); // static HashMap<Integer, Integer> map = new HashMap<>(); // static TreeMap<Integer, Integer> map = new TreeMap<>(); // static char[][] G; // class Pair implements Comparable<Pair>{ // int x; // int y; // public Pair(int a, int b) { // this.x = a ; // this.y = b; // } // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // Pair fraction = (Pair) o; // return x == fraction.x && y == fraction.y; // } // @Override // public int hashCode() { // return Objects.hash(x, y); // } // @Override // public int compareTo(Pair o) { // if (this.equals(o)) { // return 0; // } // if (this.x == 0) { // return this.y == -1 ? 1 : -1; // } // if (0 <= this.x * o.x) { // return 0 <= this.x * o.y - this.y * o.x ? 1 : -1; // } // return 0 <= this.x * o.y - this.y * o.x ? -1 : 1; // } // } 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()); } }
ConDefects/ConDefects/Code/abc234_e/Java/37981967
condefects-java_data_672
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.util.function.BinaryOperator; import java.util.function.Predicate; public class Main { public static void main(String[] args) { Solver.SOLVE(); } } class UnionFind { private int[] roots; public UnionFind(int n){ roots = new int[n]; for (int i = 0; i < n; i++) { roots[i] = i; } } public int root(int x){ if(roots[x] == x){ return x; } return roots[x] = root(roots[x]); } public void unite(int x,int y){ int rx = root(x); int ry = root(y); if(rx == ry){ return; } roots[rx] = ry; } public boolean same(int x,int y){ int rx = root(x); int ry = root(y); return rx == ry; } } class DSU { private int n; private int[] parentOrSize; public DSU(int n) { this.n = n; this.parentOrSize = new int[n]; java.util.Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; return x; } boolean same(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("" + a); return -parentOrSize[leader(a)]; } ArrayList<ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } ArrayList<ArrayList<Integer>> result = new ArrayList<>(n); for (int i = 0; i < n; i++) { result.add(new ArrayList<>(groupSize[i])); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } result.removeIf(ArrayList::isEmpty); return result; } } class PairL implements Comparable<PairL>, Comparator<PairL> { public long x,y; public PairL(long x,long y) { this.x = x; this.y = y; } public void swap(){ long t = x; x = y; y = t; } @Override public int compare(PairL o1, PairL o2) { return o1.compareTo(o2); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairL pairl = (PairL) o; return x == pairl.x && y == pairl.y; } @Override public int hashCode() { return Objects.hash(x, y); } public PairL add(PairL p){ return new PairL(x+p.x,y+p.y); } @Override public int compareTo(PairL o) { return Long.compare(x,o.x); } } class PairI implements Comparable<PairI>, Comparator<PairI> { public int x,y; public PairI(int x,int y) { this.x = x; this.y = y; } public void swap(){ int t = x; x = y; y = t; } @Override public int compare(PairI o1, PairI o2) { if(o1.x == o2.x){ return Integer.compare(o1.y,o2.y); } return Integer.compare(o1.x,o2.x); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairI pairI = (PairI) o; return x == pairI.x && y == pairI.y; } @Override public int hashCode() { return Objects.hash(x, y); } @Override public int compareTo(PairI o) { if(x == o.x){ return Integer.compare(y,o.y); } return Integer.compare(x,o.x); } public PairI add(PairI p){ return new PairI(x+p.x,y+p.y); } public PairI sub(PairI p){ return new PairI(x-p.x,y-p.y); } public PairI addG(PairI p,int h,int w) { int x = this.x + p.x; int y = this.y + p.y; if(0 <= x&&x < w&&0 <= y&&y < h){ return new PairI(x,y); } return null; } } class Dist extends PairI{ int d; public Dist(int x,int y,int d){ super(x,y); this.d = d; } public Dist addG(PairI p,int h,int w) { int x = this.x + p.x; int y = this.y + p.y; if(0 <= x&&x < w&&0 <= y&&y < h){ return new Dist(x,y,d+1); } return null; } } class Tuple implements Comparable<Tuple>{ public int x,y,z; public Tuple(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Tuple three = (Tuple) o; return x == three.x && y == three.y && z == three.z; } @Override public int hashCode() { return Objects.hash(x, y, z); } @Override public int compareTo(Tuple o) { return Integer.compare(z,o.z); } } class Node implements Comparable<Node>{ public int from; public int to; public long d; public Node(int to,long d){ this.to = to; this.d = d; } public Node(int from,int to,long d){ this.to = to; this.from = from; this.d = d; } @Override public int compareTo(Node o) { return Long.compare(d,o.d); } } class PairC{ char a,b; public PairC(char a, char b){ this.a = a; this.b = b; } } class IB{ int i; boolean b; IB(int i,boolean b){ this.i = i; this.b = b; } } class CI{ char c; int i; CI(char c,int i){ this.c = c; this.i = i; } } class Solver { public static final int MOD1 = 1000000007; public static final int MOD9 = 998244353; public static Scanner sc = new Scanner(System.in); public static final int inf = 2000000000; public static final int ninf = -inf; public static final char[] alpha = "abcdefghijklmnopqrstuvwxyz".toCharArray(); public static final char[] ALPHA = "abcdefghijklmnopqrstuvwxyz".toUpperCase().toCharArray(); public static FastScanner fs = new FastScanner(); public static PrintWriter out = new PrintWriter(System.out); public static final PairI[] move = new PairI[]{new PairI(1,0),new PairI(0,1),new PairI(-1,0),new PairI(0,-1)}; public static void solve() { long x = rL(); if(x > 9876543210L){ int deg = degL(x); int top = degN(x,deg-1); int max = 0; for (int i = 0; i < deg; i++) { max = max(max,degN(x,i)); } int ansd = top; if(max > top){ ansd++; } if(ansd == 10){ deg++; ansd = 1; } long ans = ansd; for (int i = 0; i < deg-1; i++) { ans*=10; ans+=ansd; } oL(ans); return; } if(x < 100){ oL(x); return; } boolean first = true; while (true){ int deg = degL(x); int dif = degN(x,deg-1) - degN(x,deg-2); long change = 1; boolean ok = true; for (int i = deg-2; i > 0; i--) { if(degN(x,i) - degN(x,i-1) != dif){ ok = false; change = pow(10,i-1); break; } } if(ok){ oL(x); return; } if(first) { x/=change; x*=change; first = false; } x += change; } } static int degL(long x){ return String.valueOf(x).length(); } static int degN(long x,int d){ x/=pow(10,d); return (int)(x%10); } static long comb(int n,int r){ if(r*2 > n){ r = n-r; } long ans = 1; for (int i = 0; i < r; i++) { ans*=(n-i); ans/=(i+1); } return ans; } static boolean isPalindrome(int a,int b,String s){ int dif = b-a; boolean ok = true; for (int i = 0; i < dif; i++) { if (s.charAt(i + a) != s.charAt(b - i)) { ok = false; break; } } return ok; } static int intValue(char c){ return Integer.parseInt(String.valueOf(c)); } @SuppressWarnings("unchecked") static class SegTree<T>{ T[] data; int size; BinaryOperator<T> op; T e; int inisize; SegTree(T[] a,BinaryOperator<T> op,T e){ size = 1; inisize = a.length; while (size < a.length){ size <<= 1; } this.e = e; this.op = op; data = (T[])new Object[size*2]; Arrays.fill(data,e); System.arraycopy(a,0,data,size,a.length); for (int i = size-1; i > 0; i--) { data[i] = op.apply(data[i*2],data[i*2+1]); } } void update(int i,T x){ if(i < 0) throw new IllegalArgumentException(); i += size; data[i] = x; while (i > 1){ data[i >> 1] = op.apply(data[i],data[i^1]); i >>= 1; } } T query(int l,int r){ if(l < 0) throw new IllegalArgumentException(); if(r < 0) throw new IllegalArgumentException(); T res = e; l += size; r += size; while (l < r){ if((l & 1) == 1) { res = op.apply(res,data[l]); l++; } if((r & 1) == 1){ res = op.apply(res,data[r-1]); } l >>= 1; r >>= 1; } return res; } int maxRight(int l,Predicate<T> pr){ if (!pr.test(e)) { throw new IllegalArgumentException(); } if(l == inisize) return l; l+=size; T sum = e; do { l >>= Integer.numberOfTrailingZeros(l); if (!pr.test(op.apply(sum, data[l]))) { while (l < size) { l = l << 1; if (pr.test(op.apply(sum, data[l]))) { sum = op.apply(sum, data[l]); l++; } } return l - size; } sum = op.apply(sum, data[l]); l++; } while ((l & -l) != l); return inisize; } public int minLeft(int r,Predicate<T> pr) { if (!pr.test(e)) { throw new IllegalArgumentException(); } if (r == 0) { return 0; } r += size; T sum = e; do { r--; while (r > 1 && (r & 1) == 1) { r >>= 1; } if (!pr.test(op.apply(data[r], sum))) { while (r < size) { r = r << 1 | 1; if (pr.test(op.apply(data[r], sum))) { sum = op.apply(data[r], sum); r--; } } return r + 1 - size; } sum = op.apply(data[r], sum); } while ((r & -r) != r); return 0; } } public static int toIntC(char c){ for (int i = 0; i < ALPHA.length; i++) { if(c == ALPHA[i]){ return i+1; } } throw new IllegalArgumentException("not an alphabet"); } public static int toInt(char c){ for (int i = 0; i < alpha.length; i++) { if(c == alpha[i]){ return i+1; } } throw new IllegalArgumentException("not an alphabet"); } public static void reverse(int[] a){ int[] tmp = a.clone(); for (int i = 0; i < a.length; i++) { a[i] = tmp[a.length - 1 - i]; } } public static int[] compress(int[] a){ int[] b = erase(a); Arrays.sort(b); for (int i = 0; i < a.length; i++) { a[i] = lower(b,a[i]); } return a; } public static int lower(int[] a,int x){ int low = 0, high = a.length; int mid; while (low < high) { mid = low + (high - low) / 2; if (x <= a[mid]) { high = mid; } else { low = mid + 1; } } if (low < a.length && a[low] < x) { low++; } return low; } public static int lower(long[] a,long x){ int low = 0, high = a.length; int mid; while (low < high) { mid = low + (high - low) / 2; if (x <= a[mid]) { high = mid; } else { low = mid + 1; } } if (low < a.length && a[low] < x) { low++; } return low; } public static int upper(int[] a,int x){ int low = 0, high = a.length; int mid; while (low < high && low != a.length) { mid = low + (high - low) / 2; if (x >= a[mid]) { low = mid + 1; } else { high = mid; } } return low; } public static int upper(long[] a,long x){ int low = 0, high = a.length; int mid; while (low < high && low != a.length) { mid = low + (high - low) / 2; if (x >= a[mid]) { low = mid + 1; } else { high = mid; } } return low; } public static int[] erase(int[] a){ HashSet<Integer> used = new HashSet<>(); ArrayList<Integer> ans = new ArrayList<>(); for (int i = 0; i < a.length; i++) { if(!used.contains(a[i])){ used.add(a[i]); ans.add(a[i]); } } return convI(ans); } public static int abs(int a){ return Math.abs(a); } public static long abs(long a){ return Math.abs(a); } public static int max(int a,int b){ return Math.max(a,b); } public static int max(int... a){ int max = ninf; for (int i = 0; i < a.length; i++) { max = max(a[i],max); } return max; } public static long max(long a,long b){ return Math.max(a,b); } public static long max(long... a){ long max = Long.MAX_VALUE; for (int i = 0; i < a.length; i++) { max = max(a[i],max); } return max; } public static int min(int a,int b){ return Math.min(a,b); } public static int min(int... a){ int min = inf; for (int i = 0; i < a.length; i++) { min = min(a[i],min); } return min; } public static long min(long a,long b){ return Math.min(a, b); } public static long min(long... a){ long min = inf; for (int i = 0; i < a.length; i++) { min = min(a[i],min); } return min; } public static final class MC { private final int mod; public MC(final int mod) { this.mod = mod; } public long mod(long x) { x %= mod; if (x < 0) { x += mod; } return x; } public long add(final long a, final long b) { return mod(mod(a) + mod(b)); } public long add(final long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = add(ans,a[i]); } return mod(ans); } public long mul(final long a, final long b) { return mod(mod(a) * mod(b)); } public long mul(final long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = mul(ans,a[i]); } return mod(ans); } public long div(final long numerator, final long denominator) { return mod(numerator * inverse(denominator)); } public long power(long base, long exp) { long ret = 1; base %= mod; while (exp > 0) { if ((exp & 1) == 1) { ret = mul(ret, base); } base = mul(base, base); exp >>= 1; } return ret; } public long inverse(final long x) { return power(x, mod - 2); } public long factorial(final int n) { return product(1, n); } public long product(final int start, final int end) { long result = 1; for (int i = start; i <= end; i++) { result *= i; result %= mod; } return result; } public long combination(final int n, int r) { if (r > n) { return 0; } return div(product(n - r + 1, n), factorial(r)); } } public static long pow(long x,long n){ long ans = 1L; long tmp = x; while (true){ if(n < 1L){ break; } if(n % 2L == 1L){ ans*=tmp; } tmp *=tmp; n = n >> 1; } return ans; } public static long modPow(long x,long n,long m){ long ans = 1L; long tmp = x; while (true){ if(n < 1L){ break; } if(n % 2L == 1L){ ans*=tmp; ans%=m; } tmp *=tmp; tmp%=m; n = n >> 1; } return ans; } public static int gcd(int a,int b){ if(b == 0) return a; else return gcd(b,a%b); } public static long gcd(long a,long b){ if(b == 0) return a; else return gcd(b,a%b); } public static int gcd(int... a){ int ans = a[0]; for (int i = 1; i < a.length; i++) { ans = gcd(ans,a[i]); } return ans; } public static long gcd(long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = gcd(ans,a[i]); } return ans; } public static long lcm(int a,int b){ return (long) a / gcd(a, b) * b; } public static long lcm(long a,long b){ return a / gcd(a,b) * b; } public static boolean isPrime(long x){ if(x < 2) return false; else if(x == 2) return true; if(x%2 == 0) return false; for(long i = 3; i*i <= x; i+= 2){ if(x%i == 0) return false; } return true; } public static int rI() { return fs.nextInt(); } public static int[] rIv(int length) { int[] res = new int[length]; for (int i = 0; i < length; i++) { res[i] = fs.nextInt(); } return res; } public static String rS() { return fs.next(); } public static String[] rSv(int length) { String[] res = new String[length]; for (int i = 0; i < length; i++) res[i] = fs.next(); return res; } public static long rL() { return fs.nextLong(); } public static long[] rLv(int length) { long[] res = new long[length]; for (int i = 0; i < length; i++) res[i] = fs.nextLong(); return res; } public static double rD(){ return fs.nextDouble(); } public static double[] rDv(int length){ double[] res = new double[length]; for (int i = 0; i < length; i++) res[i] = rD(); return res; } public static String aiS(int[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String alS(long[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String adS(double[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String acS(char[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String asS(String[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String liS(ArrayList<Integer> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String llS(ArrayList<Long> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String ldS(ArrayList<Double> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String lcS(ArrayList<Character> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String lsS(ArrayList<String> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static void nL(){ out.println(); } public static void oI(int a) { out.println(a); } public static void onI(int a){ out.print(a); } public static void oIv(int[] a) { oS(aiS(a)); } public static void oS(String s) { out.println(s); } public static void onS(String s) { out.print(s); } public static void oSv(String[] a) { oS(asS(a)); } public static void oL(long l) { out.println(l); } public static void onL(long l) { out.print(l); } public static void oLv(long[] a) { oS(alS(a)); } public static void oD(double d){ out.println(d); } public static void onD(double d){ out.print(d); } public static void oDv(double[] d){ oS(adS(d)); } public static void oC(char c){ out.println(c); } public static void onC(char c){ out.print(c); } public static void oCv(char[] c){ oS(acS(c)); } public static void yes_no(boolean yes){ if(yes){ oS("Yes"); return; } oS("No"); } public static int fact(int num) { if (num == 0) { return 1; } else if (num == 1) { return 1; } else if (num < 0) { throw new IllegalArgumentException("factorial should be bigger than 0"); } return num * fact(num - 1); } public static int[] convI(ArrayList<Integer> list) { int[] res = new int[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static long[] convL(ArrayList<Long> list) { long[] res = new long[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static String[] convS(ArrayList<String> list) { String[] res = new String[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static ArrayList<Integer> convI(int[] vec) { ArrayList<Integer> list = new ArrayList<>(); for (int i : vec) list.add(i); return list; } public static ArrayList<Long> convL(long[] vec) { ArrayList<Long> list = new ArrayList<>(); for (long i : vec) list.add(i); return list; } public static ArrayList<String> convS(String[] vec) { return new ArrayList<>(Arrays.asList(vec)); } public static ArrayList<ArrayList<Integer>> permutation(int a) { int[] list = new int[a]; for (int i = 0; i < a; i++) { list[i] = i; } return permutation(list); } public static ArrayList<ArrayList<Integer>> permutation(int[] seed) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); int[] perm = new int[seed.length]; boolean[] used = new boolean[seed.length]; buildPerm(seed, perm, used, 0,res); return res; } private static void buildPerm(int[] seed, int[] perm, boolean[] used, int index,ArrayList<ArrayList<Integer>> res) { if (index == seed.length) { res.add(convI(perm)); return; } for (int i = 0; i < seed.length; i++) { if (used[i]) continue; perm[index] = seed[i]; used[i] = true; buildPerm(seed, perm, used, index + 1,res); used[i] = false; } } public static ArrayList<ArrayList<String>> permutation(String[] seed) { ArrayList<ArrayList<String>> res = new ArrayList<>(); String[] perm = new String[seed.length]; boolean[] used = new boolean[seed.length]; buildPerm(seed, perm, used, 0,res); return res; } private static void buildPerm(String[] seed, String[] perm, boolean[] used, int index,ArrayList<ArrayList<String>> res) { if (index == seed.length) { res.add(convS(perm)); return; } for (int i = 0; i < seed.length; i++) { if (used[i]) continue; perm[index] = seed[i]; used[i] = true; buildPerm(seed, perm, used, index + 1,res); used[i] = false; } } public static void swap(int[] a,int i1,int i2){ int t = a[i1]; a[i1] = a[i2]; a[i2] = t; } public static void swap(char[] a,int i1,int i2){ char t = a[i1]; a[i1] = a[i2]; a[i2] = t; } public static void SOLVE(){ solve(); out.flush(); } } 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.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.util.function.BinaryOperator; import java.util.function.Predicate; public class Main { public static void main(String[] args) { Solver.SOLVE(); } } class UnionFind { private int[] roots; public UnionFind(int n){ roots = new int[n]; for (int i = 0; i < n; i++) { roots[i] = i; } } public int root(int x){ if(roots[x] == x){ return x; } return roots[x] = root(roots[x]); } public void unite(int x,int y){ int rx = root(x); int ry = root(y); if(rx == ry){ return; } roots[rx] = ry; } public boolean same(int x,int y){ int rx = root(x); int ry = root(y); return rx == ry; } } class DSU { private int n; private int[] parentOrSize; public DSU(int n) { this.n = n; this.parentOrSize = new int[n]; java.util.Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; return x; } boolean same(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("" + a); return -parentOrSize[leader(a)]; } ArrayList<ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } ArrayList<ArrayList<Integer>> result = new ArrayList<>(n); for (int i = 0; i < n; i++) { result.add(new ArrayList<>(groupSize[i])); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } result.removeIf(ArrayList::isEmpty); return result; } } class PairL implements Comparable<PairL>, Comparator<PairL> { public long x,y; public PairL(long x,long y) { this.x = x; this.y = y; } public void swap(){ long t = x; x = y; y = t; } @Override public int compare(PairL o1, PairL o2) { return o1.compareTo(o2); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairL pairl = (PairL) o; return x == pairl.x && y == pairl.y; } @Override public int hashCode() { return Objects.hash(x, y); } public PairL add(PairL p){ return new PairL(x+p.x,y+p.y); } @Override public int compareTo(PairL o) { return Long.compare(x,o.x); } } class PairI implements Comparable<PairI>, Comparator<PairI> { public int x,y; public PairI(int x,int y) { this.x = x; this.y = y; } public void swap(){ int t = x; x = y; y = t; } @Override public int compare(PairI o1, PairI o2) { if(o1.x == o2.x){ return Integer.compare(o1.y,o2.y); } return Integer.compare(o1.x,o2.x); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairI pairI = (PairI) o; return x == pairI.x && y == pairI.y; } @Override public int hashCode() { return Objects.hash(x, y); } @Override public int compareTo(PairI o) { if(x == o.x){ return Integer.compare(y,o.y); } return Integer.compare(x,o.x); } public PairI add(PairI p){ return new PairI(x+p.x,y+p.y); } public PairI sub(PairI p){ return new PairI(x-p.x,y-p.y); } public PairI addG(PairI p,int h,int w) { int x = this.x + p.x; int y = this.y + p.y; if(0 <= x&&x < w&&0 <= y&&y < h){ return new PairI(x,y); } return null; } } class Dist extends PairI{ int d; public Dist(int x,int y,int d){ super(x,y); this.d = d; } public Dist addG(PairI p,int h,int w) { int x = this.x + p.x; int y = this.y + p.y; if(0 <= x&&x < w&&0 <= y&&y < h){ return new Dist(x,y,d+1); } return null; } } class Tuple implements Comparable<Tuple>{ public int x,y,z; public Tuple(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Tuple three = (Tuple) o; return x == three.x && y == three.y && z == three.z; } @Override public int hashCode() { return Objects.hash(x, y, z); } @Override public int compareTo(Tuple o) { return Integer.compare(z,o.z); } } class Node implements Comparable<Node>{ public int from; public int to; public long d; public Node(int to,long d){ this.to = to; this.d = d; } public Node(int from,int to,long d){ this.to = to; this.from = from; this.d = d; } @Override public int compareTo(Node o) { return Long.compare(d,o.d); } } class PairC{ char a,b; public PairC(char a, char b){ this.a = a; this.b = b; } } class IB{ int i; boolean b; IB(int i,boolean b){ this.i = i; this.b = b; } } class CI{ char c; int i; CI(char c,int i){ this.c = c; this.i = i; } } class Solver { public static final int MOD1 = 1000000007; public static final int MOD9 = 998244353; public static Scanner sc = new Scanner(System.in); public static final int inf = 2000000000; public static final int ninf = -inf; public static final char[] alpha = "abcdefghijklmnopqrstuvwxyz".toCharArray(); public static final char[] ALPHA = "abcdefghijklmnopqrstuvwxyz".toUpperCase().toCharArray(); public static FastScanner fs = new FastScanner(); public static PrintWriter out = new PrintWriter(System.out); public static final PairI[] move = new PairI[]{new PairI(1,0),new PairI(0,1),new PairI(-1,0),new PairI(0,-1)}; public static void solve() { long x = rL(); if(x > 9876543210L&&false){ int deg = degL(x); int top = degN(x,deg-1); int max = 0; for (int i = 0; i < deg; i++) { max = max(max,degN(x,i)); } int ansd = top; if(max > top){ ansd++; } if(ansd == 10){ deg++; ansd = 1; } long ans = ansd; for (int i = 0; i < deg-1; i++) { ans*=10; ans+=ansd; } oL(ans); return; } if(x < 100){ oL(x); return; } boolean first = true; while (true){ int deg = degL(x); int dif = degN(x,deg-1) - degN(x,deg-2); long change = 1; boolean ok = true; for (int i = deg-2; i > 0; i--) { if(degN(x,i) - degN(x,i-1) != dif){ ok = false; change = pow(10,i-1); break; } } if(ok){ oL(x); return; } if(first) { x/=change; x*=change; first = false; } x += change; } } static int degL(long x){ return String.valueOf(x).length(); } static int degN(long x,int d){ x/=pow(10,d); return (int)(x%10); } static long comb(int n,int r){ if(r*2 > n){ r = n-r; } long ans = 1; for (int i = 0; i < r; i++) { ans*=(n-i); ans/=(i+1); } return ans; } static boolean isPalindrome(int a,int b,String s){ int dif = b-a; boolean ok = true; for (int i = 0; i < dif; i++) { if (s.charAt(i + a) != s.charAt(b - i)) { ok = false; break; } } return ok; } static int intValue(char c){ return Integer.parseInt(String.valueOf(c)); } @SuppressWarnings("unchecked") static class SegTree<T>{ T[] data; int size; BinaryOperator<T> op; T e; int inisize; SegTree(T[] a,BinaryOperator<T> op,T e){ size = 1; inisize = a.length; while (size < a.length){ size <<= 1; } this.e = e; this.op = op; data = (T[])new Object[size*2]; Arrays.fill(data,e); System.arraycopy(a,0,data,size,a.length); for (int i = size-1; i > 0; i--) { data[i] = op.apply(data[i*2],data[i*2+1]); } } void update(int i,T x){ if(i < 0) throw new IllegalArgumentException(); i += size; data[i] = x; while (i > 1){ data[i >> 1] = op.apply(data[i],data[i^1]); i >>= 1; } } T query(int l,int r){ if(l < 0) throw new IllegalArgumentException(); if(r < 0) throw new IllegalArgumentException(); T res = e; l += size; r += size; while (l < r){ if((l & 1) == 1) { res = op.apply(res,data[l]); l++; } if((r & 1) == 1){ res = op.apply(res,data[r-1]); } l >>= 1; r >>= 1; } return res; } int maxRight(int l,Predicate<T> pr){ if (!pr.test(e)) { throw new IllegalArgumentException(); } if(l == inisize) return l; l+=size; T sum = e; do { l >>= Integer.numberOfTrailingZeros(l); if (!pr.test(op.apply(sum, data[l]))) { while (l < size) { l = l << 1; if (pr.test(op.apply(sum, data[l]))) { sum = op.apply(sum, data[l]); l++; } } return l - size; } sum = op.apply(sum, data[l]); l++; } while ((l & -l) != l); return inisize; } public int minLeft(int r,Predicate<T> pr) { if (!pr.test(e)) { throw new IllegalArgumentException(); } if (r == 0) { return 0; } r += size; T sum = e; do { r--; while (r > 1 && (r & 1) == 1) { r >>= 1; } if (!pr.test(op.apply(data[r], sum))) { while (r < size) { r = r << 1 | 1; if (pr.test(op.apply(data[r], sum))) { sum = op.apply(data[r], sum); r--; } } return r + 1 - size; } sum = op.apply(data[r], sum); } while ((r & -r) != r); return 0; } } public static int toIntC(char c){ for (int i = 0; i < ALPHA.length; i++) { if(c == ALPHA[i]){ return i+1; } } throw new IllegalArgumentException("not an alphabet"); } public static int toInt(char c){ for (int i = 0; i < alpha.length; i++) { if(c == alpha[i]){ return i+1; } } throw new IllegalArgumentException("not an alphabet"); } public static void reverse(int[] a){ int[] tmp = a.clone(); for (int i = 0; i < a.length; i++) { a[i] = tmp[a.length - 1 - i]; } } public static int[] compress(int[] a){ int[] b = erase(a); Arrays.sort(b); for (int i = 0; i < a.length; i++) { a[i] = lower(b,a[i]); } return a; } public static int lower(int[] a,int x){ int low = 0, high = a.length; int mid; while (low < high) { mid = low + (high - low) / 2; if (x <= a[mid]) { high = mid; } else { low = mid + 1; } } if (low < a.length && a[low] < x) { low++; } return low; } public static int lower(long[] a,long x){ int low = 0, high = a.length; int mid; while (low < high) { mid = low + (high - low) / 2; if (x <= a[mid]) { high = mid; } else { low = mid + 1; } } if (low < a.length && a[low] < x) { low++; } return low; } public static int upper(int[] a,int x){ int low = 0, high = a.length; int mid; while (low < high && low != a.length) { mid = low + (high - low) / 2; if (x >= a[mid]) { low = mid + 1; } else { high = mid; } } return low; } public static int upper(long[] a,long x){ int low = 0, high = a.length; int mid; while (low < high && low != a.length) { mid = low + (high - low) / 2; if (x >= a[mid]) { low = mid + 1; } else { high = mid; } } return low; } public static int[] erase(int[] a){ HashSet<Integer> used = new HashSet<>(); ArrayList<Integer> ans = new ArrayList<>(); for (int i = 0; i < a.length; i++) { if(!used.contains(a[i])){ used.add(a[i]); ans.add(a[i]); } } return convI(ans); } public static int abs(int a){ return Math.abs(a); } public static long abs(long a){ return Math.abs(a); } public static int max(int a,int b){ return Math.max(a,b); } public static int max(int... a){ int max = ninf; for (int i = 0; i < a.length; i++) { max = max(a[i],max); } return max; } public static long max(long a,long b){ return Math.max(a,b); } public static long max(long... a){ long max = Long.MAX_VALUE; for (int i = 0; i < a.length; i++) { max = max(a[i],max); } return max; } public static int min(int a,int b){ return Math.min(a,b); } public static int min(int... a){ int min = inf; for (int i = 0; i < a.length; i++) { min = min(a[i],min); } return min; } public static long min(long a,long b){ return Math.min(a, b); } public static long min(long... a){ long min = inf; for (int i = 0; i < a.length; i++) { min = min(a[i],min); } return min; } public static final class MC { private final int mod; public MC(final int mod) { this.mod = mod; } public long mod(long x) { x %= mod; if (x < 0) { x += mod; } return x; } public long add(final long a, final long b) { return mod(mod(a) + mod(b)); } public long add(final long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = add(ans,a[i]); } return mod(ans); } public long mul(final long a, final long b) { return mod(mod(a) * mod(b)); } public long mul(final long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = mul(ans,a[i]); } return mod(ans); } public long div(final long numerator, final long denominator) { return mod(numerator * inverse(denominator)); } public long power(long base, long exp) { long ret = 1; base %= mod; while (exp > 0) { if ((exp & 1) == 1) { ret = mul(ret, base); } base = mul(base, base); exp >>= 1; } return ret; } public long inverse(final long x) { return power(x, mod - 2); } public long factorial(final int n) { return product(1, n); } public long product(final int start, final int end) { long result = 1; for (int i = start; i <= end; i++) { result *= i; result %= mod; } return result; } public long combination(final int n, int r) { if (r > n) { return 0; } return div(product(n - r + 1, n), factorial(r)); } } public static long pow(long x,long n){ long ans = 1L; long tmp = x; while (true){ if(n < 1L){ break; } if(n % 2L == 1L){ ans*=tmp; } tmp *=tmp; n = n >> 1; } return ans; } public static long modPow(long x,long n,long m){ long ans = 1L; long tmp = x; while (true){ if(n < 1L){ break; } if(n % 2L == 1L){ ans*=tmp; ans%=m; } tmp *=tmp; tmp%=m; n = n >> 1; } return ans; } public static int gcd(int a,int b){ if(b == 0) return a; else return gcd(b,a%b); } public static long gcd(long a,long b){ if(b == 0) return a; else return gcd(b,a%b); } public static int gcd(int... a){ int ans = a[0]; for (int i = 1; i < a.length; i++) { ans = gcd(ans,a[i]); } return ans; } public static long gcd(long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = gcd(ans,a[i]); } return ans; } public static long lcm(int a,int b){ return (long) a / gcd(a, b) * b; } public static long lcm(long a,long b){ return a / gcd(a,b) * b; } public static boolean isPrime(long x){ if(x < 2) return false; else if(x == 2) return true; if(x%2 == 0) return false; for(long i = 3; i*i <= x; i+= 2){ if(x%i == 0) return false; } return true; } public static int rI() { return fs.nextInt(); } public static int[] rIv(int length) { int[] res = new int[length]; for (int i = 0; i < length; i++) { res[i] = fs.nextInt(); } return res; } public static String rS() { return fs.next(); } public static String[] rSv(int length) { String[] res = new String[length]; for (int i = 0; i < length; i++) res[i] = fs.next(); return res; } public static long rL() { return fs.nextLong(); } public static long[] rLv(int length) { long[] res = new long[length]; for (int i = 0; i < length; i++) res[i] = fs.nextLong(); return res; } public static double rD(){ return fs.nextDouble(); } public static double[] rDv(int length){ double[] res = new double[length]; for (int i = 0; i < length; i++) res[i] = rD(); return res; } public static String aiS(int[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String alS(long[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String adS(double[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String acS(char[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String asS(String[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String liS(ArrayList<Integer> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String llS(ArrayList<Long> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String ldS(ArrayList<Double> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String lcS(ArrayList<Character> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String lsS(ArrayList<String> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static void nL(){ out.println(); } public static void oI(int a) { out.println(a); } public static void onI(int a){ out.print(a); } public static void oIv(int[] a) { oS(aiS(a)); } public static void oS(String s) { out.println(s); } public static void onS(String s) { out.print(s); } public static void oSv(String[] a) { oS(asS(a)); } public static void oL(long l) { out.println(l); } public static void onL(long l) { out.print(l); } public static void oLv(long[] a) { oS(alS(a)); } public static void oD(double d){ out.println(d); } public static void onD(double d){ out.print(d); } public static void oDv(double[] d){ oS(adS(d)); } public static void oC(char c){ out.println(c); } public static void onC(char c){ out.print(c); } public static void oCv(char[] c){ oS(acS(c)); } public static void yes_no(boolean yes){ if(yes){ oS("Yes"); return; } oS("No"); } public static int fact(int num) { if (num == 0) { return 1; } else if (num == 1) { return 1; } else if (num < 0) { throw new IllegalArgumentException("factorial should be bigger than 0"); } return num * fact(num - 1); } public static int[] convI(ArrayList<Integer> list) { int[] res = new int[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static long[] convL(ArrayList<Long> list) { long[] res = new long[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static String[] convS(ArrayList<String> list) { String[] res = new String[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static ArrayList<Integer> convI(int[] vec) { ArrayList<Integer> list = new ArrayList<>(); for (int i : vec) list.add(i); return list; } public static ArrayList<Long> convL(long[] vec) { ArrayList<Long> list = new ArrayList<>(); for (long i : vec) list.add(i); return list; } public static ArrayList<String> convS(String[] vec) { return new ArrayList<>(Arrays.asList(vec)); } public static ArrayList<ArrayList<Integer>> permutation(int a) { int[] list = new int[a]; for (int i = 0; i < a; i++) { list[i] = i; } return permutation(list); } public static ArrayList<ArrayList<Integer>> permutation(int[] seed) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); int[] perm = new int[seed.length]; boolean[] used = new boolean[seed.length]; buildPerm(seed, perm, used, 0,res); return res; } private static void buildPerm(int[] seed, int[] perm, boolean[] used, int index,ArrayList<ArrayList<Integer>> res) { if (index == seed.length) { res.add(convI(perm)); return; } for (int i = 0; i < seed.length; i++) { if (used[i]) continue; perm[index] = seed[i]; used[i] = true; buildPerm(seed, perm, used, index + 1,res); used[i] = false; } } public static ArrayList<ArrayList<String>> permutation(String[] seed) { ArrayList<ArrayList<String>> res = new ArrayList<>(); String[] perm = new String[seed.length]; boolean[] used = new boolean[seed.length]; buildPerm(seed, perm, used, 0,res); return res; } private static void buildPerm(String[] seed, String[] perm, boolean[] used, int index,ArrayList<ArrayList<String>> res) { if (index == seed.length) { res.add(convS(perm)); return; } for (int i = 0; i < seed.length; i++) { if (used[i]) continue; perm[index] = seed[i]; used[i] = true; buildPerm(seed, perm, used, index + 1,res); used[i] = false; } } public static void swap(int[] a,int i1,int i2){ int t = a[i1]; a[i1] = a[i2]; a[i2] = t; } public static void swap(char[] a,int i1,int i2){ char t = a[i1]; a[i1] = a[i2]; a[i2] = t; } public static void SOLVE(){ solve(); out.flush(); } } 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());} }
ConDefects/ConDefects/Code/abc234_e/Java/38857617
condefects-java_data_673
//package atcoder.abc234; import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); //solve(in.nextInt()); solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; 6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial. If getting stuck, skip it and solve other similar level problems. Wait for 1 week then try to solve again. Only read editorial after you solved a problem. 7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already. 8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you rushed to coding! */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a thorough idea steps! 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? */ static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { long x = in.nextLong(), n = x; List<Long> d = new ArrayList<>(); while(n > 0) { d.add(n % 10); n /= 10; } Collections.reverse(d); if(d.size() <= 2) { out.println(x); } else { long ans = Long.MAX_VALUE; for(long startD = 1; startD <= 9; startD++) { for(long diff = -9; diff <= 9; diff++) { long v = compute(startD, diff, d.size()); if(v >= x) { ans = min(ans, v); } } } out.println(ans); } } out.close(); } static long compute(long startD, long diff, int len) { long v = 0; for(int i = 0; i < len; i++) { v = v * 10 + (startD + diff * i); } return v; } static long addWithMod(long x, long y, long mod) { return (x + y) % mod; } static long subtractWithMod(long x, long y, long mod) { return ((x - y) % mod + mod) % mod; } static long multiplyWithMod(long x, long y, long mod) { return x * y % mod; } static long modInv(long x, long mod) { return fastPowMod(x, mod - 2, mod); } static long fastPowMod(long x, long n, long mod) { if (n == 0) return 1; long half = fastPowMod(x, n / 2, mod); if (n % 2 == 0) return half * half % mod; return half * half % mod * x % mod; } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("src/input.in")); out = new PrintWriter(new FileOutputStream("src/output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) g[i] = next(); return g; } List<Integer>[] readUnWeightedGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphOneIndexed(int n, int m) { List<int[]>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } List<Integer>[] readUnWeightedGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphZeroIndexed(int n, int m) { List<int[]>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building an undirected weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildUndirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]][0] = end2[i]; adj[end1[i]][idxForEachNode[end1[i]]][1] = weight[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]][0] = end1[i]; adj[end2[i]][idxForEachNode[end2[i]]][1] = weight[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } /* A more efficient way of building a directed weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildDirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]][0] = to[i]; adj[from[i]][idxForEachNode[from[i]]][1] = weight[i]; idxForEachNode[from[i]]++; } return adj; } } } //package atcoder.abc234; import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); //solve(in.nextInt()); solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; 6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial. If getting stuck, skip it and solve other similar level problems. Wait for 1 week then try to solve again. Only read editorial after you solved a problem. 7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already. 8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you rushed to coding! */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a thorough idea steps! 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? */ static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { long x = in.nextLong(), n = x; List<Long> d = new ArrayList<>(); while(n > 0) { d.add(n % 10); n /= 10; } Collections.reverse(d); if(d.size() <= 2) { out.println(x); } else { long ans = Long.MAX_VALUE; for(long startD = 1; startD <= 9; startD++) { for(long diff = -9; diff <= 9; diff++) { long v = compute(startD, diff, d.size()); if(v >= x) { ans = min(ans, v); } } } out.println(ans); } } out.close(); } static long compute(long startD, long diff, int len) { long v = 0; for(int i = 0; i < len; i++) { long w = startD + diff * i; if(w < 0 || w > 9) return Long.MAX_VALUE; v = v * 10 + (startD + diff * i); } return v; } static long addWithMod(long x, long y, long mod) { return (x + y) % mod; } static long subtractWithMod(long x, long y, long mod) { return ((x - y) % mod + mod) % mod; } static long multiplyWithMod(long x, long y, long mod) { return x * y % mod; } static long modInv(long x, long mod) { return fastPowMod(x, mod - 2, mod); } static long fastPowMod(long x, long n, long mod) { if (n == 0) return 1; long half = fastPowMod(x, n / 2, mod); if (n % 2 == 0) return half * half % mod; return half * half % mod * x % mod; } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("src/input.in")); out = new PrintWriter(new FileOutputStream("src/output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) g[i] = next(); return g; } List<Integer>[] readUnWeightedGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphOneIndexed(int n, int m) { List<int[]>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } List<Integer>[] readUnWeightedGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphZeroIndexed(int n, int m) { List<int[]>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building an undirected weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildUndirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]][0] = end2[i]; adj[end1[i]][idxForEachNode[end1[i]]][1] = weight[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]][0] = end1[i]; adj[end2[i]][idxForEachNode[end2[i]]][1] = weight[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } /* A more efficient way of building a directed weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildDirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]][0] = to[i]; adj[from[i]][idxForEachNode[from[i]]][1] = weight[i]; idxForEachNode[from[i]]++; } return adj; } } }
ConDefects/ConDefects/Code/abc234_e/Java/35557294
condefects-java_data_674
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); final StringTokenizer st = new StringTokenizer(br.readLine()); final int n = Integer.parseInt(st.nextToken()); final int l = Integer.parseInt(st.nextToken()); final StringTokenizer st_a = new StringTokenizer(br.readLine()); final int[] array_a = new int[n]; for (int i = 0; i < n; i++) { array_a[i] = Integer.parseInt(st_a.nextToken()); } br.close(); boolean isOK = true; int remain = l; for (int i = 0; i < n; i++) { if (array_a[i] == 2) { if (remain > 2) { isOK = false; break; } else { remain = Math.max(remain - 3, 0); } } else if (array_a[i] == 1) { remain = Math.max(remain - 2, 0); } } System.out.println(isOK ? "Yes" : "No"); } } import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); final StringTokenizer st = new StringTokenizer(br.readLine()); final int n = Integer.parseInt(st.nextToken()); final int l = Integer.parseInt(st.nextToken()); final StringTokenizer st_a = new StringTokenizer(br.readLine()); final int[] array_a = new int[n]; for (int i = 0; i < n; i++) { array_a[i] = Integer.parseInt(st_a.nextToken()); } br.close(); boolean isOK = true; int remain = l; for (int i = 0; i < n; i++) { if (array_a[i] == 2) { if (remain < 2) { isOK = false; break; } else { remain = Math.max(remain - 3, 0); } } else if (array_a[i] == 1) { remain = Math.max(remain - 2, 0); } } System.out.println(isOK ? "Yes" : "No"); } }
ConDefects/ConDefects/Code/arc152_a/Java/39516583
condefects-java_data_675
import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class Main{ //static final int MAXN = (int)1e6; public static void main(String[] args) throws IOException{ Scanner input = new Scanner(System.in); /*int n = input.nextInt(); int k = input.nextInt(); k = k%4; int[] a = new int[n]; for(int i = 0;i<n;i++){ a[i] = input.nextInt(); } int[] count = new int[n]; int sum = 0; for(int tt = 0;tt<k;tt++){ for(int i = 0;i<n;i++){ count[a[i]-1]++; } for(int i = 0;i<n;i++){ sum+= count[i]; } for(int i = 0;i<n;i++){ a[i] = sum; sum-= count[i]; } } for(int i = 0;i<n;i++){ System.out.print(a[i] + " "); }*/ int n = input.nextInt(); int l = input.nextInt(); int count = 0; int s = 0; for(int i = 0;i<n;i++){ int a = input.nextInt(); if(a == 2){ if(s >= l){ System.out.println("No"); return; } else if(l-s == 2){ s+= 2; } else{ s+= 3; } if(s >= l){ System.out.println("No"); return; } } else{ s+= 2; } } System.out.println("Yes"); } public static int gcd(int a,int b){ if(b == 0){ return a; } return gcd(b,a%b); } /*public static int lcm(int a,int b){ return (a / gcd(a, b)) * b; }*/ } class Pair implements Comparable<Pair>{ int x; int y; Pair(int x,int y){ this.x = x; this.y = y; } @Override public int compareTo(Pair p){ return this.x-p.x; } } import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class Main{ //static final int MAXN = (int)1e6; public static void main(String[] args) throws IOException{ Scanner input = new Scanner(System.in); /*int n = input.nextInt(); int k = input.nextInt(); k = k%4; int[] a = new int[n]; for(int i = 0;i<n;i++){ a[i] = input.nextInt(); } int[] count = new int[n]; int sum = 0; for(int tt = 0;tt<k;tt++){ for(int i = 0;i<n;i++){ count[a[i]-1]++; } for(int i = 0;i<n;i++){ sum+= count[i]; } for(int i = 0;i<n;i++){ a[i] = sum; sum-= count[i]; } } for(int i = 0;i<n;i++){ System.out.print(a[i] + " "); }*/ int n = input.nextInt(); int l = input.nextInt(); int count = 0; int s = 0; for(int i = 0;i<n;i++){ int a = input.nextInt(); if(a == 2){ if(s >= l){ System.out.println("No"); return; } else if(l-s == 2){ s+= 2; } else{ s+= 3; } if(s > l){ System.out.println("No"); return; } } else{ s+= 2; } } System.out.println("Yes"); } public static int gcd(int a,int b){ if(b == 0){ return a; } return gcd(b,a%b); } /*public static int lcm(int a,int b){ return (a / gcd(a, b)) * b; }*/ } class Pair implements Comparable<Pair>{ int x; int y; Pair(int x,int y){ this.x = x; this.y = y; } @Override public int compareTo(Pair p){ return this.x-p.x; } }
ConDefects/ConDefects/Code/arc152_a/Java/37627815
condefects-java_data_676
//package atcoder.arc152; import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); //solve(in.nextInt()); solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; 6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial. If getting stuck, skip it and solve other similar level problems. Wait for 1 week then try to solve again. Only read editorial after you solved a problem. 7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already. 8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you rushed to coding! */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a thorough idea steps! 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? */ static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { int n = in.nextInt(), l = in.nextInt(); int[] a = in.nextIntArrayPrimitive(n); boolean ans = true; int last2 = n - 1; for(; last2 >= 0 && a[last2] == 1; last2--) {} if(last2 >= 0) { int next = 1; for(int i = 0; i < last2; i++) { if(a[i] == 1) { next += 2; } else { if(next + 1 < l) { next += 3; } else { ans = false; break; } } } ans = next - 1 <= l - 2; } out.println(ans ? "Yes" : "No"); } out.close(); } static long addWithMod(long x, long y, long mod) { return (x + y) % mod; } static long subtractWithMod(long x, long y, long mod) { return ((x - y) % mod + mod) % mod; } static long multiplyWithMod(long x, long y, long mod) { return x * y % mod; } static long modInv(long x, long mod) { return fastPowMod(x, mod - 2, mod); } static long fastPowMod(long x, long n, long mod) { if (n == 0) return 1; long half = fastPowMod(x, n / 2, mod); if (n % 2 == 0) return half * half % mod; return half * half % mod * x % mod; } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("src/input.in")); out = new PrintWriter(new FileOutputStream("src/output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) g[i] = next(); return g; } List<Integer>[] readUnWeightedGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphOneIndexed(int n, int m) { List<int[]>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } List<Integer>[] readUnWeightedGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphZeroIndexed(int n, int m) { List<int[]>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building an undirected weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildUndirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]][0] = end2[i]; adj[end1[i]][idxForEachNode[end1[i]]][1] = weight[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]][0] = end1[i]; adj[end2[i]][idxForEachNode[end2[i]]][1] = weight[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } /* A more efficient way of building a directed weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildDirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]][0] = to[i]; adj[from[i]][idxForEachNode[from[i]]][1] = weight[i]; idxForEachNode[from[i]]++; } return adj; } } } //package atcoder.arc152; import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); //solve(in.nextInt()); solve(1); } /* General tips 1. It is ok to fail, but it is not ok to fail for the same mistakes over and over! 2. Train smarter, not harder! 3. If you find an answer and want to return immediately, don't forget to flush before return! */ /* Read before practice 1. Set a timer based on a problem's difficulty level: 45 minutes at your current target practice level; 2. During a problem solving session, focus! Do not switch problems or even worse switch to do something else; 3. If fail to solve within timer limit, read editorials to get as little help as possible to get yourself unblocked; 4. If after reading the entire editorial and other people's code but still can not solve, move this problem to to-do list and re-try in the future. 5. Keep a practice log about new thinking approaches, good tricks, bugs; Review regularly; 6. Also try this new approach suggested by um_nik: Solve with no intention to read editorial. If getting stuck, skip it and solve other similar level problems. Wait for 1 week then try to solve again. Only read editorial after you solved a problem. 7. Remember to also submit in the original problem link (if using gym) so that the 1 v 1 bot knows which problems I have solved already. 8. Form the habit of writing down an implementable solution idea before coding! You've taken enough hits during contests because you rushed to coding! */ /* Read before contests and lockout 1 v 1 Mistakes you've made in the past contests: 1. Tried to solve without going through given test examples -> wasting time on solving a different problem than asked; 2. Rushed to coding without getting a comprehensive sketch of your solution -> implementation bugs and WA; Write down your idea step by step, no need to rush. It is always better to have all the steps considered before hand! Think about all the past contests that you have failed because slow implementation and implementation bugs! This will be greatly reduced if you take your time to get a thorough idea steps! 3. Forgot about possible integer overflow; When stuck: 1. Understand problem statements? Walked through test examples? 2. Take a step back and think about other approaches? 3. Check rank board to see if you can skip to work on a possibly easier problem? 4. If none of the above works, take a guess? */ static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { int n = in.nextInt(), l = in.nextInt(); int[] a = in.nextIntArrayPrimitive(n); boolean ans = true; int last2 = n - 1; for(; last2 >= 0 && a[last2] == 1; last2--) {} if(last2 >= 0) { int next = 1; for(int i = 0; i < last2; i++) { if(a[i] == 1) { next += 2; } else { if(next + 1 < l) { next += 3; } else { ans = false; break; } } } ans &= next - 1 <= l - 2; } out.println(ans ? "Yes" : "No"); } out.close(); } static long addWithMod(long x, long y, long mod) { return (x + y) % mod; } static long subtractWithMod(long x, long y, long mod) { return ((x - y) % mod + mod) % mod; } static long multiplyWithMod(long x, long y, long mod) { return x * y % mod; } static long modInv(long x, long mod) { return fastPowMod(x, mod - 2, mod); } static long fastPowMod(long x, long n, long mod) { if (n == 0) return 1; long half = fastPowMod(x, n / 2, mod); if (n % 2 == 0) return half * half % mod; return half * half % mod * x % mod; } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("src/input.in")); out = new PrintWriter(new FileOutputStream("src/output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } int[] nextIntArrayPrimitiveOneIndexed(int n) { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long[] nextLongArrayPrimitiveOneIndexed(int n) { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } String[] nextStringArray(int n) { String[] g = new String[n]; for (int i = 0; i < n; i++) g[i] = next(); return g; } List<Integer>[] readUnWeightedGraphOneIndexed(int n, int m) { List<Integer>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphOneIndexed(int n, int m) { List<int[]>[] adj = new List[n + 1]; for (int i = 0; i <= n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt(); int v = nextInt(); int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } List<Integer>[] readUnWeightedGraphZeroIndexed(int n, int m) { List<Integer>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; adj[u].add(v); adj[v].add(u); } return adj; } List<int[]>[] readWeightedGraphZeroIndexed(int n, int m) { List<int[]>[] adj = new List[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int w = in.nextInt(); adj[u].add(new int[]{v, w}); adj[v].add(new int[]{u, w}); } return adj; } /* A more efficient way of building an undirected graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildUndirectedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]] = end2[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]] = end1[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building an undirected weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildUndirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; edgeCntForEachNode[v]++; end1[i] = u; end2[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[end1[i]][idxForEachNode[end1[i]]][0] = end2[i]; adj[end1[i]][idxForEachNode[end1[i]]][1] = weight[i]; idxForEachNode[end1[i]]++; adj[end2[i]][idxForEachNode[end2[i]]][0] = end1[i]; adj[end2[i]][idxForEachNode[end2[i]]][1] = weight[i]; idxForEachNode[end2[i]]++; } return adj; } /* A more efficient way of building a directed graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][] buildDirectedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; } int[][] adj = new int[nodeCnt + 1][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]] = to[i]; idxForEachNode[from[i]]++; } return adj; } /* A more efficient way of building a directed weighted graph using int[] instead of ArrayList to store each node's neighboring nodes. 1-indexed. */ int[][][] buildDirectedWeightedGraph(int nodeCnt, int edgeCnt) { int[] from = new int[edgeCnt], to = new int[edgeCnt], weight = new int[edgeCnt]; int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1]; //from u to v: u -> v for (int i = 0; i < edgeCnt; i++) { int u = in.nextInt(), v = in.nextInt(), w = in.nextInt(); edgeCntForEachNode[u]++; from[i] = u; to[i] = v; weight[i] = w; } int[][][] adj = new int[nodeCnt + 1][][]; for (int i = 1; i <= nodeCnt; i++) { adj[i] = new int[edgeCntForEachNode[i]][2]; } for (int i = 0; i < edgeCnt; i++) { adj[from[i]][idxForEachNode[from[i]]][0] = to[i]; adj[from[i]][idxForEachNode[from[i]]][1] = weight[i]; idxForEachNode[from[i]]++; } return adj; } } }
ConDefects/ConDefects/Code/arc152_a/Java/39754102
condefects-java_data_677
import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main { public static void printArray(int[]a) { for(int i=0;i<a.length-1;i++) { System.out.print(a[i]+" "); } System.out.println(a[a.length-1]); } public static long lmax(long a,long b) { if(a<b)return b; else return a; } public static long lmin(long a,long b) { if(a>b)return b; else return a; } public static int max(int a,int b) { if(a<b)return b; else return a; } public static int min(int a,int b) { if(a>b)return b; else return a; } public static int[] setArray(int n) { int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=scan.nextInt(); return a; } public static long[] lsetArray(int n) { long a[]=new long[n]; for(int i=0;i<n;i++)a[i]=scan.nextLong(); return a; } public static int abs(int n) { if(n<0)n*=-1; return n; } public static long labs(long n) { if(n<0)n*=-1; return n; } public static void doublesort(int a[][]){ merge(0,a.length-1,a); return; } public static boolean compare(int a,int b,int[][]origin) { for(int i=0;i<origin[a].length;i++) { if(origin[a][i]>origin[b][i]) { return false; } else if(origin[a][i]<origin[b][i]) { return true; } } return true; } public static void merge(int left,int right,int[][]origin) { if(left==right) { return; } else { int mid=(left+right)/2; merge(left,mid,origin); merge(mid+1,right,origin); int hoge2[][]=new int[right-left+1][origin[0].length]; int itr=0; int leftcount=0; int rightcount=0; while(leftcount<=(mid-left)||rightcount<=(right-(mid+1))) { if(leftcount==mid-left+1) { for(int i=0;i<origin[0].length;i++) { hoge2[itr][i]=origin[mid+rightcount+1][i]; } rightcount++; } else if(rightcount==right-(mid+1)+1) { for(int i=0;i<origin[0].length;i++) { hoge2[itr][i]=origin[left+leftcount][i]; } leftcount++; } else { if(compare(left+leftcount,mid+rightcount+1,origin)) { for(int i=0;i<origin[0].length;i++) { hoge2[itr][i]=origin[left+leftcount][i]; } leftcount++; } else { for(int i=0;i<origin[0].length;i++) { hoge2[itr][i]=origin[mid+rightcount+1][i]; } rightcount++; } } itr++; } for(int i=0;i<(right-left+1);i++) { for(int j=0;j<origin[0].length;j++) { origin[left+i][j]=hoge2[i][j]; } } } } static Scanner scan=new Scanner(System.in); public static void main(String[] args) { int n=scan.nextInt(); int l=scan.nextInt(); int a[]=setArray(n); for(int i=0;i<n;i++) { if(l==2&&a[i]==2) { l-=2; } else if(l>=3) { l-=(a[i]+1); } else if(l<=1&&a[i]==2) { System.out.println("No"); return; } } System.out.println("Yes"); } } import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main { public static void printArray(int[]a) { for(int i=0;i<a.length-1;i++) { System.out.print(a[i]+" "); } System.out.println(a[a.length-1]); } public static long lmax(long a,long b) { if(a<b)return b; else return a; } public static long lmin(long a,long b) { if(a>b)return b; else return a; } public static int max(int a,int b) { if(a<b)return b; else return a; } public static int min(int a,int b) { if(a>b)return b; else return a; } public static int[] setArray(int n) { int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=scan.nextInt(); return a; } public static long[] lsetArray(int n) { long a[]=new long[n]; for(int i=0;i<n;i++)a[i]=scan.nextLong(); return a; } public static int abs(int n) { if(n<0)n*=-1; return n; } public static long labs(long n) { if(n<0)n*=-1; return n; } public static void doublesort(int a[][]){ merge(0,a.length-1,a); return; } public static boolean compare(int a,int b,int[][]origin) { for(int i=0;i<origin[a].length;i++) { if(origin[a][i]>origin[b][i]) { return false; } else if(origin[a][i]<origin[b][i]) { return true; } } return true; } public static void merge(int left,int right,int[][]origin) { if(left==right) { return; } else { int mid=(left+right)/2; merge(left,mid,origin); merge(mid+1,right,origin); int hoge2[][]=new int[right-left+1][origin[0].length]; int itr=0; int leftcount=0; int rightcount=0; while(leftcount<=(mid-left)||rightcount<=(right-(mid+1))) { if(leftcount==mid-left+1) { for(int i=0;i<origin[0].length;i++) { hoge2[itr][i]=origin[mid+rightcount+1][i]; } rightcount++; } else if(rightcount==right-(mid+1)+1) { for(int i=0;i<origin[0].length;i++) { hoge2[itr][i]=origin[left+leftcount][i]; } leftcount++; } else { if(compare(left+leftcount,mid+rightcount+1,origin)) { for(int i=0;i<origin[0].length;i++) { hoge2[itr][i]=origin[left+leftcount][i]; } leftcount++; } else { for(int i=0;i<origin[0].length;i++) { hoge2[itr][i]=origin[mid+rightcount+1][i]; } rightcount++; } } itr++; } for(int i=0;i<(right-left+1);i++) { for(int j=0;j<origin[0].length;j++) { origin[left+i][j]=hoge2[i][j]; } } } } static Scanner scan=new Scanner(System.in); public static void main(String[] args) { int n=scan.nextInt(); int l=scan.nextInt(); int a[]=setArray(n); for(int i=0;i<n;i++) { if(l==2&&a[i]==2) { l-=2; } else if(l>=2) { l-=(a[i]+1); } else if(l<=1&&a[i]==2) { System.out.println("No"); return; } } System.out.println("Yes"); } }
ConDefects/ConDefects/Code/arc152_a/Java/41204854
condefects-java_data_678
import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) { int n = nextInt(); int l = nextInt(); int[] a = nextIntArray(n); int pair = 0; while (l > 0) { int ai = a[pair]; if (ai <= l) { l -= (ai+1); pair++; } else { break; } } for (int i = pair; i < n; i++) { if (a[pair] == 2) { System.out.println("No"); return; } } System.out.println("Yes"); out.flush(); } static PrintWriter out = new PrintWriter(System.out); static Scanner scanner = new Scanner(System.in); static String next() { return scanner.next(); } static int nextInt() { int res = 0; char[] chars = next().toCharArray(); boolean minus = chars[0] == '-'; int start = minus?1:0; for (int i = start; i < chars.length; i++) { res = res*10 + (chars[i]-'0'); } return minus?-res:res; } static long nextLong() { long res = 0; char[] chars = next().toCharArray(); boolean minus = chars[0] == '-'; int start = minus?1:0; for (int i = start; i < chars.length; i++) { res = res*10 + (chars[i]-'0'); } return minus?-res:res; } static double nextDouble() { return Double.parseDouble(next()); } static int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } static long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; i++) { array[i] = nextLong(); } return array; } } import java.io.PrintWriter; import java.util.Scanner; public class Main { public static void main(String[] args) { int n = nextInt(); int l = nextInt(); int[] a = nextIntArray(n); int pair = 0; while (l > 0) { int ai = a[pair]; if (ai <= l) { l -= (ai+1); pair++; } else { break; } } for (int i = pair; i < n; i++) { if (a[i] == 2) { System.out.println("No"); return; } } System.out.println("Yes"); out.flush(); } static PrintWriter out = new PrintWriter(System.out); static Scanner scanner = new Scanner(System.in); static String next() { return scanner.next(); } static int nextInt() { int res = 0; char[] chars = next().toCharArray(); boolean minus = chars[0] == '-'; int start = minus?1:0; for (int i = start; i < chars.length; i++) { res = res*10 + (chars[i]-'0'); } return minus?-res:res; } static long nextLong() { long res = 0; char[] chars = next().toCharArray(); boolean minus = chars[0] == '-'; int start = minus?1:0; for (int i = start; i < chars.length; i++) { res = res*10 + (chars[i]-'0'); } return minus?-res:res; } static double nextDouble() { return Double.parseDouble(next()); } static int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } static long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; i++) { array[i] = nextLong(); } return array; } }
ConDefects/ConDefects/Code/arc152_a/Java/38494892
condefects-java_data_679
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); int N = s.nextInt(); int L = s.nextInt(); int last2Idx = -1; for (int i=1;i<N + 1;++i) { int x = s.nextInt(); if (x == 2) { last2Idx = i; } } if (last2Idx != -1 && 2 * last2Idx >= N + 1) System.out.println("No"); else System.out.println("Yes"); } } import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); int N = s.nextInt(); int L = s.nextInt(); int last2Idx = -1; for (int i=1;i<N + 1;++i) { int x = s.nextInt(); if (x == 2) { last2Idx = i; } } if (last2Idx != -1 && 2 * last2Idx > N + 1) System.out.println("No"); else System.out.println("Yes"); } }
ConDefects/ConDefects/Code/arc152_a/Java/36768229
condefects-java_data_680
import java.io.IOException; import java.io.InputStream; import java.util.NoSuchElementException; public class Main { public static void main(String[] args) { Main o = new Main(); o.solve(); } static final String YES = "Yes"; static final String NO = "No"; public void solve() { FastScanner sc = new FastScanner(System.in); int N = sc.nextInt(); int L = sc.nextInt(); int[] a = new int[N]; for (int i = 0; i < N; i++) { a[i] = sc.nextInt(); } int cur = 0; int pos = 0; while ( cur < N ) { if ( pos == L - 2 && a[cur] == 2 ) { cur++; break; } else if ( pos == L - 1 ) { break; } pos += a[cur++] + 1; } while ( cur < N ) { if ( a[cur++] == 2 ) { System.out.println(NO); return; } } System.out.println(YES); } class FastScanner { private final InputStream in; private final byte[] buf = new byte[1024]; private int ptr = 0; private int buflen = 0; FastScanner( InputStream source ) { this.in = source; } private boolean hasNextByte() { if ( ptr < buflen ) return true; else { ptr = 0; try { buflen = in.read(buf); } catch (IOException e) { e.printStackTrace(); } if ( buflen <= 0 ) return false; } return true; } private int readByte() { if ( hasNextByte() ) return buf[ptr++]; else return -1; } private boolean isPrintableChar( int c ) { return 33 <= c && c <= 126; } private boolean isNumeric( int c ) { return '0' <= c && c <= '9'; } private void skipToNextPrintableChar() { while ( hasNextByte() && !isPrintableChar(buf[ptr]) ) ptr++; } public boolean hasNext() { skipToNextPrintableChar(); return hasNextByte(); } public String next() { if ( !hasNext() ) throw new NoSuchElementException(); StringBuilder ret = new StringBuilder(); int b = readByte(); while ( isPrintableChar(b) ) { ret.appendCodePoint(b); b = readByte(); } return ret.toString(); } public long nextLong() { if ( !hasNext() ) throw new NoSuchElementException(); long ret = 0; int b = readByte(); boolean negative = false; if ( b == '-' ) { negative = true; if ( hasNextByte() ) b = readByte(); } if ( !isNumeric(b) ) throw new NumberFormatException(); while ( true ) { if ( isNumeric(b) ) ret = ret * 10 + b - '0'; else if ( b == -1 || !isPrintableChar(b) ) return negative ? -ret : ret; else throw new NumberFormatException(); b = readByte(); } } public int nextInt() { return (int)nextLong(); } public double nextDouble() { return Double.parseDouble(next()); } } } import java.io.IOException; import java.io.InputStream; import java.util.NoSuchElementException; public class Main { public static void main(String[] args) { Main o = new Main(); o.solve(); } static final String YES = "Yes"; static final String NO = "No"; public void solve() { FastScanner sc = new FastScanner(System.in); int N = sc.nextInt(); int L = sc.nextInt(); int[] a = new int[N]; for (int i = 0; i < N; i++) { a[i] = sc.nextInt(); } int cur = 0; int pos = 0; while ( cur < N ) { if ( pos == L - 2 && a[cur] == 2 ) { cur++; break; } else if ( pos >= L - 1 ) { break; } pos += a[cur++] + 1; } while ( cur < N ) { if ( a[cur++] == 2 ) { System.out.println(NO); return; } } System.out.println(YES); } class FastScanner { private final InputStream in; private final byte[] buf = new byte[1024]; private int ptr = 0; private int buflen = 0; FastScanner( InputStream source ) { this.in = source; } private boolean hasNextByte() { if ( ptr < buflen ) return true; else { ptr = 0; try { buflen = in.read(buf); } catch (IOException e) { e.printStackTrace(); } if ( buflen <= 0 ) return false; } return true; } private int readByte() { if ( hasNextByte() ) return buf[ptr++]; else return -1; } private boolean isPrintableChar( int c ) { return 33 <= c && c <= 126; } private boolean isNumeric( int c ) { return '0' <= c && c <= '9'; } private void skipToNextPrintableChar() { while ( hasNextByte() && !isPrintableChar(buf[ptr]) ) ptr++; } public boolean hasNext() { skipToNextPrintableChar(); return hasNextByte(); } public String next() { if ( !hasNext() ) throw new NoSuchElementException(); StringBuilder ret = new StringBuilder(); int b = readByte(); while ( isPrintableChar(b) ) { ret.appendCodePoint(b); b = readByte(); } return ret.toString(); } public long nextLong() { if ( !hasNext() ) throw new NoSuchElementException(); long ret = 0; int b = readByte(); boolean negative = false; if ( b == '-' ) { negative = true; if ( hasNextByte() ) b = readByte(); } if ( !isNumeric(b) ) throw new NumberFormatException(); while ( true ) { if ( isNumeric(b) ) ret = ret * 10 + b - '0'; else if ( b == -1 || !isPrintableChar(b) ) return negative ? -ret : ret; else throw new NumberFormatException(); b = readByte(); } } public int nextInt() { return (int)nextLong(); } public double nextDouble() { return Double.parseDouble(next()); } } }
ConDefects/ConDefects/Code/arc152_a/Java/36772974
condefects-java_data_681
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int q = sc.nextInt(); int k = sc.nextInt(); sc.nextLine(); long[] dp = new long[k+1]; dp[0] = 1; for(int i=0;i<q;i++) { String[] temp = sc.nextLine().split(" "); int num = Integer.parseInt(temp[1]); if(temp[0].equals("+")) { for(int j=k;j>=1;j--) { if(j-num>=0)dp[j] += dp[j-num]; dp[j]%=998244353; } } else if(temp[0].equals("-")) { for(int j=1;j<=k;j++) { if(j-num>=0)dp[j] -= dp[j-num]; dp[j]%=998244353; } } System.out.println(dp[k]); } } } import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int q = sc.nextInt(); int k = sc.nextInt(); sc.nextLine(); long[] dp = new long[k+1]; dp[0] = 1; for(int i=0;i<q;i++) { String[] temp = sc.nextLine().split(" "); int num = Integer.parseInt(temp[1]); if(temp[0].equals("+")) { for(int j=k;j>=1;j--) { if(j-num>=0)dp[j] += dp[j-num]; dp[j]%=998244353; } } else if(temp[0].equals("-")) { for(int j=1;j<=k;j++) { if(j-num>=0)dp[j]+=(998244353-dp[j-num]); dp[j]%=998244353; } } System.out.println(dp[k]); } } }
ConDefects/ConDefects/Code/abc321_f/Java/49588869
condefects-java_data_682
import java.util.*; import java.io.*; public class Main { static ContestScanner sc = new ContestScanner(System.in); static ContestPrinter pw = new ContestPrinter(System.out); static StringBuilder sb = new StringBuilder(); static long mod = 998244353; public static void main(String[] args) throws Exception { //int T = sc.nextInt(); //for(int i = 0; i < T; i++)solve(); solve(); pw.flush(); } public static void solve() { int Q = sc.nextInt(); int K = sc.nextInt(); long[][] dp = new long[Q+1][K+1]; dp[0][0] = 1; for(int i = 0; i < Q; i++){ char c = sc.next().charAt(0); int k = sc.nextInt(); if(c == '+'){ for(int j = K; j >= 0; j--){ if(j+k <= K){ dp[i+1][j+k] += dp[i][j]; dp[i+1][j+k] %= mod; } dp[i+1][j] += dp[i][j]; dp[i+1][j] %= mod; } }else{ for(int j = 0; j <= K; j++){ dp[i+1][j] += dp[i][j]; if(j+k <= K){ dp[i+1][j+k] -= dp[i+1][j]; dp[i+1][j+k] += mod; dp[i+1][j+k] %= mod; } dp[i+1][j] %= mod; } } pw.println(dp[i+1][K]); } } static class GeekInteger { public static void save_sort(int[] array) { shuffle(array); Arrays.sort(array); } public static int[] shuffle(int[] array) { int n = array.length; Random random = new Random(); for (int i = 0, j; i < n; i++) { j = i + random.nextInt(n - i); int randomElement = array[j]; array[j] = array[i]; array[i] = randomElement; } return array; } public static void save_sort(long[] array) { shuffle(array); Arrays.sort(array); } public static long[] shuffle(long[] array) { int n = array.length; Random random = new Random(); for (int i = 0, j; i < n; i++) { j = i + random.nextInt(n - i); long randomElement = array[j]; array[j] = array[i]; array[i] = randomElement; } return array; } } } /** * 処理は[s, t) の半開区間で指定すること * 例えばtree[0]の値を取得したい場合はgetTotal(0,1)で取得できる。 */ class SegmentTree{ long[] tree; int N; long INF = -(long)1e18; long mod = 998244353; public SegmentTree(int n){ int now = 1; while(now < n){ now *= 2; } this.N = now; this.tree = new long[N*2]; } public void add(int x, long val){ x += (N - 1); tree[x] += val; tree[x] %= mod; while(x > 0) { x = (x - 1) / 2; tree[x] = (tree[2*x+1]+tree[2*x+2])%mod; } } public void set(int x, long val){ x += (N - 1); tree[x] = val; while(x > 0) { x = (x - 1) / 2; tree[x] = Math.max(tree[2*x+1],tree[2*x+2]); } } public long getTotal(int a, int b){ return getTotal(a,b,0,0,N); } public long getTotal(int a, int b, int k, int l, int r){ if(r < 0) r = N; if(r <= a || b <= l) return 0; if(a <= l && r <= b) return tree[k]; long vl = getTotal(a, b, 2*k+1, l, (l+r)/2); long vr = getTotal(a, b, 2*k+2, (l+r)/2, r); return (vl+vr)%mod; } public void printArr(){ for(long v : tree){ System.out.print(v + " "); } System.out.println(); return; } public long getMax(int a, int b) { return getMax(a, b, 0, 0, N); } public long getMax(int a, int b, int k, int l, int r) { if(r < 0) r = N; if(r <= a || b <= l) return -INF; if(a <= l && r <= b) return tree[k]; long vl = getMax(a, b, 2*k+1, l, (l+r)/2); long vr = getMax(a, b, 2*k+2, (l+r)/2, r); return Math.max(vl, vr); } public long getMin(int a, int b) { return getMin(a, b, 0, 0, N); } public long getMin(int a, int b, int k, int l, int r) { if(r < 0) r = N; if(r <= a || b <= l) return 0; if(a <= l && r <= b) return tree[k]; long vl = getMin(a, b, 2*k+1, l, (l+r)/2); long vr = getMin(a, b, 2*k+2, (l+r)/2, r); return Math.min(vl, vr); } public void printArrByTree(){ for(int i = N-1; i < N*2; i++){ System.out.print(tree[i] + " "); } System.out.println(); } } /** * refercence : https://github.com/NASU41/AtCoderLibraryForJava/blob/master/ContestIO/ContestScanner.java */ class ContestScanner { private final java.io.InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public ContestScanner(java.io.InputStream in){ this.in = in; } public ContestScanner(java.io.File file) throws java.io.FileNotFoundException { this(new java.io.BufferedInputStream(new java.io.FileInputStream(file))); } public ContestScanner(){ this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (java.io.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 java.util.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 java.util.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') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit) ); } n = n * 10 + digit; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(int length){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = this.nextInt(); return array; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width){ long[][] mat = new long[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width){ int[][] mat = new int[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width){ double[][] mat = new double[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width){ char[][] mat = new char[height][width]; for(int h=0; h<height; h++){ String s = this.next(); for(int w=0; w<width; w++){ mat[h][w] = s.charAt(w); } } return mat; } } class ContestPrinter extends PrintWriter { public ContestPrinter(PrintStream stream) { super(stream); } public ContestPrinter() { super(System.out); } private static String dtos(double x, int n) { StringBuilder sb = new StringBuilder(); if (x < 0) { sb.append('-'); x = -x; } x += Math.pow(10, -n) / 2; sb.append((long) x); sb.append("."); x -= (long) x; for (int i = 0; i < n; i++) { x *= 10; sb.append((int) x); x -= (int) x; } return sb.toString(); } @Override public void print(float f) { super.print(dtos(f, 20)); } @Override public void println(float f) { super.println(dtos(f, 20)); } @Override public void print(double d) { super.print(dtos(d, 20)); } @Override public void println(double d) { super.println(dtos(d, 20)); } public void printlnArray(String[] array) { for (String i : array) super.println(i); } public void printSpace(Object... o) { int n = o.length - 1; for (int i = 0; i < n; i++) { super.print(o[i]); super.print(" "); } super.println(o[n]); } public void println(Object... o) { int n = o.length - 1; for (int i = 0; i < n; i++) super.print(o[i]); super.println(o[n]); } public void printYN(boolean o) { super.println(o ? "Yes" : "No"); } public void print(Object... o) { int n = o.length - 1; for (int i = 0; i < n; i++) super.print(o[i]); super.print(o[n]); } public void printArray(Object[] array) { int n = array.length - 1; for (int i = 0; i < n; i++) { super.print(array[i]); super.print(" "); } super.println(array[n]); } public void printlnArray(Object[] array) { for (Object i : array) super.println(i); } public void printArray(int[] array, String separator) { int n = array.length - 1; if (n == -1) return; for (int i = 0; i < n; i++) { super.print(array[i]); super.print(separator); } super.println(array[n]); } public void printArray(int[] array) { this.printArray(array, " "); } public void printArray(Integer[] array) { this.printArray(array, " "); } public void printArray(Integer[] array, String separator) { int n = array.length - 1; for (int i = 0; i < n; i++) { super.print(array[i]); super.print(separator); } super.println(array[n]); } public void printlnArray(int[] array) { for (int i : array) super.println(i); } public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map) { int n = array.length - 1; for (int i = 0; i < n; i++) { super.print(map.applyAsInt(array[i])); super.print(separator); } super.println(map.applyAsInt(array[n])); } public void printlnArray(int[] array, java.util.function.IntUnaryOperator map) { for (int i : array) super.println(map.applyAsInt(i)); } public void printlnArray(long[] array, java.util.function.LongUnaryOperator map) { for (long i : array) super.println(map.applyAsLong(i)); } public void printArray(int[] array, java.util.function.IntUnaryOperator map) { this.printArray(array, " ", map); } public void printArray(long[] array, String separator) { int n = array.length - 1; for (int i = 0; i < n; i++) { super.print(array[i]); super.print(separator); } super.println(array[n]); } public void printArray(long[] array) { this.printArray(array, " "); } public void printlnArray(long[] array) { for (long i : array) super.println(i); } public void printArray(double[] array) { printArray(array, " "); } public void printArray(double[] array, String separator) { int n = array.length - 1; for (int i = 0; i < n; i++) { super.print(array[i]); super.print(separator); } super.println(array[n]); } public void printlnArray(double[] array) { for (double i : array) super.println(i); } public void printArray(boolean[] array, String a, String b) { int n = array.length - 1; for (int i = 0; i < n; i++) super.print((array[i] ? a : b) + " "); super.println(array[n] ? a : b); } public void printArray(boolean[] array) { this.printArray(array, "Y", "N"); } public void printArray(char[] array) { for (char c : array) this.print(c); this.println(); } public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map) { int n = array.length - 1; for (int i = 0; i < n; i++) { super.print(map.applyAsLong(array[i])); super.print(separator); } super.println(map.applyAsLong(array[n])); } public void printArray(long[] array, java.util.function.LongUnaryOperator map) { this.printArray(array, " ", map); } public void printArray(ArrayList<?> array) { this.printArray(array, " "); } public void printArray(ArrayList<?> array, String separator) { int n = array.size() - 1; if (n == -1) return; for (int i = 0; i < n; i++) { super.print(array.get(i).toString()); super.print(separator); } super.println(array.get(n).toString()); } public void printlnArray(ArrayList<?> array) { int n = array.size(); for (int i = 0; i < n; i++) super.println(array.get(i).toString()); } public void printlnArray(ArrayList<Integer> array, java.util.function.IntUnaryOperator map) { int n = array.size(); for (int i = 0; i < n; i++) super.println(map.applyAsInt(array.get(i))); } public void printlnArray(ArrayList<Long> array, java.util.function.LongUnaryOperator map) { int n = array.size(); for (int i = 0; i < n; i++) super.println(map.applyAsLong(array.get(i))); } public void printArray(int[][] array) { for (int[] a : array) this.printArray(a); } public void printArray(int[][] array, java.util.function.IntUnaryOperator map) { for (int[] a : array) this.printArray(a, map); } public void printArray(long[][] array) { int n = array.length; if (n == 0) return; int m = array[0].length - 1; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) super.print(array[i][j] + " "); super.println(array[i][m]); } } public void printArray(long[][] array, java.util.function.LongUnaryOperator map) { int n = array.length; if (n == 0) return; int m = array[0].length - 1; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { super.print(map.applyAsLong(array[i][j])); super.print(" "); } super.println(map.applyAsLong(array[i][m])); } } public void printArray(boolean[][] array) { int n = array.length; if (n == 0) return; int m = array[0].length - 1; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) super.print(array[i][j] ? "○ " : "× "); super.println(array[i][m] ? "○" : "×"); } } public void printArray(char[][] array) { int n = array.length; if (n == 0) return; int m = array[0].length; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) super.print(array[i][j]); super.println(); } } } import java.util.*; import java.io.*; public class Main { static ContestScanner sc = new ContestScanner(System.in); static ContestPrinter pw = new ContestPrinter(System.out); static StringBuilder sb = new StringBuilder(); static long mod = 998244353; public static void main(String[] args) throws Exception { //int T = sc.nextInt(); //for(int i = 0; i < T; i++)solve(); solve(); pw.flush(); } public static void solve() { int Q = sc.nextInt(); int K = sc.nextInt(); long[][] dp = new long[Q+1][K+1]; dp[0][0] = 1; for(int i = 0; i < Q; i++){ char c = sc.next().charAt(0); int k = sc.nextInt(); if(c == '+'){ for(int j = K; j >= 0; j--){ if(j+k <= K){ dp[i+1][j+k] += dp[i][j]; dp[i+1][j+k] %= mod; } dp[i+1][j] += dp[i][j]; dp[i+1][j] %= mod; } }else{ for(int j = 0; j <= K; j++){ dp[i+1][j] += dp[i][j]; dp[i+1][j] %= mod; if(j+k <= K){ dp[i+1][j+k] -= dp[i+1][j]; dp[i+1][j+k] += mod; dp[i+1][j+k] %= mod; } } } pw.println(dp[i+1][K]); } } static class GeekInteger { public static void save_sort(int[] array) { shuffle(array); Arrays.sort(array); } public static int[] shuffle(int[] array) { int n = array.length; Random random = new Random(); for (int i = 0, j; i < n; i++) { j = i + random.nextInt(n - i); int randomElement = array[j]; array[j] = array[i]; array[i] = randomElement; } return array; } public static void save_sort(long[] array) { shuffle(array); Arrays.sort(array); } public static long[] shuffle(long[] array) { int n = array.length; Random random = new Random(); for (int i = 0, j; i < n; i++) { j = i + random.nextInt(n - i); long randomElement = array[j]; array[j] = array[i]; array[i] = randomElement; } return array; } } } /** * 処理は[s, t) の半開区間で指定すること * 例えばtree[0]の値を取得したい場合はgetTotal(0,1)で取得できる。 */ class SegmentTree{ long[] tree; int N; long INF = -(long)1e18; long mod = 998244353; public SegmentTree(int n){ int now = 1; while(now < n){ now *= 2; } this.N = now; this.tree = new long[N*2]; } public void add(int x, long val){ x += (N - 1); tree[x] += val; tree[x] %= mod; while(x > 0) { x = (x - 1) / 2; tree[x] = (tree[2*x+1]+tree[2*x+2])%mod; } } public void set(int x, long val){ x += (N - 1); tree[x] = val; while(x > 0) { x = (x - 1) / 2; tree[x] = Math.max(tree[2*x+1],tree[2*x+2]); } } public long getTotal(int a, int b){ return getTotal(a,b,0,0,N); } public long getTotal(int a, int b, int k, int l, int r){ if(r < 0) r = N; if(r <= a || b <= l) return 0; if(a <= l && r <= b) return tree[k]; long vl = getTotal(a, b, 2*k+1, l, (l+r)/2); long vr = getTotal(a, b, 2*k+2, (l+r)/2, r); return (vl+vr)%mod; } public void printArr(){ for(long v : tree){ System.out.print(v + " "); } System.out.println(); return; } public long getMax(int a, int b) { return getMax(a, b, 0, 0, N); } public long getMax(int a, int b, int k, int l, int r) { if(r < 0) r = N; if(r <= a || b <= l) return -INF; if(a <= l && r <= b) return tree[k]; long vl = getMax(a, b, 2*k+1, l, (l+r)/2); long vr = getMax(a, b, 2*k+2, (l+r)/2, r); return Math.max(vl, vr); } public long getMin(int a, int b) { return getMin(a, b, 0, 0, N); } public long getMin(int a, int b, int k, int l, int r) { if(r < 0) r = N; if(r <= a || b <= l) return 0; if(a <= l && r <= b) return tree[k]; long vl = getMin(a, b, 2*k+1, l, (l+r)/2); long vr = getMin(a, b, 2*k+2, (l+r)/2, r); return Math.min(vl, vr); } public void printArrByTree(){ for(int i = N-1; i < N*2; i++){ System.out.print(tree[i] + " "); } System.out.println(); } } /** * refercence : https://github.com/NASU41/AtCoderLibraryForJava/blob/master/ContestIO/ContestScanner.java */ class ContestScanner { private final java.io.InputStream in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private static final long LONG_MAX_TENTHS = 922337203685477580L; private static final int LONG_MAX_LAST_DIGIT = 7; private static final int LONG_MIN_LAST_DIGIT = 8; public ContestScanner(java.io.InputStream in){ this.in = in; } public ContestScanner(java.io.File file) throws java.io.FileNotFoundException { this(new java.io.BufferedInputStream(new java.io.FileInputStream(file))); } public ContestScanner(){ this(System.in); } private boolean hasNextByte() { if (ptr < buflen) { return true; }else{ ptr = 0; try { buflen = in.read(buffer); } catch (java.io.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 java.util.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 java.util.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') { int digit = b - '0'; if (n >= LONG_MAX_TENTHS) { if (n == LONG_MAX_TENTHS) { if (minus) { if (digit <= LONG_MIN_LAST_DIGIT) { n = -n * 10 - digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } else { if (digit <= LONG_MAX_LAST_DIGIT) { n = n * 10 + digit; b = readByte(); if (!isPrintableChar(b)) { return n; } else if (b < '0' || '9' < b) { throw new NumberFormatException( String.format("%d%s... is not number", n, Character.toString(b)) ); } } } } throw new ArithmeticException( String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit) ); } n = n * 10 + digit; }else if(b == -1 || !isPrintableChar(b)){ return minus ? -n : n; }else{ throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public long[] nextLongArray(int length){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = this.nextLong(); return array; } public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map){ long[] array = new long[length]; for(int i=0; i<length; i++) array[i] = map.applyAsLong(this.nextLong()); return array; } public int[] nextIntArray(int length){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = this.nextInt(); return array; } public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map){ int[] array = new int[length]; for(int i=0; i<length; i++) array[i] = map.applyAsInt(this.nextInt()); return array; } public double[] nextDoubleArray(int length){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = this.nextDouble(); return array; } public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map){ double[] array = new double[length]; for(int i=0; i<length; i++) array[i] = map.applyAsDouble(this.nextDouble()); return array; } public long[][] nextLongMatrix(int height, int width){ long[][] mat = new long[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextLong(); } return mat; } public int[][] nextIntMatrix(int height, int width){ int[][] mat = new int[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextInt(); } return mat; } public double[][] nextDoubleMatrix(int height, int width){ double[][] mat = new double[height][width]; for(int h=0; h<height; h++) for(int w=0; w<width; w++){ mat[h][w] = this.nextDouble(); } return mat; } public char[][] nextCharMatrix(int height, int width){ char[][] mat = new char[height][width]; for(int h=0; h<height; h++){ String s = this.next(); for(int w=0; w<width; w++){ mat[h][w] = s.charAt(w); } } return mat; } } class ContestPrinter extends PrintWriter { public ContestPrinter(PrintStream stream) { super(stream); } public ContestPrinter() { super(System.out); } private static String dtos(double x, int n) { StringBuilder sb = new StringBuilder(); if (x < 0) { sb.append('-'); x = -x; } x += Math.pow(10, -n) / 2; sb.append((long) x); sb.append("."); x -= (long) x; for (int i = 0; i < n; i++) { x *= 10; sb.append((int) x); x -= (int) x; } return sb.toString(); } @Override public void print(float f) { super.print(dtos(f, 20)); } @Override public void println(float f) { super.println(dtos(f, 20)); } @Override public void print(double d) { super.print(dtos(d, 20)); } @Override public void println(double d) { super.println(dtos(d, 20)); } public void printlnArray(String[] array) { for (String i : array) super.println(i); } public void printSpace(Object... o) { int n = o.length - 1; for (int i = 0; i < n; i++) { super.print(o[i]); super.print(" "); } super.println(o[n]); } public void println(Object... o) { int n = o.length - 1; for (int i = 0; i < n; i++) super.print(o[i]); super.println(o[n]); } public void printYN(boolean o) { super.println(o ? "Yes" : "No"); } public void print(Object... o) { int n = o.length - 1; for (int i = 0; i < n; i++) super.print(o[i]); super.print(o[n]); } public void printArray(Object[] array) { int n = array.length - 1; for (int i = 0; i < n; i++) { super.print(array[i]); super.print(" "); } super.println(array[n]); } public void printlnArray(Object[] array) { for (Object i : array) super.println(i); } public void printArray(int[] array, String separator) { int n = array.length - 1; if (n == -1) return; for (int i = 0; i < n; i++) { super.print(array[i]); super.print(separator); } super.println(array[n]); } public void printArray(int[] array) { this.printArray(array, " "); } public void printArray(Integer[] array) { this.printArray(array, " "); } public void printArray(Integer[] array, String separator) { int n = array.length - 1; for (int i = 0; i < n; i++) { super.print(array[i]); super.print(separator); } super.println(array[n]); } public void printlnArray(int[] array) { for (int i : array) super.println(i); } public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map) { int n = array.length - 1; for (int i = 0; i < n; i++) { super.print(map.applyAsInt(array[i])); super.print(separator); } super.println(map.applyAsInt(array[n])); } public void printlnArray(int[] array, java.util.function.IntUnaryOperator map) { for (int i : array) super.println(map.applyAsInt(i)); } public void printlnArray(long[] array, java.util.function.LongUnaryOperator map) { for (long i : array) super.println(map.applyAsLong(i)); } public void printArray(int[] array, java.util.function.IntUnaryOperator map) { this.printArray(array, " ", map); } public void printArray(long[] array, String separator) { int n = array.length - 1; for (int i = 0; i < n; i++) { super.print(array[i]); super.print(separator); } super.println(array[n]); } public void printArray(long[] array) { this.printArray(array, " "); } public void printlnArray(long[] array) { for (long i : array) super.println(i); } public void printArray(double[] array) { printArray(array, " "); } public void printArray(double[] array, String separator) { int n = array.length - 1; for (int i = 0; i < n; i++) { super.print(array[i]); super.print(separator); } super.println(array[n]); } public void printlnArray(double[] array) { for (double i : array) super.println(i); } public void printArray(boolean[] array, String a, String b) { int n = array.length - 1; for (int i = 0; i < n; i++) super.print((array[i] ? a : b) + " "); super.println(array[n] ? a : b); } public void printArray(boolean[] array) { this.printArray(array, "Y", "N"); } public void printArray(char[] array) { for (char c : array) this.print(c); this.println(); } public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map) { int n = array.length - 1; for (int i = 0; i < n; i++) { super.print(map.applyAsLong(array[i])); super.print(separator); } super.println(map.applyAsLong(array[n])); } public void printArray(long[] array, java.util.function.LongUnaryOperator map) { this.printArray(array, " ", map); } public void printArray(ArrayList<?> array) { this.printArray(array, " "); } public void printArray(ArrayList<?> array, String separator) { int n = array.size() - 1; if (n == -1) return; for (int i = 0; i < n; i++) { super.print(array.get(i).toString()); super.print(separator); } super.println(array.get(n).toString()); } public void printlnArray(ArrayList<?> array) { int n = array.size(); for (int i = 0; i < n; i++) super.println(array.get(i).toString()); } public void printlnArray(ArrayList<Integer> array, java.util.function.IntUnaryOperator map) { int n = array.size(); for (int i = 0; i < n; i++) super.println(map.applyAsInt(array.get(i))); } public void printlnArray(ArrayList<Long> array, java.util.function.LongUnaryOperator map) { int n = array.size(); for (int i = 0; i < n; i++) super.println(map.applyAsLong(array.get(i))); } public void printArray(int[][] array) { for (int[] a : array) this.printArray(a); } public void printArray(int[][] array, java.util.function.IntUnaryOperator map) { for (int[] a : array) this.printArray(a, map); } public void printArray(long[][] array) { int n = array.length; if (n == 0) return; int m = array[0].length - 1; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) super.print(array[i][j] + " "); super.println(array[i][m]); } } public void printArray(long[][] array, java.util.function.LongUnaryOperator map) { int n = array.length; if (n == 0) return; int m = array[0].length - 1; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { super.print(map.applyAsLong(array[i][j])); super.print(" "); } super.println(map.applyAsLong(array[i][m])); } } public void printArray(boolean[][] array) { int n = array.length; if (n == 0) return; int m = array[0].length - 1; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) super.print(array[i][j] ? "○ " : "× "); super.println(array[i][m] ? "○" : "×"); } } public void printArray(char[][] array) { int n = array.length; if (n == 0) return; int m = array[0].length; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) super.print(array[i][j]); super.println(); } } }
ConDefects/ConDefects/Code/abc321_f/Java/45888232
condefects-java_data_683
import java.util.*; class Main { public static void main(String[] args) { final int mod = 998244353; Scanner scan = new Scanner(System.in); int Q = scan.nextInt(); int K = scan.nextInt(); long[] dp = new long[K + 1]; dp[0] = 1; while (Q-- > 0) { String op = scan.next(); int x = scan.nextInt(); if (op.equals("+")) { for (int i = K;i >= x;i --) dp[i] = (dp[i] + dp[i - x]) % mod; } else { for (int i = x;i <= K;i ++) dp[i] = (dp[i] - dp[i - x]) % mod; } System.out.println(dp[K]); } } } import java.util.*; class Main { public static void main(String[] args) { final int mod = 998244353; Scanner scan = new Scanner(System.in); int Q = scan.nextInt(); int K = scan.nextInt(); long[] dp = new long[K + 1]; dp[0] = 1; while (Q-- > 0) { String op = scan.next(); int x = scan.nextInt(); if (op.equals("+")) { for (int i = K;i >= x;i --) dp[i] = (dp[i] + dp[i - x]) % mod; } else { for (int i = x;i <= K;i ++) dp[i] = (dp[i] - dp[i - x] + mod) % mod; } System.out.println(dp[K]); } } }
ConDefects/ConDefects/Code/abc321_f/Java/46005538
condefects-java_data_684
import java.util.*; import java.io.*; public class Main { private static final int MOD = 998244353; public static void main(String[] args) throws IOException{ BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(r.readLine()); int q = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int[] sums = new int[k + 1]; sums[0] = 1; for (int i = 0; i < q; i++) { st = new StringTokenizer(r.readLine()); char c = st.nextToken().charAt(0); int change = Integer.parseInt(st.nextToken()); if(c == '-'){ for (int j = change; j <= k; j++) { if(sums[j - change] > 0){ sums[j] = (sums[j] - sums[j - change])%MOD; } } } else{ for (int j = k; j >= change; j--) { sums[j] = (sums[j] + sums[j - change])%MOD; } } pw.println(sums[k]); } pw.close(); } } import java.util.*; import java.io.*; public class Main { private static final int MOD = 998244353; public static void main(String[] args) throws IOException{ BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(r.readLine()); int q = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int[] sums = new int[k + 1]; sums[0] = 1; for (int i = 0; i < q; i++) { st = new StringTokenizer(r.readLine()); char c = st.nextToken().charAt(0); int change = Integer.parseInt(st.nextToken()); if(c == '-'){ for (int j = change; j <= k; j++) { if(sums[j - change] > 0){ sums[j] = (sums[j] - sums[j - change] + MOD)%MOD; } } } else{ for (int j = k; j >= change; j--) { sums[j] = (sums[j] + sums[j - change])%MOD; } } pw.println(sums[k]); } pw.close(); } }
ConDefects/ConDefects/Code/abc321_f/Java/54212746
condefects-java_data_685
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.util.function.IntUnaryOperator; import java.util.function.LongUnaryOperator; import java.util.stream.Collectors; public class Main { static In in = new In(); static Out out = new Out(); static final long inf = 0x1fffffffffffffffL; static final int iinf = 0x3fffffff; static final double eps = 1e-9; static long mod = 1000000007; List<IntPair> list; void solve() { int n = in.nextInt(); list = new ArrayList<>(); for (int i = 0; i < n; i++) { int x = in.nextInt(); int y = in.nextInt(); list.add(new IntPair(x + y, x - y)); } list.sort(Comparator.<IntPair>comparingInt(p -> p.second).thenComparingInt(p -> p.first)); WaveletMatrix<IntPair> wm = new WaveletMatrix<>(list); int q = in.nextInt(); for (int i = 0; i < q; i++) { int a = in.nextInt(); int b = in.nextInt(); int c = a + b; int d = a - b; int k = in.nextInt(); int left = 0; int right = 500000; while (right - left > 1) { int mid = (left + right) / 2; int ll = lowerBound(list, d - mid); int rr = upperBound(list, d + mid); int count = 0; if (ll < rr) { count = wm.rangeFreq(new IntPair(c - mid, -iinf), new IntPair(c + mid + 1, -iinf), ll, rr); } if (count >= k) { right = mid; } else { left = mid; } } out.println(right); } } int lowerBound(List<IntPair> list, int value) { int left = -1; int right = list.size(); while (right - left > 1) { int mid = (left + right) / 2; if (list.get(mid).second < value) { left = mid; } else { right = mid; } } return right; } int upperBound(List<IntPair> list, int value) { int left = -1; int right = list.size(); while (right - left > 1) { int mid = (left + right) / 2; if (list.get(mid).second <= value) { left = mid; } else { right = mid; } } return right; } class IntPair implements Comparable<IntPair> { int first; int second; IntPair(int first, int second) { this.first = first; this.second = second; } @Override public boolean equals(Object o) { if (!(o instanceof IntPair)) { return false; } IntPair that = (IntPair)o; return first == that.first && second == that.second; } @Override public int hashCode() { return first * 31 + second; } @Override public int compareTo(IntPair o) { return first == o.first ? Integer.compare(second, o.second) : Integer.compare(first, o.first); } @Override public String toString() { return String.format("[%d, %d]", first, second); } } class BitVector { private static final int CHUNK_WIDTH = 256; private static final int BLOCK_WIDTH = 32; private static final int BLOCK_PER_CHUNK = CHUNK_WIDTH / BLOCK_WIDTH; private final int length; private final int[] bit; private final byte[] blocks; private final int[] chunk; private boolean isBuilt; BitVector(int nbits) { this.length = nbits; this.bit = new int[nbits / BLOCK_WIDTH + 1]; this.blocks = new byte[nbits / BLOCK_WIDTH + 1]; this.chunk = new int[nbits / CHUNK_WIDTH + 1]; } void flip(int bitIndex) { int blockPos = bitIndex / BLOCK_WIDTH; int offset = bitIndex % BLOCK_WIDTH; bit[blockPos] ^= 1 << offset; } void set(int bitIndex) { int blockPos = bitIndex / BLOCK_WIDTH; int offset = bitIndex % BLOCK_WIDTH; bit[blockPos] |= 1 << offset; } void clear(int bitIndex) { int blockPos = bitIndex / BLOCK_WIDTH; int offset = bitIndex % BLOCK_WIDTH; bit[blockPos] &= ~(1 << offset); } int get(int bitIndex) { int blockPos = bitIndex / BLOCK_WIDTH; int offset = bitIndex % BLOCK_WIDTH; return bit[blockPos] >> offset & 1; } void build() { int acc = 0; for (int i = 0; i <= length / BLOCK_WIDTH; i++) { if (i % BLOCK_PER_CHUNK == 0) { chunk[i / BLOCK_PER_CHUNK] = acc; } blocks[i] = (byte)(acc - chunk[i / BLOCK_PER_CHUNK]); acc += Integer.bitCount(bit[i]); } this.isBuilt = true; } int rank(int b, int left, int right) { return b == 0 ? rankZero(left, right) : rankOne(left, right); } int rank(int b, int k) { return b == 0 ? rankZero(k) : rankOne(k); } int rankZero(int left, int right) { return rankZero(right) - rankZero(left); } int rankZero(int bitIndex) { return bitIndex - rankOne(bitIndex); } int rankOne(int left, int right) { return rankOne(right) - rankOne(left); } int rankOne(int bitIndex) { checkBuilt(); int chunkPos = bitIndex / CHUNK_WIDTH; int blockPos = bitIndex / BLOCK_WIDTH; int offset = bitIndex % BLOCK_WIDTH; int masked = bit[blockPos] & ((1 << offset) - 1); return chunk[chunkPos] + Byte.toUnsignedInt(blocks[blockPos]) + Integer.bitCount(masked); } int select(int b, int k) { return b == 0 ? selectZero(k) : selectOne(k); } int select(int b, int k, int left) { return b == 0 ? selectZero(k, left) : selectOne(k, left); } int selectZero(int k, int left) { return selectZero(k + rankZero(left)); } int selectZero(int k) { checkBuilt(); if (rankZero(length) <= k) { return -1; } int left = 0; int right = length; while (right - left > 1) { int mid = (left + right) / 2; if (rankZero(mid) <= k) { left = mid; } else { right = mid; } } return left; } int selectOne(int k, int left) { return selectOne(k + rankOne(left)); } int selectOne(int k) { checkBuilt(); if (rankOne(length) <= k) { return -1; } int left = 0; int right = length; while (right - left > 1) { int mid = (left + right) / 2; if (rankOne(mid) <= k) { left = mid; } else { right = mid; } } return left; } int length() { return length; } @Override public String toString() { BitSet bitSet = new BitSet(length); for (int i = 0; i < length; i++) { bitSet.set(i, get(i) == 1); } return bitSet.toString(); } private void checkBuilt() { if (!isBuilt) { throw new IllegalStateException("bit vector is not built"); } } } class Pair<F, S> { F first; S second; Pair(F first, S second) { this.first = first; this.second = second; } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) { return false; } Pair<?, ?> that = (Pair<?, ?>)o; return Objects.equals(first, that.first) && Objects.equals(second, that.second); } @Override public int hashCode() { return Objects.hash(first, second); } @Override public String toString() { return String.format("[%s, %s]", first, second); } } class WaveletMatrix<T extends Comparable<T>> { private final int n; private final int m; private final int bitLen; private final int[] mids; private final List<BitVector> bitVectors = new ArrayList<>(); private final List<T> values = new ArrayList<>(); WaveletMatrix(List<T> list) { this.n = list.size(); TreeMap<T, Integer> map = new TreeMap<>(); for (T t : list) { map.put(t, 0); } int size = 0; for (Map.Entry<T, Integer> entry : map.entrySet()) { values.add(entry.getKey()); entry.setValue(size); size++; } this.m = size; this.bitLen = Integer.bitCount(Integer.highestOneBit(m * 2 - 1) - 1); this.mids = new int[bitLen]; int[] dataCurrent = new int[n]; int[] dataNext = new int[n]; for (int i = 0; i < n; i++) { dataCurrent[i] = map.get(list.get(i)); } for (int bit = 0; bit < bitLen; bit++) { bitVectors.add(new BitVector(n)); int pos = 0; for (int i = 0; i < n; i++) { if ((dataCurrent[i] >> (bitLen - bit - 1) & 1) == 0) { dataNext[pos++] = dataCurrent[i]; } } mids[bit] = pos; for (int i = 0; i < n; i++) { if ((dataCurrent[i] >> (bitLen - bit - 1) & 1) == 1) { bitVectors.get(bit).set(i); dataNext[pos++] = dataCurrent[i]; } } bitVectors.get(bit).build(); int[] temp = dataCurrent; dataCurrent = dataNext; dataNext = temp; } } // k 番目の値 T get(int k) { rangeCheck(k, 0, n); return get0(k); } // [left, right) で最小の値 T min() { return values.get(0); } T min(int left, int right) { rangeCheck(left, right); return kthMin(0, left, right); } // [left, right) で最大の値 T max() { return values.get(m - 1); } T max(int left, int right) { rangeCheck(left, right); return kthMax(0, left, right); } // [left, right) の value の個数 int rank(T value) { return rank(value, 0, n); } int rank(T value, int left, int right) { rangeCheck(left, right); return rankAll(value, left, right).rank; } // [left, right) の value に対して 等しい/小さい/大きい 値の個数 RankResult rankAll(T value) { return rankAll(value, 0, n); } RankResult rankAll(T value, int left, int right) { rangeCheck(left, right); return rankAll0(value, left, right); } // [left, right) の k 番目の value の位置 int select(T value, int k) { rangeCheck(k, 0, n); return select0(value, k); } int select(T value, int k, int left, int right) { rangeCheck(k, 0, n); rangeCheck(k, left, right); int prev = left == 0 ? 0 : rank(value, 0, left); int select = select0(value, prev + k); return select < right ? select : -1; } // [left, right) の k 番目に小さい値 T kthMin(int k) { rangeCheck(k, 0, n); return kthMin(k, 0, n); } T kthMin(int k, int left, int right) { rangeCheck(k, 0, right - left); return kthMin0(k, left, right); } // [left, right) の k 番目に大きい値 T kthMax(int k) { rangeCheck(k, 0, n); return kthMax(k, 0, n); } T kthMax(int k, int left, int right) { rangeCheck(k, 0, right - left); return kthMin(right - left - 1 - k, left, right); } // [left, right) の k 番目に小さい値のうち最も小さい index int kthMinIndex(int k) { rangeCheck(k, 0, n); return kthMinIndex(k, 0, n); } int kthMinIndex(int k, int left, int right) { rangeCheck(k, 0, right - left); return select(kthMin0(k, left, right), 0, left, right); } // [left, right) の k 番目に大きい値のうち最も小さい index int kthMaxIndex(int k) { return kthMaxIndex(k, 0, n); } int kthMaxIndex(int k, int left, int right) { rangeCheck(k, 0, right - left); return select(kthMax(k, left, right), 0, left, right); } // [left, right) で値が [a, b) 内のものの個数 int rangeFreq(T a, T b) { return rankAll(b).rankLessThan - rankAll(a).rankLessThan; } int rangeFreq(T a, T b, int left, int right) { rangeCheck(left, right); return rankAll(b, left, right).rankLessThan - rankAll(a, left, right).rankLessThan; } // [left, right) で値が higher より小さく最大のもの(存在しない場合null) T prevValue(T higher) { int lower = lower(higher); return lower == -1 ? null : values.get(lower); } T prevValue(T higher, int left, int right) { rangeCheck(left, right); int count = rankAll(higher, left, right).rankLessThan; return count == 0 ? null : kthMin(count - 1, left, right); } // [left, right) で値が lower より大きく最小のもの(存在しない場合null) T nextValue(T lower) { int higher = higher(lower); return higher == m ? null : values.get(higher); } T nextValue(T lower, int left, int right) { rangeCheck(left, right); int count = rankAll(lower, left, right).rankMoreThan; return count == 0 ? null : kthMax(count - 1, left, right); } // [left, right) で出現頻度が多い順に k 個の値と頻度、出現頻度が同じ場合値が小さいほうから List<Pair<T, Integer>> topK(int k) { return topK(k, 0, n); } List<Pair<T, Integer>> topK(int k, int left, int right) { rangeCheck(left, right); rangeCheck(k, 0, n + 1); return topK0(k, left, right); } // [left, right) で値の小さい順に k 個の値と頻度 List<Pair<T, Integer>> minK(int k) { return minK(k, 0, n); } List<Pair<T, Integer>> minK(int k, int left, int right) { rangeCheck(left, right); rangeCheck(k, 0, n + 1); return minK0(k, left, right); } // [left, right) で値の大きい順に k 個の値と頻度 List<Pair<T, Integer>> maxK(int k) { return maxK(k, 0, n); } List<Pair<T, Integer>> maxK(int k, int left, int right) { rangeCheck(left, right); rangeCheck(k, 0, n + 1); return maxK0(k, left, right); } // [left, right) で値が [a, b) 内のものの値と頻度、値の昇順 List<Pair<T, Integer>> rangeList(T a, T b) { return rangeList(a, b, 0, n); } List<Pair<T, Integer>> rangeList(T a, T b, int left, int right) { rangeCheck(left, right); return rangeList0(a, b, left, right); } // [left1, right1) と [left2, right2) に共通して出現するものの値と頻度、値の昇順 List<IntersectResult> intersect(int left1, int right1, int left2, int right2) { rangeCheck(left1, right1); rangeCheck(left2, right2); return intersect0(left1, right1, left2, right2); } private T get0(int k) { int index = 0; for (int bit = 0; bit < bitLen; bit++) { int dir = bitVectors.get(bit).get(k); index = index << 1 | dir; k = bitVectors.get(bit).rank(dir, k) + dir * mids[bit]; } return values.get(index); } private RankResult rankAll0(T value, int left, int right) { RankResult result = new RankResult(); int floor = floor(value); if (floor == -1) { result.rankMoreThan = right - left; return result; } for (int bit = 0; bit < bitLen; bit++) { int dir = floor >> (bitLen - bit - 1) & 1; int leftCount = bitVectors.get(bit).rank(dir, left); int rightCount = bitVectors.get(bit).rank(dir, right); if (dir == 1) { result.rankLessThan += (right - left) - (rightCount - leftCount); } else { result.rankMoreThan += (right - left) - (rightCount - leftCount); } left = leftCount + dir * mids[bit]; right = rightCount + dir * mids[bit]; } result.rank = right - left; if (values.get(floor).compareTo(value) != 0) { result.rankLessThan += result.rank; result.rank = 0; } return result; } private int select0(T value, int k) { int id = getId(value); if (id == -1) { return -1; } int[] lefts = new int[bitLen]; int[] rights = new int[bitLen]; int left = 0; int right = n; for (int bit = 0; bit < bitLen; bit++) { lefts[bit] = left; rights[bit] = right; int dir = id >> (bitLen - bit - 1) & 1; left = bitVectors.get(bit).rank(dir, left) + dir * mids[bit]; right = bitVectors.get(bit).rank(dir, right) + dir * mids[bit]; } for (int bit = bitLen - 1; bit >= 0; bit--) { int dir = id >> (bitLen - bit - 1) & 1; k = bitVectors.get(bit).select(dir, k, lefts[bit]); if (k < 0 || rights[bit] <= k) { return -1; } k -= lefts[bit]; } return k; } private T kthMin0(int k, int left, int right) { int id = 0; for (int bit = 0; bit < bitLen; bit++) { int count = bitVectors.get(bit).rankZero(left, right); int dir = k >= count ? 1 : 0; id = id << 1 | dir; if (dir == 1) { k -= count; } left = bitVectors.get(bit).rank(dir, left) + dir * mids[bit]; right = bitVectors.get(bit).rank(dir, right) + dir * mids[bit]; } return values.get(id); } private List<Pair<T, Integer>> topK0(int k, int left, int right) { List<Pair<T, Integer>> result = new ArrayList<>(); PriorityQueue<Node> queue = new PriorityQueue<>(); queue.add(new Node(left, right, 0, 0)); while (!queue.isEmpty() && result.size() < k) { Node node = queue.poll(); if (node.depth == bitLen) { result.add(new Pair<>(values.get(node.value), node.right - node.left)); continue; } int leftZero = bitVectors.get(node.depth).rankZero(node.left); int rightZero = bitVectors.get(node.depth).rankZero(node.right); if (leftZero < rightZero) { queue.add(new Node(leftZero, rightZero, node.depth + 1, node.value)); } int leftOne = node.left - leftZero + mids[node.depth]; int rightOne = node.right - rightZero + mids[node.depth]; if (leftOne < rightOne) { queue.add(new Node(leftOne, rightOne, node.depth + 1, node.value | (1 << (bitLen - node.depth - 1)))); } } return result; } private List<Pair<T, Integer>> minK0(int k, int left, int right) { List<Pair<T, Integer>> result = new ArrayList<>(); Deque<Node> deque = new ArrayDeque<>(); deque.addLast(new Node(left, right, 0, 0)); while (!deque.isEmpty() && result.size() < k) { Node node = deque.pollLast(); if (node.depth == bitLen) { result.add(new Pair<>(values.get(node.value), node.right - node.left)); continue; } int leftZero = bitVectors.get(node.depth).rankZero(node.left); int rightZero = bitVectors.get(node.depth).rankZero(node.right); if (leftZero < rightZero) { deque.addLast(new Node(leftZero, rightZero, node.depth + 1, node.value)); } int leftOne = node.left - leftZero + mids[node.depth]; int rightOne = node.right - rightZero + mids[node.depth]; if (leftOne < rightOne) { deque.addLast(new Node(leftOne, rightOne, node.depth + 1, node.value | (1 << (bitLen - node.depth - 1)))); } } return result; } private List<Pair<T, Integer>> maxK0(int k, int left, int right) { List<Pair<T, Integer>> result = new ArrayList<>(); Deque<Node> deque = new ArrayDeque<>(); deque.addLast(new Node(left, right, 0, 0)); while (!deque.isEmpty() && result.size() < k) { Node node = deque.pollLast(); if (node.depth == bitLen) { result.add(new Pair<>(values.get(node.value), node.right - node.left)); continue; } int leftOne = bitVectors.get(node.depth).rankOne(node.left) + mids[node.depth]; int rightOne = bitVectors.get(node.depth).rankOne(node.right) + mids[node.depth]; if (leftOne < rightOne) { deque.addLast(new Node(leftOne, rightOne, node.depth + 1, node.value | (1 << (bitLen - node.depth - 1)))); } int leftZero = node.left - leftOne + mids[node.depth]; int rightZero = node.right - rightOne + mids[node.depth]; if (leftZero < rightZero) { deque.addLast(new Node(leftZero, rightZero, node.depth + 1, node.value)); } } return result; } private List<Pair<T, Integer>> rangeList0(T a, T b, int left, int right) { if (a.compareTo(b) >= 0) { return new ArrayList<>(); } List<Pair<T, Integer>> result = new ArrayList<>(); Deque<Node> deque = new ArrayDeque<>(); deque.addLast(new Node(left, right, 0, 0)); while (!deque.isEmpty()) { Node node = deque.pollLast(); if (node.depth == bitLen) { if (a.compareTo(values.get(node.value)) <= 0) { result.add(new Pair<>(values.get(node.value), node.right - node.left)); } continue; } int leftOne = bitVectors.get(node.depth).rankOne(node.left) + mids[node.depth]; int rightOne = bitVectors.get(node.depth).rankOne(node.right) + mids[node.depth]; int nextValue = node.value | (1 << (bitLen - node.depth - 1)); if (leftOne < rightOne && values.get(nextValue).compareTo(b) < 0) { deque.addLast(new Node(leftOne, rightOne, node.depth + 1, nextValue)); } int leftZero = node.left - leftOne + mids[node.depth]; int rightZero = node.right - rightOne + mids[node.depth]; if (leftZero < rightZero) { deque.addLast(new Node(leftZero, rightZero, node.depth + 1, node.value)); } } return result; } private List<IntersectResult> intersect0(int left1, int right1, int left2, int right2) { List<IntersectResult> result = new ArrayList<>(); Deque<IntersectNode> deque = new ArrayDeque<>(); deque.addLast(new IntersectNode(left1, right1, left2, right2, 0, 0)); while (!deque.isEmpty()) { IntersectNode node = deque.pollLast(); if (node.depth == bitLen) { result.add(new IntersectResult(values.get(node.value), node.right1 - node.left1, node.right2 - node.left2)); continue; } int leftOne1 = bitVectors.get(node.depth).rankOne(node.left1) + mids[node.depth]; int rightOne1 = bitVectors.get(node.depth).rankOne(node.right1) + mids[node.depth]; int leftOne2 = bitVectors.get(node.depth).rankOne(node.left2) + mids[node.depth]; int rightOne2 = bitVectors.get(node.depth).rankOne(node.right2) + mids[node.depth]; if (leftOne1 < rightOne1 && leftOne2 < rightOne2) { deque.addLast(new IntersectNode(leftOne1, rightOne1, leftOne2, rightOne2, node.depth + 1, node.value | (1 << (bitLen - node.depth - 1)))); } int leftZero1 = node.left1 - leftOne1 + mids[node.depth]; int rightZero1 = node.right1 - rightOne1 + mids[node.depth]; int leftZero2 = node.left2 - leftOne2 + mids[node.depth]; int rightZero2 = node.right2 - rightOne2 + mids[node.depth]; if (leftZero1 < rightZero1 && leftZero2 < rightZero2) { deque.addLast(new IntersectNode(leftZero1, rightZero1, leftZero2, rightZero2, node.depth + 1, node.value)); } } return result; } private int getId(T value) { int left = -1; int right = m; while (right - left > 1) { int mid = (left + right) / 2; if (values.get(mid).compareTo(value) <= 0) { left = mid; } else { right = mid; } } return left == -1 || values.get(left).compareTo(value) != 0 ? -1 : left; } private int lower(T value) { int left = -1; int right = m; while (right - left > 1) { int mid = (left + right) / 2; if (values.get(mid).compareTo(value) < 0) { left = mid; } else { right = mid; } } return left; } private int higher(T value) { int left = -1; int right = m; while (right - left > 1) { int mid = (left + right) / 2; if (values.get(mid).compareTo(value) <= 0) { left = mid; } else { right = mid; } } return right; } private int floor(T value) { int left = -1; int right = m; while (right - left > 1) { int mid = (left + right) / 2; if (values.get(mid).compareTo(value) <= 0) { left = mid; } else { right = mid; } } return left; } private int ceiling(T value) { int left = -1; int right = m; while (right - left > 1) { int mid = (left + right) / 2; if (values.get(mid).compareTo(value) < 0) { left = mid; } else { right = mid; } } return right; } private void rangeCheck(int left, int right) { if (left >= right) { throw new IllegalArgumentException("left >= right"); } } private void rangeCheck(int k, int left, int right) { rangeCheck(left, right); if (k < 0 || right - left <= k) { throw new IllegalArgumentException("k: " + k); } } private class IntersectNode { private final int left1; private final int right1; private final int left2; private final int right2; private final int depth; private final int value; private IntersectNode(int left1, int right1, int left2, int right2, int depth, int value) { this.left1 = left1; this.right1 = right1; this.left2 = left2; this.right2 = right2; this.depth = depth; this.value = value; } } private class Node implements Comparable<Node> { private final int left; private final int right; private final int depth; private final int value; private Node(int left, int right, int depth, int value) { this.left = left; this.right = right; this.depth = depth; this.value = value; } @Override public int compareTo(Node other) { if (right - left != other.right - other.left) { return -Integer.compare(right - left, other.right - other.left); } if (depth != other.depth) { return Integer.compare(depth, other.depth); } if (value != other.value) { return Integer.compare(value, other.value); } return 0; } } class RankResult { int rank; int rankLessThan; int rankMoreThan; private RankResult() { } @Override public String toString() { return String.format("[%d<%d<%d]", rankLessThan, rank, rankMoreThan); } } class IntersectResult { T value; int freq1; int freq2; private IntersectResult(T value, int freq1, int freq2) { this.value = value; this.freq1 = freq1; this.freq2 = freq2; } @Override public String toString() { return String.format("[%s:{%d, %d}]", value, freq1, freq2); } } } public static void main(String... args) { new Main().solve(); out.flush(); } } class In { private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 0x10000); private StringTokenizer tokenizer; String next() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (IOException ignored) { } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } char[] nextCharArray() { return next().toCharArray(); } String[] nextStringArray(int n) { String[] s = new String[n]; for (int i = 0; i < n; i++) { s[i] = next(); } return s; } char[][] nextCharGrid(int n, int m) { char[][] a = new char[n][m]; for (int i = 0; i < n; i++) { a[i] = next().toCharArray(); } return a; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } int[] nextIntArray(int n, IntUnaryOperator op) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = op.applyAsInt(nextInt()); } return a; } int[][] nextIntMatrix(int h, int w) { int[][] a = new int[h][w]; for (int i = 0; i < h; i++) { a[i] = nextIntArray(w); } return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } long[] nextLongArray(int n, LongUnaryOperator op) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = op.applyAsLong(nextLong()); } return a; } long[][] nextLongMatrix(int h, int w) { long[][] a = new long[h][w]; for (int i = 0; i < h; i++) { a[i] = nextLongArray(w); } return a; } List<List<Integer>> nextEdges(int n, int m, boolean directed) { List<List<Integer>> res = new ArrayList<>(); for (int i = 0; i < n; i++) { res.add(new ArrayList<>()); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; res.get(u).add(v); if (!directed) { res.get(v).add(u); } } return res; } } class Out { private final PrintWriter out = new PrintWriter(System.out); boolean autoFlush = false; void println(Object... args) { if (args == null || args.getClass() != Object[].class) { args = new Object[] {args}; } out.println(Arrays.stream(args).map(obj -> { Class<?> clazz = obj == null ? null : obj.getClass(); return clazz == Double.class ? String.format("%.8f", obj) : clazz == byte[].class ? Arrays.toString((byte[])obj) : clazz == short[].class ? Arrays.toString((short[])obj) : clazz == int[].class ? Arrays.toString((int[])obj) : clazz == long[].class ? Arrays.toString((long[])obj) : clazz == char[].class ? Arrays.toString((char[])obj) : clazz == float[].class ? Arrays.toString((float[])obj) : clazz == double[].class ? Arrays.toString((double[])obj) : clazz == boolean[].class ? Arrays.toString((boolean[])obj) : obj instanceof Object[] ? Arrays.deepToString((Object[])obj) : String.valueOf(obj); }).collect(Collectors.joining(" "))); if (autoFlush) { out.flush(); } } void println(char[] s) { out.println(String.valueOf(s)); if (autoFlush) { out.flush(); } } void println(int[] a) { StringJoiner joiner = new StringJoiner(" "); for (int i : a) { joiner.add(Integer.toString(i)); } out.println(joiner); if (autoFlush) { out.flush(); } } void println(long[] a) { StringJoiner joiner = new StringJoiner(" "); for (long i : a) { joiner.add(Long.toString(i)); } out.println(joiner); if (autoFlush) { out.flush(); } } void flush() { out.flush(); } } import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import java.util.function.IntUnaryOperator; import java.util.function.LongUnaryOperator; import java.util.stream.Collectors; public class Main { static In in = new In(); static Out out = new Out(); static final long inf = 0x1fffffffffffffffL; static final int iinf = 0x3fffffff; static final double eps = 1e-9; static long mod = 1000000007; List<IntPair> list; void solve() { int n = in.nextInt(); list = new ArrayList<>(); for (int i = 0; i < n; i++) { int x = in.nextInt(); int y = in.nextInt(); list.add(new IntPair(x + y, x - y)); } list.sort(Comparator.<IntPair>comparingInt(p -> p.second).thenComparingInt(p -> p.first)); WaveletMatrix<IntPair> wm = new WaveletMatrix<>(list); int q = in.nextInt(); for (int i = 0; i < q; i++) { int a = in.nextInt(); int b = in.nextInt(); int c = a + b; int d = a - b; int k = in.nextInt(); int left = -1; int right = 500000; while (right - left > 1) { int mid = (left + right) / 2; int ll = lowerBound(list, d - mid); int rr = upperBound(list, d + mid); int count = 0; if (ll < rr) { count = wm.rangeFreq(new IntPair(c - mid, -iinf), new IntPair(c + mid + 1, -iinf), ll, rr); } if (count >= k) { right = mid; } else { left = mid; } } out.println(right); } } int lowerBound(List<IntPair> list, int value) { int left = -1; int right = list.size(); while (right - left > 1) { int mid = (left + right) / 2; if (list.get(mid).second < value) { left = mid; } else { right = mid; } } return right; } int upperBound(List<IntPair> list, int value) { int left = -1; int right = list.size(); while (right - left > 1) { int mid = (left + right) / 2; if (list.get(mid).second <= value) { left = mid; } else { right = mid; } } return right; } class IntPair implements Comparable<IntPair> { int first; int second; IntPair(int first, int second) { this.first = first; this.second = second; } @Override public boolean equals(Object o) { if (!(o instanceof IntPair)) { return false; } IntPair that = (IntPair)o; return first == that.first && second == that.second; } @Override public int hashCode() { return first * 31 + second; } @Override public int compareTo(IntPair o) { return first == o.first ? Integer.compare(second, o.second) : Integer.compare(first, o.first); } @Override public String toString() { return String.format("[%d, %d]", first, second); } } class BitVector { private static final int CHUNK_WIDTH = 256; private static final int BLOCK_WIDTH = 32; private static final int BLOCK_PER_CHUNK = CHUNK_WIDTH / BLOCK_WIDTH; private final int length; private final int[] bit; private final byte[] blocks; private final int[] chunk; private boolean isBuilt; BitVector(int nbits) { this.length = nbits; this.bit = new int[nbits / BLOCK_WIDTH + 1]; this.blocks = new byte[nbits / BLOCK_WIDTH + 1]; this.chunk = new int[nbits / CHUNK_WIDTH + 1]; } void flip(int bitIndex) { int blockPos = bitIndex / BLOCK_WIDTH; int offset = bitIndex % BLOCK_WIDTH; bit[blockPos] ^= 1 << offset; } void set(int bitIndex) { int blockPos = bitIndex / BLOCK_WIDTH; int offset = bitIndex % BLOCK_WIDTH; bit[blockPos] |= 1 << offset; } void clear(int bitIndex) { int blockPos = bitIndex / BLOCK_WIDTH; int offset = bitIndex % BLOCK_WIDTH; bit[blockPos] &= ~(1 << offset); } int get(int bitIndex) { int blockPos = bitIndex / BLOCK_WIDTH; int offset = bitIndex % BLOCK_WIDTH; return bit[blockPos] >> offset & 1; } void build() { int acc = 0; for (int i = 0; i <= length / BLOCK_WIDTH; i++) { if (i % BLOCK_PER_CHUNK == 0) { chunk[i / BLOCK_PER_CHUNK] = acc; } blocks[i] = (byte)(acc - chunk[i / BLOCK_PER_CHUNK]); acc += Integer.bitCount(bit[i]); } this.isBuilt = true; } int rank(int b, int left, int right) { return b == 0 ? rankZero(left, right) : rankOne(left, right); } int rank(int b, int k) { return b == 0 ? rankZero(k) : rankOne(k); } int rankZero(int left, int right) { return rankZero(right) - rankZero(left); } int rankZero(int bitIndex) { return bitIndex - rankOne(bitIndex); } int rankOne(int left, int right) { return rankOne(right) - rankOne(left); } int rankOne(int bitIndex) { checkBuilt(); int chunkPos = bitIndex / CHUNK_WIDTH; int blockPos = bitIndex / BLOCK_WIDTH; int offset = bitIndex % BLOCK_WIDTH; int masked = bit[blockPos] & ((1 << offset) - 1); return chunk[chunkPos] + Byte.toUnsignedInt(blocks[blockPos]) + Integer.bitCount(masked); } int select(int b, int k) { return b == 0 ? selectZero(k) : selectOne(k); } int select(int b, int k, int left) { return b == 0 ? selectZero(k, left) : selectOne(k, left); } int selectZero(int k, int left) { return selectZero(k + rankZero(left)); } int selectZero(int k) { checkBuilt(); if (rankZero(length) <= k) { return -1; } int left = 0; int right = length; while (right - left > 1) { int mid = (left + right) / 2; if (rankZero(mid) <= k) { left = mid; } else { right = mid; } } return left; } int selectOne(int k, int left) { return selectOne(k + rankOne(left)); } int selectOne(int k) { checkBuilt(); if (rankOne(length) <= k) { return -1; } int left = 0; int right = length; while (right - left > 1) { int mid = (left + right) / 2; if (rankOne(mid) <= k) { left = mid; } else { right = mid; } } return left; } int length() { return length; } @Override public String toString() { BitSet bitSet = new BitSet(length); for (int i = 0; i < length; i++) { bitSet.set(i, get(i) == 1); } return bitSet.toString(); } private void checkBuilt() { if (!isBuilt) { throw new IllegalStateException("bit vector is not built"); } } } class Pair<F, S> { F first; S second; Pair(F first, S second) { this.first = first; this.second = second; } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) { return false; } Pair<?, ?> that = (Pair<?, ?>)o; return Objects.equals(first, that.first) && Objects.equals(second, that.second); } @Override public int hashCode() { return Objects.hash(first, second); } @Override public String toString() { return String.format("[%s, %s]", first, second); } } class WaveletMatrix<T extends Comparable<T>> { private final int n; private final int m; private final int bitLen; private final int[] mids; private final List<BitVector> bitVectors = new ArrayList<>(); private final List<T> values = new ArrayList<>(); WaveletMatrix(List<T> list) { this.n = list.size(); TreeMap<T, Integer> map = new TreeMap<>(); for (T t : list) { map.put(t, 0); } int size = 0; for (Map.Entry<T, Integer> entry : map.entrySet()) { values.add(entry.getKey()); entry.setValue(size); size++; } this.m = size; this.bitLen = Integer.bitCount(Integer.highestOneBit(m * 2 - 1) - 1); this.mids = new int[bitLen]; int[] dataCurrent = new int[n]; int[] dataNext = new int[n]; for (int i = 0; i < n; i++) { dataCurrent[i] = map.get(list.get(i)); } for (int bit = 0; bit < bitLen; bit++) { bitVectors.add(new BitVector(n)); int pos = 0; for (int i = 0; i < n; i++) { if ((dataCurrent[i] >> (bitLen - bit - 1) & 1) == 0) { dataNext[pos++] = dataCurrent[i]; } } mids[bit] = pos; for (int i = 0; i < n; i++) { if ((dataCurrent[i] >> (bitLen - bit - 1) & 1) == 1) { bitVectors.get(bit).set(i); dataNext[pos++] = dataCurrent[i]; } } bitVectors.get(bit).build(); int[] temp = dataCurrent; dataCurrent = dataNext; dataNext = temp; } } // k 番目の値 T get(int k) { rangeCheck(k, 0, n); return get0(k); } // [left, right) で最小の値 T min() { return values.get(0); } T min(int left, int right) { rangeCheck(left, right); return kthMin(0, left, right); } // [left, right) で最大の値 T max() { return values.get(m - 1); } T max(int left, int right) { rangeCheck(left, right); return kthMax(0, left, right); } // [left, right) の value の個数 int rank(T value) { return rank(value, 0, n); } int rank(T value, int left, int right) { rangeCheck(left, right); return rankAll(value, left, right).rank; } // [left, right) の value に対して 等しい/小さい/大きい 値の個数 RankResult rankAll(T value) { return rankAll(value, 0, n); } RankResult rankAll(T value, int left, int right) { rangeCheck(left, right); return rankAll0(value, left, right); } // [left, right) の k 番目の value の位置 int select(T value, int k) { rangeCheck(k, 0, n); return select0(value, k); } int select(T value, int k, int left, int right) { rangeCheck(k, 0, n); rangeCheck(k, left, right); int prev = left == 0 ? 0 : rank(value, 0, left); int select = select0(value, prev + k); return select < right ? select : -1; } // [left, right) の k 番目に小さい値 T kthMin(int k) { rangeCheck(k, 0, n); return kthMin(k, 0, n); } T kthMin(int k, int left, int right) { rangeCheck(k, 0, right - left); return kthMin0(k, left, right); } // [left, right) の k 番目に大きい値 T kthMax(int k) { rangeCheck(k, 0, n); return kthMax(k, 0, n); } T kthMax(int k, int left, int right) { rangeCheck(k, 0, right - left); return kthMin(right - left - 1 - k, left, right); } // [left, right) の k 番目に小さい値のうち最も小さい index int kthMinIndex(int k) { rangeCheck(k, 0, n); return kthMinIndex(k, 0, n); } int kthMinIndex(int k, int left, int right) { rangeCheck(k, 0, right - left); return select(kthMin0(k, left, right), 0, left, right); } // [left, right) の k 番目に大きい値のうち最も小さい index int kthMaxIndex(int k) { return kthMaxIndex(k, 0, n); } int kthMaxIndex(int k, int left, int right) { rangeCheck(k, 0, right - left); return select(kthMax(k, left, right), 0, left, right); } // [left, right) で値が [a, b) 内のものの個数 int rangeFreq(T a, T b) { return rankAll(b).rankLessThan - rankAll(a).rankLessThan; } int rangeFreq(T a, T b, int left, int right) { rangeCheck(left, right); return rankAll(b, left, right).rankLessThan - rankAll(a, left, right).rankLessThan; } // [left, right) で値が higher より小さく最大のもの(存在しない場合null) T prevValue(T higher) { int lower = lower(higher); return lower == -1 ? null : values.get(lower); } T prevValue(T higher, int left, int right) { rangeCheck(left, right); int count = rankAll(higher, left, right).rankLessThan; return count == 0 ? null : kthMin(count - 1, left, right); } // [left, right) で値が lower より大きく最小のもの(存在しない場合null) T nextValue(T lower) { int higher = higher(lower); return higher == m ? null : values.get(higher); } T nextValue(T lower, int left, int right) { rangeCheck(left, right); int count = rankAll(lower, left, right).rankMoreThan; return count == 0 ? null : kthMax(count - 1, left, right); } // [left, right) で出現頻度が多い順に k 個の値と頻度、出現頻度が同じ場合値が小さいほうから List<Pair<T, Integer>> topK(int k) { return topK(k, 0, n); } List<Pair<T, Integer>> topK(int k, int left, int right) { rangeCheck(left, right); rangeCheck(k, 0, n + 1); return topK0(k, left, right); } // [left, right) で値の小さい順に k 個の値と頻度 List<Pair<T, Integer>> minK(int k) { return minK(k, 0, n); } List<Pair<T, Integer>> minK(int k, int left, int right) { rangeCheck(left, right); rangeCheck(k, 0, n + 1); return minK0(k, left, right); } // [left, right) で値の大きい順に k 個の値と頻度 List<Pair<T, Integer>> maxK(int k) { return maxK(k, 0, n); } List<Pair<T, Integer>> maxK(int k, int left, int right) { rangeCheck(left, right); rangeCheck(k, 0, n + 1); return maxK0(k, left, right); } // [left, right) で値が [a, b) 内のものの値と頻度、値の昇順 List<Pair<T, Integer>> rangeList(T a, T b) { return rangeList(a, b, 0, n); } List<Pair<T, Integer>> rangeList(T a, T b, int left, int right) { rangeCheck(left, right); return rangeList0(a, b, left, right); } // [left1, right1) と [left2, right2) に共通して出現するものの値と頻度、値の昇順 List<IntersectResult> intersect(int left1, int right1, int left2, int right2) { rangeCheck(left1, right1); rangeCheck(left2, right2); return intersect0(left1, right1, left2, right2); } private T get0(int k) { int index = 0; for (int bit = 0; bit < bitLen; bit++) { int dir = bitVectors.get(bit).get(k); index = index << 1 | dir; k = bitVectors.get(bit).rank(dir, k) + dir * mids[bit]; } return values.get(index); } private RankResult rankAll0(T value, int left, int right) { RankResult result = new RankResult(); int floor = floor(value); if (floor == -1) { result.rankMoreThan = right - left; return result; } for (int bit = 0; bit < bitLen; bit++) { int dir = floor >> (bitLen - bit - 1) & 1; int leftCount = bitVectors.get(bit).rank(dir, left); int rightCount = bitVectors.get(bit).rank(dir, right); if (dir == 1) { result.rankLessThan += (right - left) - (rightCount - leftCount); } else { result.rankMoreThan += (right - left) - (rightCount - leftCount); } left = leftCount + dir * mids[bit]; right = rightCount + dir * mids[bit]; } result.rank = right - left; if (values.get(floor).compareTo(value) != 0) { result.rankLessThan += result.rank; result.rank = 0; } return result; } private int select0(T value, int k) { int id = getId(value); if (id == -1) { return -1; } int[] lefts = new int[bitLen]; int[] rights = new int[bitLen]; int left = 0; int right = n; for (int bit = 0; bit < bitLen; bit++) { lefts[bit] = left; rights[bit] = right; int dir = id >> (bitLen - bit - 1) & 1; left = bitVectors.get(bit).rank(dir, left) + dir * mids[bit]; right = bitVectors.get(bit).rank(dir, right) + dir * mids[bit]; } for (int bit = bitLen - 1; bit >= 0; bit--) { int dir = id >> (bitLen - bit - 1) & 1; k = bitVectors.get(bit).select(dir, k, lefts[bit]); if (k < 0 || rights[bit] <= k) { return -1; } k -= lefts[bit]; } return k; } private T kthMin0(int k, int left, int right) { int id = 0; for (int bit = 0; bit < bitLen; bit++) { int count = bitVectors.get(bit).rankZero(left, right); int dir = k >= count ? 1 : 0; id = id << 1 | dir; if (dir == 1) { k -= count; } left = bitVectors.get(bit).rank(dir, left) + dir * mids[bit]; right = bitVectors.get(bit).rank(dir, right) + dir * mids[bit]; } return values.get(id); } private List<Pair<T, Integer>> topK0(int k, int left, int right) { List<Pair<T, Integer>> result = new ArrayList<>(); PriorityQueue<Node> queue = new PriorityQueue<>(); queue.add(new Node(left, right, 0, 0)); while (!queue.isEmpty() && result.size() < k) { Node node = queue.poll(); if (node.depth == bitLen) { result.add(new Pair<>(values.get(node.value), node.right - node.left)); continue; } int leftZero = bitVectors.get(node.depth).rankZero(node.left); int rightZero = bitVectors.get(node.depth).rankZero(node.right); if (leftZero < rightZero) { queue.add(new Node(leftZero, rightZero, node.depth + 1, node.value)); } int leftOne = node.left - leftZero + mids[node.depth]; int rightOne = node.right - rightZero + mids[node.depth]; if (leftOne < rightOne) { queue.add(new Node(leftOne, rightOne, node.depth + 1, node.value | (1 << (bitLen - node.depth - 1)))); } } return result; } private List<Pair<T, Integer>> minK0(int k, int left, int right) { List<Pair<T, Integer>> result = new ArrayList<>(); Deque<Node> deque = new ArrayDeque<>(); deque.addLast(new Node(left, right, 0, 0)); while (!deque.isEmpty() && result.size() < k) { Node node = deque.pollLast(); if (node.depth == bitLen) { result.add(new Pair<>(values.get(node.value), node.right - node.left)); continue; } int leftZero = bitVectors.get(node.depth).rankZero(node.left); int rightZero = bitVectors.get(node.depth).rankZero(node.right); if (leftZero < rightZero) { deque.addLast(new Node(leftZero, rightZero, node.depth + 1, node.value)); } int leftOne = node.left - leftZero + mids[node.depth]; int rightOne = node.right - rightZero + mids[node.depth]; if (leftOne < rightOne) { deque.addLast(new Node(leftOne, rightOne, node.depth + 1, node.value | (1 << (bitLen - node.depth - 1)))); } } return result; } private List<Pair<T, Integer>> maxK0(int k, int left, int right) { List<Pair<T, Integer>> result = new ArrayList<>(); Deque<Node> deque = new ArrayDeque<>(); deque.addLast(new Node(left, right, 0, 0)); while (!deque.isEmpty() && result.size() < k) { Node node = deque.pollLast(); if (node.depth == bitLen) { result.add(new Pair<>(values.get(node.value), node.right - node.left)); continue; } int leftOne = bitVectors.get(node.depth).rankOne(node.left) + mids[node.depth]; int rightOne = bitVectors.get(node.depth).rankOne(node.right) + mids[node.depth]; if (leftOne < rightOne) { deque.addLast(new Node(leftOne, rightOne, node.depth + 1, node.value | (1 << (bitLen - node.depth - 1)))); } int leftZero = node.left - leftOne + mids[node.depth]; int rightZero = node.right - rightOne + mids[node.depth]; if (leftZero < rightZero) { deque.addLast(new Node(leftZero, rightZero, node.depth + 1, node.value)); } } return result; } private List<Pair<T, Integer>> rangeList0(T a, T b, int left, int right) { if (a.compareTo(b) >= 0) { return new ArrayList<>(); } List<Pair<T, Integer>> result = new ArrayList<>(); Deque<Node> deque = new ArrayDeque<>(); deque.addLast(new Node(left, right, 0, 0)); while (!deque.isEmpty()) { Node node = deque.pollLast(); if (node.depth == bitLen) { if (a.compareTo(values.get(node.value)) <= 0) { result.add(new Pair<>(values.get(node.value), node.right - node.left)); } continue; } int leftOne = bitVectors.get(node.depth).rankOne(node.left) + mids[node.depth]; int rightOne = bitVectors.get(node.depth).rankOne(node.right) + mids[node.depth]; int nextValue = node.value | (1 << (bitLen - node.depth - 1)); if (leftOne < rightOne && values.get(nextValue).compareTo(b) < 0) { deque.addLast(new Node(leftOne, rightOne, node.depth + 1, nextValue)); } int leftZero = node.left - leftOne + mids[node.depth]; int rightZero = node.right - rightOne + mids[node.depth]; if (leftZero < rightZero) { deque.addLast(new Node(leftZero, rightZero, node.depth + 1, node.value)); } } return result; } private List<IntersectResult> intersect0(int left1, int right1, int left2, int right2) { List<IntersectResult> result = new ArrayList<>(); Deque<IntersectNode> deque = new ArrayDeque<>(); deque.addLast(new IntersectNode(left1, right1, left2, right2, 0, 0)); while (!deque.isEmpty()) { IntersectNode node = deque.pollLast(); if (node.depth == bitLen) { result.add(new IntersectResult(values.get(node.value), node.right1 - node.left1, node.right2 - node.left2)); continue; } int leftOne1 = bitVectors.get(node.depth).rankOne(node.left1) + mids[node.depth]; int rightOne1 = bitVectors.get(node.depth).rankOne(node.right1) + mids[node.depth]; int leftOne2 = bitVectors.get(node.depth).rankOne(node.left2) + mids[node.depth]; int rightOne2 = bitVectors.get(node.depth).rankOne(node.right2) + mids[node.depth]; if (leftOne1 < rightOne1 && leftOne2 < rightOne2) { deque.addLast(new IntersectNode(leftOne1, rightOne1, leftOne2, rightOne2, node.depth + 1, node.value | (1 << (bitLen - node.depth - 1)))); } int leftZero1 = node.left1 - leftOne1 + mids[node.depth]; int rightZero1 = node.right1 - rightOne1 + mids[node.depth]; int leftZero2 = node.left2 - leftOne2 + mids[node.depth]; int rightZero2 = node.right2 - rightOne2 + mids[node.depth]; if (leftZero1 < rightZero1 && leftZero2 < rightZero2) { deque.addLast(new IntersectNode(leftZero1, rightZero1, leftZero2, rightZero2, node.depth + 1, node.value)); } } return result; } private int getId(T value) { int left = -1; int right = m; while (right - left > 1) { int mid = (left + right) / 2; if (values.get(mid).compareTo(value) <= 0) { left = mid; } else { right = mid; } } return left == -1 || values.get(left).compareTo(value) != 0 ? -1 : left; } private int lower(T value) { int left = -1; int right = m; while (right - left > 1) { int mid = (left + right) / 2; if (values.get(mid).compareTo(value) < 0) { left = mid; } else { right = mid; } } return left; } private int higher(T value) { int left = -1; int right = m; while (right - left > 1) { int mid = (left + right) / 2; if (values.get(mid).compareTo(value) <= 0) { left = mid; } else { right = mid; } } return right; } private int floor(T value) { int left = -1; int right = m; while (right - left > 1) { int mid = (left + right) / 2; if (values.get(mid).compareTo(value) <= 0) { left = mid; } else { right = mid; } } return left; } private int ceiling(T value) { int left = -1; int right = m; while (right - left > 1) { int mid = (left + right) / 2; if (values.get(mid).compareTo(value) < 0) { left = mid; } else { right = mid; } } return right; } private void rangeCheck(int left, int right) { if (left >= right) { throw new IllegalArgumentException("left >= right"); } } private void rangeCheck(int k, int left, int right) { rangeCheck(left, right); if (k < 0 || right - left <= k) { throw new IllegalArgumentException("k: " + k); } } private class IntersectNode { private final int left1; private final int right1; private final int left2; private final int right2; private final int depth; private final int value; private IntersectNode(int left1, int right1, int left2, int right2, int depth, int value) { this.left1 = left1; this.right1 = right1; this.left2 = left2; this.right2 = right2; this.depth = depth; this.value = value; } } private class Node implements Comparable<Node> { private final int left; private final int right; private final int depth; private final int value; private Node(int left, int right, int depth, int value) { this.left = left; this.right = right; this.depth = depth; this.value = value; } @Override public int compareTo(Node other) { if (right - left != other.right - other.left) { return -Integer.compare(right - left, other.right - other.left); } if (depth != other.depth) { return Integer.compare(depth, other.depth); } if (value != other.value) { return Integer.compare(value, other.value); } return 0; } } class RankResult { int rank; int rankLessThan; int rankMoreThan; private RankResult() { } @Override public String toString() { return String.format("[%d<%d<%d]", rankLessThan, rank, rankMoreThan); } } class IntersectResult { T value; int freq1; int freq2; private IntersectResult(T value, int freq1, int freq2) { this.value = value; this.freq1 = freq1; this.freq2 = freq2; } @Override public String toString() { return String.format("[%s:{%d, %d}]", value, freq1, freq2); } } } public static void main(String... args) { new Main().solve(); out.flush(); } } class In { private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 0x10000); private StringTokenizer tokenizer; String next() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (IOException ignored) { } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } char[] nextCharArray() { return next().toCharArray(); } String[] nextStringArray(int n) { String[] s = new String[n]; for (int i = 0; i < n; i++) { s[i] = next(); } return s; } char[][] nextCharGrid(int n, int m) { char[][] a = new char[n][m]; for (int i = 0; i < n; i++) { a[i] = next().toCharArray(); } return a; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } int[] nextIntArray(int n, IntUnaryOperator op) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = op.applyAsInt(nextInt()); } return a; } int[][] nextIntMatrix(int h, int w) { int[][] a = new int[h][w]; for (int i = 0; i < h; i++) { a[i] = nextIntArray(w); } return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } long[] nextLongArray(int n, LongUnaryOperator op) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = op.applyAsLong(nextLong()); } return a; } long[][] nextLongMatrix(int h, int w) { long[][] a = new long[h][w]; for (int i = 0; i < h; i++) { a[i] = nextLongArray(w); } return a; } List<List<Integer>> nextEdges(int n, int m, boolean directed) { List<List<Integer>> res = new ArrayList<>(); for (int i = 0; i < n; i++) { res.add(new ArrayList<>()); } for (int i = 0; i < m; i++) { int u = nextInt() - 1; int v = nextInt() - 1; res.get(u).add(v); if (!directed) { res.get(v).add(u); } } return res; } } class Out { private final PrintWriter out = new PrintWriter(System.out); boolean autoFlush = false; void println(Object... args) { if (args == null || args.getClass() != Object[].class) { args = new Object[] {args}; } out.println(Arrays.stream(args).map(obj -> { Class<?> clazz = obj == null ? null : obj.getClass(); return clazz == Double.class ? String.format("%.8f", obj) : clazz == byte[].class ? Arrays.toString((byte[])obj) : clazz == short[].class ? Arrays.toString((short[])obj) : clazz == int[].class ? Arrays.toString((int[])obj) : clazz == long[].class ? Arrays.toString((long[])obj) : clazz == char[].class ? Arrays.toString((char[])obj) : clazz == float[].class ? Arrays.toString((float[])obj) : clazz == double[].class ? Arrays.toString((double[])obj) : clazz == boolean[].class ? Arrays.toString((boolean[])obj) : obj instanceof Object[] ? Arrays.deepToString((Object[])obj) : String.valueOf(obj); }).collect(Collectors.joining(" "))); if (autoFlush) { out.flush(); } } void println(char[] s) { out.println(String.valueOf(s)); if (autoFlush) { out.flush(); } } void println(int[] a) { StringJoiner joiner = new StringJoiner(" "); for (int i : a) { joiner.add(Integer.toString(i)); } out.println(joiner); if (autoFlush) { out.flush(); } } void println(long[] a) { StringJoiner joiner = new StringJoiner(" "); for (long i : a) { joiner.add(Long.toString(i)); } out.println(joiner); if (autoFlush) { out.flush(); } } void flush() { out.flush(); } }
ConDefects/ConDefects/Code/abc233_h/Java/28148929
condefects-java_data_686
import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.NoSuchElementException; import java.util.Queue; public class Main { public static void main(String[] args) throws FileNotFoundException { new Main().run(); } long pow(long a, long n) { if (n == 0) return 1; return pow(a * a % mod, n / 2) * (n % 2 == 1 ? a : 1) % mod; } long inv(long a) { return pow(a, mod - 2); } long mod = 998244353; int MAX = 600010; long[] fac = new long[MAX]; long[] ifac = new long[MAX]; long[] pwr = new long[MAX]; { Arrays.fill(fac, 1); Arrays.fill(ifac, 1); Arrays.fill(pwr, 1); for (int i = 2; i < fac.length; ++i) { fac[i] = i * fac[i - 1] % mod; } ifac[MAX - 1] = inv(fac[MAX - 1]); for (int i = MAX - 2; i >= 2; --i) { ifac[i] = ifac[i + 1] * (i + 1) % mod; } for (int i = 1; i < pwr.length; ++i) pwr[i] = 26 * pwr[i - 1] % mod; } boolean isLower(char c) { return 'a' <= c && c < 'z'; } boolean isLarge(char c) { return 'A' <= c && c <= 'Z'; } long C(int n, int k) { if (k < 0 || n - k < 0) return 0; return fac[n] * ifac[k] % mod * ifac[n - k] % mod; } long P(int n, int k) { return C(n, k) * fac[k] % mod; } void run() throws FileNotFoundException { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); long ans = 0; char[] cs = sc.next().toCharArray(); int N = cs.length; long[] dp = new long[N]; // dp[i] == S[i] が大文字かつ S[0..i) に同じ文字が出現する最初の場所 { int free = 0; int set = 0; out : for (int i = 0; i < N; ++i) { int used = Integer.bitCount(set); if (cs[i] == '?') { for (int k = 0; k + used <= 26 && k <= free; ++k) {//S[1..i)で?を大文字にする個数 dp[i] += C(free, k) * P(26 - used, k) % mod * pwr[free - k] % mod * (used + k) % mod; dp[i] %= mod; } ++free; } else if (isLarge(cs[i])) { int id = cs[i] - 'A'; if ((set >> id) % 2 == 1) { for (int k = 0; k + used <= 26 && k <= free; ++k) { dp[i] += C(free, k) * P(26 - used, k) % mod * pwr[free - k] % mod; dp[i] %= mod; } break out; } else { for (int k = 1; k + used <= 26 && k <= free; ++k) { // ひとつは cs[i] で確定 dp[i] += C(free, k) * k % mod * P(26 - (used + 1), k - 1) % mod * pwr[free - k] % mod; dp[i] %= mod; } set |= 1 << id; } } if (i == N - 1) { used = Integer.bitCount(set); for (int k = 0; k + used <= 26 && k <= free; ++k) { ans += C(free, k) * P(26 - used, k) % mod * pwr[free - k] % mod; ans %= mod; } ans %= mod; } } } //dp以降で大文字が0個以上続いている for (int i = 0; i < N; ++i) { if (isLarge(cs[i]) && i > 0) { dp[i] += dp[i - 1]; } if (cs[i] == '?' && i > 0) { dp[i] += dp[i - 1] * 26; } dp[i] %= mod; } long[] dp3 = new long[N];//dp3[i]=dp2以降で小文字しか現れておらず、小文字は1文字以上現れた for (int i = 0; i < N; ++i) { long way = 0; if (isLower(cs[i])) way = 1; else if (cs[i] == '?') way = 26; if (i > 0) { dp3[i] += way * (dp[i - 1] + dp3[i - 1]); } dp3[i] %= mod; } ans += dp[N - 1]; ans += dp3[N - 1]; ans %= mod; System.out.println(ans); pw.close(); } void tr(Object... objects) { System.out.println(Arrays.deepToString(objects)); } } class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } public boolean hasNext() { skipUnprintable(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { return (int) nextLong(); } } import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.NoSuchElementException; import java.util.Queue; public class Main { public static void main(String[] args) throws FileNotFoundException { new Main().run(); } long pow(long a, long n) { if (n == 0) return 1; return pow(a * a % mod, n / 2) * (n % 2 == 1 ? a : 1) % mod; } long inv(long a) { return pow(a, mod - 2); } long mod = 998244353; int MAX = 600010; long[] fac = new long[MAX]; long[] ifac = new long[MAX]; long[] pwr = new long[MAX]; { Arrays.fill(fac, 1); Arrays.fill(ifac, 1); Arrays.fill(pwr, 1); for (int i = 2; i < fac.length; ++i) { fac[i] = i * fac[i - 1] % mod; } ifac[MAX - 1] = inv(fac[MAX - 1]); for (int i = MAX - 2; i >= 2; --i) { ifac[i] = ifac[i + 1] * (i + 1) % mod; } for (int i = 1; i < pwr.length; ++i) pwr[i] = 26 * pwr[i - 1] % mod; } boolean isLower(char c) { return 'a' <= c && c <= 'z'; } boolean isLarge(char c) { return 'A' <= c && c <= 'Z'; } long C(int n, int k) { if (k < 0 || n - k < 0) return 0; return fac[n] * ifac[k] % mod * ifac[n - k] % mod; } long P(int n, int k) { return C(n, k) * fac[k] % mod; } void run() throws FileNotFoundException { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); long ans = 0; char[] cs = sc.next().toCharArray(); int N = cs.length; long[] dp = new long[N]; // dp[i] == S[i] が大文字かつ S[0..i) に同じ文字が出現する最初の場所 { int free = 0; int set = 0; out : for (int i = 0; i < N; ++i) { int used = Integer.bitCount(set); if (cs[i] == '?') { for (int k = 0; k + used <= 26 && k <= free; ++k) {//S[1..i)で?を大文字にする個数 dp[i] += C(free, k) * P(26 - used, k) % mod * pwr[free - k] % mod * (used + k) % mod; dp[i] %= mod; } ++free; } else if (isLarge(cs[i])) { int id = cs[i] - 'A'; if ((set >> id) % 2 == 1) { for (int k = 0; k + used <= 26 && k <= free; ++k) { dp[i] += C(free, k) * P(26 - used, k) % mod * pwr[free - k] % mod; dp[i] %= mod; } break out; } else { for (int k = 1; k + used <= 26 && k <= free; ++k) { // ひとつは cs[i] で確定 dp[i] += C(free, k) * k % mod * P(26 - (used + 1), k - 1) % mod * pwr[free - k] % mod; dp[i] %= mod; } set |= 1 << id; } } if (i == N - 1) { used = Integer.bitCount(set); for (int k = 0; k + used <= 26 && k <= free; ++k) { ans += C(free, k) * P(26 - used, k) % mod * pwr[free - k] % mod; ans %= mod; } ans %= mod; } } } //dp以降で大文字が0個以上続いている for (int i = 0; i < N; ++i) { if (isLarge(cs[i]) && i > 0) { dp[i] += dp[i - 1]; } if (cs[i] == '?' && i > 0) { dp[i] += dp[i - 1] * 26; } dp[i] %= mod; } long[] dp3 = new long[N];//dp3[i]=dp2以降で小文字しか現れておらず、小文字は1文字以上現れた for (int i = 0; i < N; ++i) { long way = 0; if (isLower(cs[i])) way = 1; else if (cs[i] == '?') way = 26; if (i > 0) { dp3[i] += way * (dp[i - 1] + dp3[i - 1]); } dp3[i] %= mod; } ans += dp[N - 1]; ans += dp3[N - 1]; ans %= mod; System.out.println(ans); pw.close(); } void tr(Object... objects) { System.out.println(Arrays.deepToString(objects)); } } class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } public boolean hasNext() { skipUnprintable(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { return (int) nextLong(); } }
ConDefects/ConDefects/Code/abc301_f/Java/41400655
condefects-java_data_687
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.NoSuchElementException; import java.util.stream.Collectors; public class Main { public static boolean debug = true; public static void main(String[] args) { var sc = FastScanner.getInstance(); var s = sc.next(); var ans = 0; for (int i = 0; i < s.length(); i++) { for (int j = i + 1; j <= s.length(); j++) { var str = s.substring(i, j); var sb = new StringBuilder(); sb.append(str); var rev = sb.reverse().toString(); if (s.contains(rev)) { ans = max(ans, rev.length()); } } } System.out.println(ans); } /*--- ---*/ /*--- Util ---*/ /*--- ---*/ public static int max(int[] array) { return Arrays.stream(array).max().getAsInt(); } public static int max(int a, int b) { return Math.max(a, b); } public static String colToString(Collection<?> col) { return col.toString().replaceAll("[,\\[\\]]", ""); } public static void printYesNo(boolean b) { System.out.println(b ? "Yes" : "No"); } public static void print(Collection<?> c) { System.out.println(String.join(" ", c.stream().map(String::valueOf).collect(Collectors.toList()))); } public static void print(Object obj) { System.out.print(obj); } public static void println(Object obj) { System.out.println(obj); } public static void println(Collection<?> c) { StringBuilder sb = new StringBuilder(); for (Object object : c) { // java 15以下の環境だとisEmptyがコンパイルしない if (!sb.isEmpty()) sb.append("\r\n"); sb.append(object); } System.out.println(sb); } public static void print(String[] a) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < a.length; i++) { if (i != 0) sb.append(" "); sb.append(a[i]); } System.out.println(sb); } public static void println(String[] a) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < a.length; i++) { if (i != 0) sb.append("\r\n"); sb.append(a[i]); } System.out.println(sb); } public static void print(int[] a) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < a.length; i++) { if (i != 0) sb.append(" "); sb.append(a[i]); } System.out.println(sb); } public static void println(int[] a) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < a.length; i++) { if (i != 0) sb.append("\r\n"); sb.append(a[i]); } System.out.println(sb); } public static void print(boolean[] a) { for (int i = 0; i < a.length; i++) { System.out.println(a[i] + " "); } System.out.println(""); } public static void printBooleanTable(boolean[][] b) { for (int i = 0; i < b.length; i++) { for (int j = 0; j < b[0].length; j++) { System.out.println(b[i][j] ? "o" : "x"); } System.out.println(""); } } public static void printIntTable(int[][] a) { for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[0].length; j++) { System.out.println(a[i][j] + " "); } System.out.println(""); } } /*--- ---*/ /*--- debug ---*/ /*--- ---*/ public static void debug(int[] x) { if (debug) out(Arrays.toString(x)); } public static void debug(boolean[] x) { if (debug) out(Arrays.toString(x)); } public static void debug(long[] x) { if (debug) out(Arrays.toString(x)); } public static void debug(int[][] x) { if (debug) out(Arrays.deepToString(x)); } public static void debug(boolean[][] x) { if (debug) out(Arrays.deepToString(x)); } public static void debug(char[][] x) { if (debug) out(Arrays.deepToString(x)); } public static void debug(Object[] x) { if (debug) out(Arrays.toString(x)); } public static void debug(Object[][] x) { if (debug) out(Arrays.deepToString(x)); } public static void debug(Object a) { if (debug) System.err.println(a); } public static void out(String x) { if (debug) System.err.println(x); } } class FastScanner { private FastScanner() { } private static final FastScanner instance = new FastScanner(); public static FastScanner getInstance() { return instance; } private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public int[] readIntArray(int size) { int[] intArray = new int[size]; Arrays.setAll(intArray, i -> nextInt()); return intArray; } public long[] readLongArray(int size) { long[] longArray = new long[size]; Arrays.setAll(longArray, i -> nextLong()); return longArray; } public String[] readStringArray(int size) { String[] stringArray = new String[size]; Arrays.setAll(stringArray, i -> next()); return stringArray; } public List<String> readStringList(int size) { List<String> list = new ArrayList<>(); for (int i = 0; i < size; i++) { list.add(next()); } return list; } public Integer[] readIntegerArray(int size) { Integer[] ret = new Integer[size]; for (int i = 0; i < size; i++) { ret[i] = nextInt(); } return ret; } public char[][] twoDimensionalCharArray(int h, int w) { char[][] array = new char[h][w]; for (int i = 0; i < h; i++) { array[i] = next().toCharArray(); } return array; } public int[][] twoDimensionalIntArray(int h, int w) { int[][] array = new int[h][w]; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { array[i][j] = nextInt(); } } return array; } public int[][] getIntArrayFromStr(int h, int w) { int[][] array = new int[h][w]; for (int i = 0; i < h; i++) { String temp = next(); for (int j = 0; j < w; j++) { array[i][j] = temp.charAt(j) - '0'; } } return array; } public List<Integer> readIntgerList(int size) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < size; i++) { list.add(nextInt()); } return list; } } import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.NoSuchElementException; import java.util.stream.Collectors; public class Main { public static boolean debug = true; public static void main(String[] args) { var sc = FastScanner.getInstance(); var s = sc.next(); var ans = 0; for (int i = 0; i < s.length(); i++) { for (int j = i + 1; j <= s.length(); j++) { var str = s.substring(i, j); var sb = new StringBuilder(); sb.append(str); var rev = sb.reverse().toString(); if (str.equals(rev)) { ans = max(ans, rev.length()); } } } System.out.println(ans); } /*--- ---*/ /*--- Util ---*/ /*--- ---*/ public static int max(int[] array) { return Arrays.stream(array).max().getAsInt(); } public static int max(int a, int b) { return Math.max(a, b); } public static String colToString(Collection<?> col) { return col.toString().replaceAll("[,\\[\\]]", ""); } public static void printYesNo(boolean b) { System.out.println(b ? "Yes" : "No"); } public static void print(Collection<?> c) { System.out.println(String.join(" ", c.stream().map(String::valueOf).collect(Collectors.toList()))); } public static void print(Object obj) { System.out.print(obj); } public static void println(Object obj) { System.out.println(obj); } public static void println(Collection<?> c) { StringBuilder sb = new StringBuilder(); for (Object object : c) { // java 15以下の環境だとisEmptyがコンパイルしない if (!sb.isEmpty()) sb.append("\r\n"); sb.append(object); } System.out.println(sb); } public static void print(String[] a) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < a.length; i++) { if (i != 0) sb.append(" "); sb.append(a[i]); } System.out.println(sb); } public static void println(String[] a) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < a.length; i++) { if (i != 0) sb.append("\r\n"); sb.append(a[i]); } System.out.println(sb); } public static void print(int[] a) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < a.length; i++) { if (i != 0) sb.append(" "); sb.append(a[i]); } System.out.println(sb); } public static void println(int[] a) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < a.length; i++) { if (i != 0) sb.append("\r\n"); sb.append(a[i]); } System.out.println(sb); } public static void print(boolean[] a) { for (int i = 0; i < a.length; i++) { System.out.println(a[i] + " "); } System.out.println(""); } public static void printBooleanTable(boolean[][] b) { for (int i = 0; i < b.length; i++) { for (int j = 0; j < b[0].length; j++) { System.out.println(b[i][j] ? "o" : "x"); } System.out.println(""); } } public static void printIntTable(int[][] a) { for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[0].length; j++) { System.out.println(a[i][j] + " "); } System.out.println(""); } } /*--- ---*/ /*--- debug ---*/ /*--- ---*/ public static void debug(int[] x) { if (debug) out(Arrays.toString(x)); } public static void debug(boolean[] x) { if (debug) out(Arrays.toString(x)); } public static void debug(long[] x) { if (debug) out(Arrays.toString(x)); } public static void debug(int[][] x) { if (debug) out(Arrays.deepToString(x)); } public static void debug(boolean[][] x) { if (debug) out(Arrays.deepToString(x)); } public static void debug(char[][] x) { if (debug) out(Arrays.deepToString(x)); } public static void debug(Object[] x) { if (debug) out(Arrays.toString(x)); } public static void debug(Object[][] x) { if (debug) out(Arrays.deepToString(x)); } public static void debug(Object a) { if (debug) System.err.println(a); } public static void out(String x) { if (debug) System.err.println(x); } } class FastScanner { private FastScanner() { } private static final FastScanner instance = new FastScanner(); public static FastScanner getInstance() { return instance; } private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int buflen = 0; private boolean hasNextByte() { if (ptr < buflen) { return true; } else { ptr = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } public boolean hasNext() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } public int nextInt() { long nl = nextLong(); if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) nl; } public double nextDouble() { return Double.parseDouble(next()); } public int[] readIntArray(int size) { int[] intArray = new int[size]; Arrays.setAll(intArray, i -> nextInt()); return intArray; } public long[] readLongArray(int size) { long[] longArray = new long[size]; Arrays.setAll(longArray, i -> nextLong()); return longArray; } public String[] readStringArray(int size) { String[] stringArray = new String[size]; Arrays.setAll(stringArray, i -> next()); return stringArray; } public List<String> readStringList(int size) { List<String> list = new ArrayList<>(); for (int i = 0; i < size; i++) { list.add(next()); } return list; } public Integer[] readIntegerArray(int size) { Integer[] ret = new Integer[size]; for (int i = 0; i < size; i++) { ret[i] = nextInt(); } return ret; } public char[][] twoDimensionalCharArray(int h, int w) { char[][] array = new char[h][w]; for (int i = 0; i < h; i++) { array[i] = next().toCharArray(); } return array; } public int[][] twoDimensionalIntArray(int h, int w) { int[][] array = new int[h][w]; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { array[i][j] = nextInt(); } } return array; } public int[][] getIntArrayFromStr(int h, int w) { int[][] array = new int[h][w]; for (int i = 0; i < h; i++) { String temp = next(); for (int j = 0; j < w; j++) { array[i][j] = temp.charAt(j) - '0'; } } return array; } public List<Integer> readIntgerList(int size) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < size; i++) { list.add(nextInt()); } return list; } }
ConDefects/ConDefects/Code/abc320_b/Java/46778463
condefects-java_data_688
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); String ws1 = ""; String ws2 = ""; StringBuilder sb = new StringBuilder(); int ans = 0; for (int i = 0; i < s.length(); i++) { for (int j = i; j < s.length(); j++) { ws1 = s.substring(i, j); sb.append(ws1); ws2 = sb.reverse().toString(); if (ws1.equals(ws2)) { ans = Math.max(ans, ws1.length()); } sb.setLength(0); } } System.out.println(ans); sc.close(); } } import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); String ws1 = ""; String ws2 = ""; StringBuilder sb = new StringBuilder(); int ans = 0; for (int i = 0; i < s.length(); i++) { for (int j = i; j <= s.length(); j++) { ws1 = s.substring(i, j); sb.append(ws1); ws2 = sb.reverse().toString(); if (ws1.equals(ws2)) { ans = Math.max(ans, ws1.length()); } sb.setLength(0); } } System.out.println(ans); sc.close(); } }
ConDefects/ConDefects/Code/abc320_b/Java/47118468
condefects-java_data_689
import java.util.Scanner; import java.math.BigDecimal; public class Main { public static void main(String[] args) { String i = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"; Scanner scan = new Scanner(System.in); int p = scan.nextInt(); String s = i.substring(0, p+1); System.out.println(s); } } import java.util.Scanner; import java.math.BigDecimal; public class Main { public static void main(String[] args) { String i = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"; Scanner scan = new Scanner(System.in); int p = scan.nextInt(); String s = i.substring(0, p+2); System.out.println(s); } }
ConDefects/ConDefects/Code/abc314_a/Java/45649202
condefects-java_data_690
import java.util.*; public class Main{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); String pi = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"; System.out.println(pi.substring(0, n)); } } import java.util.*; public class Main{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); String pi = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"; System.out.println(pi.substring(0, n+2)); } }
ConDefects/ConDefects/Code/abc314_a/Java/45732411
condefects-java_data_691
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.DecimalFormat; import java.util.*; public class Main { //class Codechef { static FastReader sc; static StringBuilder sb = new StringBuilder(); static int mod = (int) (Math.pow(10, 9) + 7); static final int dx[] = {-1, 0, 1, 0}, dy[] = {0, -1, 0, 1}; static final int[] dx8 = {-1, -1, -1, 0, 0, 1, 1, 1}, dy8 = {-1, 0, 1, -1, 1, -1, 0, 1}; static final int[] dx9 = {-1, -1, -1, 0, 0, 0, 1, 1, 1}, dy9 = {-1, 0, 1, -1, 0, 1, -1, 0, 1}; static HashSet<Character> set; static final double eps = 1e-10; static long[] arr = new long[100001]; static List<Integer> primeNumbers = new ArrayList<>(); static int cnt = 0; static HashSet<Character> hor = new HashSet<>(); static HashSet<Character> ver = new HashSet<>(); public static void main(String[] args) { sc = new FastReader(); int testCases = 1; hor.add('L'); hor.add('R'); ver.add('U'); ver.add('D'); //primeSieve(40000000); //testCases = sc.nextInt(); while (testCases-- > 0) compute(); //sb.append(cnt); System.out.println(sb.toString()); } public static void compute() { //Arrays.sort(al,Comparator.comparingInt(ar -> ar.value)); //Arrays.sort(al,Comparator.comparingInt(ar -> ar.index)); //shortestCompletingWord() // String s="1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"; int n=sc.nextInt(); sb.append("3.").append("\n"); for(int i=0;i<n;i++){ sb.append(s.charAt(i)); } /*res.append(s.charAt(i)); if(i<l-2 && check(s.substring(i,i+3))) i+=2;*/ //sb.append(((risk^x)&risk)>0?(-1):(risk^x)).append("\n"); //sb.append(isValid(x,y,z)).append("\n"); // int sec = Arrays.stream(arr).sorted().distinct().skip(1).findFirst().getAsInt(); } public int numberOfEmployeesWhoMetTarget(int[] hours, int target) { return ((int) Arrays.stream(hours).filter(i -> i >= target).count()); } public boolean isSame(String a,String b){ int l1 = a.length(),l2=b.length(); if(l1!=l2) return false; for(int i=0;i<l1;i++){ if(a.charAt(i)!=b.charAt(l1-i-1)) return false; } return true; } public int findDelayedArrivalTime(int arrivalTime, int delayedTime) { return (delayedTime+arrivalTime)%24; } public String makeSmallestPalindrome(String s) { StringBuilder res = new StringBuilder(); int l=s.length(); for(int i=0;i<=l/2;i++){ if(s.charAt(i)==s.charAt(l-1-i)) res.append(s.charAt(i)); else res.append(s.charAt(i)<s.charAt(l-1-i)?s.charAt(i):s.charAt(l-i-1)); } if(l%2==0) return res.toString()+res.reverse().toString(); return res.toString()+s.charAt(l/2)+res.reverse().toString(); } public int minimizedStringLength(String s) { int[] arr = new int[26]; for (char c : s.toCharArray()) arr[c - 'a']++; int res = 0; for (int i : arr) { if (i > 0) res++; } return res; } private static int findsum(int n) { int res = 0; while (n > 0) { res++; n /= 10; } return res; } public static boolean check(char a, char b) { if (a == '0' || a == 'o') { if (b != '0' && b != 'o') return false; return true; } if (a == '1' || a == 'l') { if (b != '1' && b != 'l') return false; return true; } return false; } public String removeTrailingZeros(String num) { int l = num.length(); while (num.charAt(l--) == '0') ; return num.substring(0, l); } public int buyChoco(int[] prices, int money) { int sum = Arrays.stream(prices).sorted().limit(2).sum(); return money >= sum ? money - sum : money; } public static long nChooseK(int n, int k) { if (k > n) { return 0; // invalid input } long numerator = 1L; for (int i = 1; i <= k; i++) { numerator *= (n - (k - i)); numerator /= i; } return numerator; } public int maximizeSum(int[] nums, int k) { int max = Arrays.stream(nums).max().getAsInt(); max *= 2; max += (k - 1); max *= k; max /= 2; return max; } public static boolean check(String s) { //System.out.println(s); if (s.equalsIgnoreCase("and") || s.equalsIgnoreCase("not") || s.equalsIgnoreCase("that") || s.equalsIgnoreCase("the") || s.equalsIgnoreCase("you")) return true; return false; } public int minNumber(int[] nums1, int[] nums2) { int min1 = Arrays.stream(nums1).min().getAsInt(); int min2 = Arrays.stream(nums1).min().getAsInt(); Arrays.sort(nums1); Arrays.sort(nums2); for (int i : nums1) { for (int ii : nums2) { if (i == ii) return i; } } int m1 = Math.min(min1, min2); int m2 = min2 + min1 - m1; return 10 * m1 + m2; } public int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { int res = 0; if (k <= numOnes) return Math.min(k, numOnes); else { res += numOnes; k -= numOnes; } if (k <= numZeros) return res; else k -= numZeros; if (k <= numNegOnes) return res - numNegOnes; return -1 * (numNegOnes - res); } public int passThePillow(int n, int time) { int q = time / n; if (q % 2 == 0) return time % n; return n - time % n; } public static boolean match(Character c, Character d) { if (ver.contains(c) && ver.contains(d)) return true; if (hor.contains(c) && hor.contains(d)) return true; return false; } public int[] evenOddBit(int n) { int[] res = new int[2]; int odd = 0, even = 0; String s = Integer.toBinaryString(n); System.out.println(s); int l = s.length(), t = 0; for (int i = l - 1; i >= 0; i--) { System.out.println(s.charAt(i)); if (s.charAt(i) == 1) { if (t % 2 == 0) even++; else odd++; t++; } } res[0] = even; res[1] = odd; return res; } public int maxScore(int[] nums) { long res = 0; int rr = 0; ArrayList<Integer> negs = new ArrayList<>(); for (int i : nums) { if (i >= 0) { rr++; res += i; } else negs.add(i); } Collections.sort(negs, Collections.reverseOrder()); for (int i : negs) { res += i; if (res > 0) rr++; else break; } return rr; } public int vowelStrings(String[] words, int left, int right) { int res = 0; for (int i = left; i <= right; i++) { if (isVowel(words[i].charAt(0)) && isVowel(words[i].charAt(words[i].length() - 1))) res++; } return res; } static int nCr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } // Returns factorial of n static int fact(int n) { if (n == 0) return 1; int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res; } public int splitNum(int num) { StringBuilder n1 = new StringBuilder(); StringBuilder n2 = new StringBuilder(); ArrayList<Integer> list = new ArrayList<>(); while (num > 0) { list.add(num % 10); num /= 10; } Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < list.size(); i++) { if (i % 2 == 0) n1.append(list.get(i)); else n2.append(list.get(i)); } System.out.println(n1.toString() + " " + n2.toString()); return Integer.parseInt(n1.toString()) + Integer.parseInt(n2.toString()); } public int minMaxDifference(int num) { int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int i = 0; i < 10; i++) { min = Math.min(min, Integer.parseInt(String.valueOf(num).replaceAll(Integer.toString(i), "0"))); max = Math.max(max, Integer.parseInt(String.valueOf(num).replaceAll(Integer.toString(i), "9"))); } return max - min; } public int[] leftRigthDifference(int[] nums) { int l = nums.length; int[] lsum = new int[l]; int[] rsum = new int[l]; int[] res = new int[l]; for (int i = 1; i < l; i++) lsum[i] += (nums[i - 1] + lsum[i - 1]); for (int i = l - 2; i >= 0; i--) rsum[i] += (nums[i + 1] + rsum[i + 1]); for (int i = 0; i < l; i++) res[i] = Math.abs(lsum[i] - rsum[i]); return res; } public static String isValid(int x, int y, int z) { if (x == y && x == z) return "YES"; else if (x != y && y != z && x != z) return "NO"; else { if (x == y && x != z && z > x) return "YES"; else if (x == z && x != y && y > x) return "YES"; else if (y == z && y != x && x > y) return "YES"; } return "NO"; } public long findTheArrayConcVal(int[] nums) { long res = 0; int l = nums.length; for (int i = 0; i < l / 2; i++) { res += concat(nums[i], nums[l - i - 1]); } if (l % 2 == 0) res += nums[l / 2]; return res; } public int concat(int a, int b) { StringBuilder res = new StringBuilder(); res.append(a).append(b); System.out.println(res.toString()); return Integer.parseInt(res.toString()); } public int[] vowelStrings(String[] words, int[][] queries) { int l = words.length; int ql = queries.length; int[] rll = new int[l + 1]; int[] res = new int[ql]; for (int i = 1; i <= l; i++) { if (isVowel(words[i - 1].charAt(0)) && isVowel(words[i - 1].charAt(words[i - 1].length() - 1))) rll[i]++; rll[i] += rll[i - 1]; } for (int i = 0; i < ql; i++) { res[i] = (rll[queries[i][1] + 1] - rll[queries[i][0]]); } return res; } public int getCommon(int[] nums1, int[] nums2) { int l1 = nums1.length, l2 = nums2.length; int s1 = 0, s2 = 0; while (s1 < l1 && s2 < l2) { System.out.println(nums1[s1] + " " + nums2[s2]); if (nums1[s1] == nums2[s2]) return nums1[s1]; else if (nums1[s1] < nums2[s2]) return s1++; else s2++; } return -1; } public int closetTarget(String[] words, String target, int startIndex) { int n = words.length; int dis1 = 0, dis2 = 0; boolean ispresent = false; for (String s : words) { if (s.equals(target)) { ispresent = true; break; } } if (!ispresent) return -1; for (int i = startIndex; i < words.length; i++) { if (words[i].equals(target)) break; dis1++; } dis1 = Math.min(dis1, n + 1 - dis1); for (int i = startIndex; i >= 0; i--) { if (words[i].equals(target)) break; dis2++; } dis2 = Math.min(dis2, n + 1 - dis2); return Math.min(dis1, dis2); } public int[] plusOne(int[] a) { int[] arr = new int[a.length + 1]; int carry = 1, l = a.length; for (int i = l - 1; i >= 0; i--) { arr[i + 1] = a[i] + carry; if (arr[i + 1] == 10) { arr[i + 1] = 0; carry = 1; } else carry = 0; } System.out.println(carry); arr[0] = carry; if (arr[0] == 0) { int[] res = new int[l]; for (int i = 1; i < l; i++) res[i - 1] = arr[i]; return res; } return arr; } public int captureForts(int[] forts) { int sp = 0, ep = forts.length - 1; while (forts[sp] == 0) sp++; while (forts[ep] == 0) ep--; if (sp + 1 <= ep) return 0; int max = 0, t = 0; System.out.println(sp + " " + ep); for (int i = sp + 1; i < ep; i++) { while (forts[i] == 0) { i++; t++; } max = Math.max(max, t); t = 0; } return max; } public boolean check(int[] arr) { int l = arr.length; int si = l / 2; int sum = 0; for (int i : arr) sum += i; if (sum % 2 == 1 && si != 1) return false; if (sum % si != 0) return false; int val = sum / si; Arrays.sort(arr); for (int i = 0; i < l / 2; i++) { if (arr[i] + arr[l - 1 - i] != val) return false; } return true; } public int similarPairs(String[] words) { int res = 0, l = words.length; for (int i = 0; i < l - 1; i++) { for (int j = i + 1; j < l; j++) { if (similar(words[i], words[j])) { res++; System.out.println(words[i] + " " + words[j]); } } } return res; } public static boolean similar(String a, String j) { int[] arr = new int[26]; for (char c : a.toCharArray()) arr[c - 'a']++; for (char c : j.toCharArray()) { if (arr[c - 'a'] == 0) return false; } for (char c : j.toCharArray()) arr[c - 'a'] = 0; for (int i : arr) { if (i == 0) return false; } return true; } public boolean validPalindrome(String s) { if (isPalindrome(s)) return true; String result; for (int i = 0; i < s.length(); i++) { result = s.substring(0, i) + s.substring(i + 1); if (isPalindrome(result)) return true; } return false; } public int distinctAverages(int[] nums) { HashSet<Double> set = new HashSet<>(); Arrays.sort(nums); int l = nums.length; double t; for (int i = 0; i < l / 2; i++) { t = nums[i] + nums[l - i - 1]; t /= 2; set.add(t); } return set.size(); } public double[] convertTemperature(double celsius) { double[] res = {celsius + 273.15, (celsius * 1.8) + 32}; return res; } public int unequalTriplets(int[] nums) { int res = 0, l = nums.length; for (int i = 0; i < l; i++) { for (int j = i + 1; j < l; j++) { if (nums[i] != nums[j]) { for (int k = j + 1; k < l; k++) { if (nums[i] != nums[k] && nums[k] != nums[j]) res++; } } } } return res; } public int maximumValue(String[] strs) { int res = 0; for (String s : strs) { if (isNumber(s)) res = Math.max(res, Integer.parseInt(s)); else res = Math.max(res, s.length()); } return res; } public boolean isNumber(String s) { for (char c : s.toCharArray()) { if (!Character.isDigit(c)) return false; } return true; } public static boolean isPerfectSquare(int n) { int nn = (int) Math.sqrt(n); if (nn * nn == n) return true; return false; } public int garbageCollection(String[] garbage, int[] travel) { int res = 0; int gi = -1, mi = -1, pi = -1; int gl = garbage.length; for (int i = gl - 1; i >= 0; i--) { if (garbage[i].contains("G")) { gi = i; break; } } for (int i = gl - 1; i >= 0; i--) { if (garbage[i].contains("P")) { pi = i; break; } } for (int i = gl - 1; i >= 0; i--) { if (garbage[i].contains("M")) { mi = i; break; } } System.out.println(gi + " " + pi + " " + mi); for (int i = 1; i <= gi; i++) { res += travel[i - 1]; if (garbage[i].contains("G")) res += count(garbage[i], 'G'); } for (int i = 1; i <= mi; i++) { res += travel[i - 1]; if (garbage[i].contains("M")) res += count(garbage[i], 'M'); } for (int i = 1; i <= pi; i++) { res += travel[i - 1]; if (garbage[i].contains("P")) res += count(garbage[i], 'P'); } if (garbage[0].contains("P")) res += count(garbage[0], 'P'); if (garbage[0].contains("M")) res += count(garbage[0], 'M'); if (garbage[0].contains("G")) res += count(garbage[0], 'G'); return res; } public int count(String s, char p) { int res = 0; for (char c : s.toCharArray()) { if (c == (p)) res++; } return res; } public int reverseInt(int n) { StringBuffer sbr = new StringBuffer(String.valueOf(n)); return Integer.parseInt(sbr.reverse().toString()); } public boolean equalFrequency(String word) { int[] arr = new int[26]; for (char c : word.toCharArray()) arr[c - 'a']++; HashSet<Integer> set = new HashSet<>(); int max = -1; for (int i : arr) { if (i > 0) set.add(i); max = Math.max(max, i); } Integer[] inset = set.toArray(new Integer[set.size()]); if (set.size() != 2) return false; if (Math.abs(inset[0] - inset[1]) != 1) return false; int maxcnt = 0; for (int i : arr) { if (i == max) maxcnt++; } return maxcnt == 1 ? true : false; } public List<Boolean> prefixesDivBy5(int[] nums) { int l = nums.length; List<Boolean> ar = new ArrayList<>(); StringBuilder res = new StringBuilder(); for (int i : nums) { res.append(i); if (Integer.parseInt(res.toString(), 2) % 5 == 0) ar.add(true); else ar.add(false); } return ar; } static long factorial(int i) { long result = 1; for (int factor = 2; factor <= i; factor++) { result *= factor; } return result; } static void reverseRange(int[] arr, int start, int end) { int[] res = new int[end - start + 1]; for (int i = start; i < end; i++) res[i - start] = arr[i]; reverse(res); for (int i : res) System.out.print(i + "--"); System.out.println(""); for (int i = start; i < end; i++) arr[i] = res[i - start]; } class LRU { /* Pseudo code int size; // size of cache double linked list // maintains elements; head tail // constructor { size = n dll = new dll head = tail } boolean checkforhit(int k){ for(tail -> head) if(hit){ updatedll() return true; } return false } void put(int k){ if(checkforhit(k)) get(k) else head = k tail --; } int get(dll) search and return k void updatedll(int k){ //find node where val == k; from val to head shift values back head = k } */ } class Bitset { int[] arr; boolean allv; boolean onev; int cnt; int l; public Bitset(int size) { arr = new int[size]; l = size; Arrays.fill(arr, 0); allv = false; onev = false; cnt = 0; } public void fix(int idx) { if (idx <= this.arr.length && arr[idx] == 0) { arr[idx] = 1; onev = true; cnt++; } if (cnt == l) allv = true; } public void unfix(int idx) { if (idx <= this.arr.length && arr[idx] == 1) { arr[idx] = 0; allv = false; cnt--; } if (cnt == 0) onev = false; } public void flip() { for (int i = 0; i < l; i++) { if (arr[i] == 0) arr[i] = 1; else arr[i] = 0; } cnt = l - cnt; if (cnt == 0) onev = false; else onev = true; if (cnt == l) allv = true; else allv = false; } public boolean all() { return this.allv; } public boolean one() { return this.onev; } public int count() { return cnt; } public String toString() { StringBuilder sb = new StringBuilder(); for (int i : arr) sb.append(i); return sb.toString(); } } public long smallestNumber(long num) { long res = 0; //Arrays.sort(pl,Comparator.comparingInt(ar -> ar.b).thenComparingInt()); ArrayList<Long> arr = new ArrayList<>(); long n = Math.abs(num); int zc = 0; if (num == 0) return 0; StringBuilder sb = new StringBuilder(); while (n > 0) { arr.add(n % 10); if (n % 10 == 0) zc++; n /= 10; } if (num > 0) { Collections.sort(arr); sb.append(arr.get(zc)); for (int i = 0; i < zc; i++) sb.append(0); for (int i = zc + 1; i < arr.size(); i++) sb.append(arr.get(i)); } else { Collections.sort(arr, Collections.reverseOrder()); for (int i = 0; i < arr.size(); i++) sb.append(arr.get(i)); } res = Long.parseLong(sb.toString()); if (num < 0) res *= (-1); return res; } static int getDigitSum(long n) { int t = 0; while (n > 0) { t += (n % 10); n /= 10; } return t; } static class Node { int n; int a; int s; public int getA() { return a; } public int getAvg() { return s; } Node(int a, int s, int n) { this.a = a; this.s = s; this.n = n; } } /* sorting based on number then age Comparator<Triplet> employeeAgeComparator = Comparator.comparingInt(Triplet::getA).reversed(); final Function<Triplet, String> byTheirName = person -> person.getName(); Arrays.sort(tarr,employeeAgeComparator.thenComparing(byTheirName)); */ //Updation Required //Fenwick Tree (customisable) //Segment Tree (customisable) //-----CURRENTLY PRESENT-------// //Graph //DSU //powerMODe //power //Segment Tree (work on this one) //Prime Sieve //Count Divisors //Next Permutation //Get NCR //isVowel //Sort (int) //Sort (long) //Binomial Coefficient //Pair //Triplet //lcm (int & long) //gcd (int & long) //gcd (for binomial coefficient) //swap (int & char) //reverse //Fast input and output //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- static boolean isPrime(long n) { if (n < 2) return false; if (n == 2 || n == 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; long sqrtN = (long) Math.sqrt(n) + 1; for (long i = 6L; i <= sqrtN; i += 6) { if (n % (i - 1) == 0 || n % (i + 1) == 0) return false; } return true; } static boolean isPalindrome(String str) { int i = 0, j = str.length() - 1; while (i < j) { if (str.charAt(i) != str.charAt(j)) return false; i++; j--; } return true; } //GRAPH (basic structure) public static class Graph { public int V; public ArrayList<ArrayList<Integer>> edges; //2 -> [0,1,2] (current) Graph(int V) { this.V = V; edges = new ArrayList<>(V + 1); for (int i = 0; i <= V; i++) { edges.add(new ArrayList<>()); } } public void addEdge(int from, int to) { edges.get(from).add(to); } } //DSU (path and rank optimised) public static class DisjointUnionSets { int[] rank, parent; int n; public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; Arrays.fill(rank, 1); Arrays.fill(parent, -1); this.n = n; } public int find(int curr) { if (parent[curr] == -1) return curr; //path compression optimisation return parent[curr] = find(parent[curr]); } public void union(int a, int b) { int s1 = find(a); int s2 = find(b); if (s1 != s2) { if (rank[s1] < rank[s2]) { parent[s1] = s2; rank[s2] += rank[s1]; } else { parent[s2] = s1; rank[s1] += rank[s2]; } } } } //with mod public static long powerMOD(long x, long y) { long res = 1L; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) { x %= mod; res %= mod; res = (res * x) % mod; } // y must be even now y = y >> 1; // y = y/2 x %= mod; x = (x * x) % mod; // Change x to x^2 } return res % mod; } //without mod public static long power(long x, long y) { long res = 1L; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) { res = (res * x); } // y must be even now y = y >> 1; // y = y/ x = (x * x); } return res; } public static class segmentTree { public long[] arr; public long[] tree; public long[] lazy; segmentTree(long[] array) { int n = array.length; arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = array[i]; tree = new long[4 * n + 1]; lazy = new long[4 * n + 1]; } public void build(int[] arr, int s, int e, int[] tree, int index) { if (s == e) { tree[index] = arr[s]; return; } //otherwise divide in two parts and fill both sides simply int mid = (s + e) / 2; build(arr, s, mid, tree, 2 * index); build(arr, mid + 1, e, tree, 2 * index + 1); //who will build the current position dude tree[index] = Math.min(tree[2 * index], tree[2 * index + 1]); } public int query(int sr, int er, int sc, int ec, int index, int[] tree) { if (lazy[index] != 0) { tree[index] += lazy[index]; if (sc != ec) { lazy[2 * index + 1] += lazy[index]; lazy[2 * index] += lazy[index]; } lazy[index] = 0; } //no overlap if (sr > ec || sc > er) return Integer.MAX_VALUE; //found the index baby if (sr <= sc && ec <= er) return tree[index]; //finding the index on both sides hehehehhe int mid = (sc + ec) / 2; int left = query(sr, er, sc, mid, 2 * index, tree); int right = query(sr, er, mid + 1, ec, 2 * index + 1, tree); return Integer.min(left, right); } //now we will do point update implementation //it should be simple then we expected for sure public void update(int index, int indexr, int increment, int[] tree, int s, int e) { if (lazy[index] != 0) { tree[index] += lazy[index]; if (s != e) { lazy[2 * index + 1] = lazy[index]; lazy[2 * index] = lazy[index]; } lazy[index] = 0; } //no overlap if (indexr < s || indexr > e) return; //found the required index if (s == e) { tree[index] += increment; return; } //search for the index on both sides int mid = (s + e) / 2; update(2 * index, indexr, increment, tree, s, mid); update(2 * index + 1, indexr, increment, tree, mid + 1, e); //now update the current range simply tree[index] = Math.min(tree[2 * index + 1], tree[2 * index]); } public void rangeUpdate(int[] tree, int index, int s, int e, int sr, int er, int increment) { //if not at all in the same range if (e < sr || er < s) return; //complete then also move forward if (s == e) { tree[index] += increment; return; } //otherwise move in both subparts int mid = (s + e) / 2; rangeUpdate(tree, 2 * index, s, mid, sr, er, increment); rangeUpdate(tree, 2 * index + 1, mid + 1, e, sr, er, increment); //update current range too na //i always forget this step for some reasons hehehe, idiot tree[index] = Math.min(tree[2 * index], tree[2 * index + 1]); } public void rangeUpdateLazy(int[] tree, int index, int s, int e, int sr, int er, int increment) { //update lazy values //resolve lazy value before going down if (lazy[index] != 0) { tree[index] += lazy[index]; if (s != e) { lazy[2 * index + 1] += lazy[index]; lazy[2 * index] += lazy[index]; } lazy[index] = 0; } //no overlap case if (sr > e || s > er) return; //complete overlap if (sr <= s && er >= e) { tree[index] += increment; if (s != e) { lazy[2 * index + 1] += increment; lazy[2 * index] += increment; } return; } //otherwise go on both left and right side and do your shit int mid = (s + e) / 2; rangeUpdateLazy(tree, 2 * index, s, mid, sr, er, increment); rangeUpdateLazy(tree, 2 * index + 1, mid + 1, e, sr, er, increment); tree[index] = Math.min(tree[2 * index + 1], tree[2 * index]); return; } } //ceil int static int ceil(int x, int y) { return (x % y == 0 ? x / y : (x / y + 1)); } //ceil long static long ceil(long x, long y) { return (x % y == 0 ? x / y : (x / y + 1)); } //sqrt static long sqrt(long z) { long sqz = (long) Math.sqrt(z); while (sqz * 1L * sqz < z) { sqz++; } while (sqz * 1L * sqz > z) { sqz--; } return sqz; } //log base 2 static int log2(int N) { int result = (int) (Math.log(N) / Math.log(2)); return result; } //power of two static boolean isPowerOfTwo(int n) { if (n == 0) return false; while (n != 1) { if (n % 2 != 0) return false; n = n / 2; } return true; } public static int lower_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = -1; while (low <= high) { mid = (low + high) / 2; if (arr[mid] > x) { high = mid - 1; } else { ans = mid; low = mid + 1; } } return ans; } public static int upper_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = arr.length; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) { ans = mid; high = mid - 1; } else { low = mid + 1; } } return ans; } //prime sieve public static void primeSieve(int n) { BitSet bitset = new BitSet(n + 1); for (long i = 0; i < n; i++) { if (i == 0 || i == 1) { bitset.set((int) i); continue; } if (bitset.get((int) i)) continue; primeNumbers.add((int) i); for (long j = i; j <= n; j += i) bitset.set((int) j); } } //number of divisors public static int countDivisors(long number) { if (number == 1) return 1; List<Integer> primeFactors = new ArrayList<>(); int index = 0; long curr = primeNumbers.get(index); while (curr * curr <= number) { while (number % curr == 0) { number = number / curr; primeFactors.add((int) curr); } index++; curr = primeNumbers.get(index); } if (number != 1) primeFactors.add((int) number); int current = primeFactors.get(0); int totalDivisors = 1; int currentCount = 2; for (int i = 1; i < primeFactors.size(); i++) { if (primeFactors.get(i) == current) { currentCount++; } else { totalDivisors *= currentCount; currentCount = 2; current = primeFactors.get(i); } } totalDivisors *= currentCount; return totalDivisors; } //now adding next permutation function to java hehe public static boolean next_permutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1; ; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } //finding the value of NCR in O(RlogN) time and O(1) space public static long getNcR(int n, int r) { long p = 1, k = 1; if (n - r < r) r = n - r; if (r != 0) { while (r > 0) { p *= n; k *= r; long m = __gcd(p, k); p /= m; k /= m; n--; r--; } } else { p = 1; } return p; } //is vowel function public static boolean isVowel(char c) { return (c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O' || c == 'u' || c == 'U'); } public static boolean isSingleHole(char c) { return (c == 'A' || c == 'D' || c == 'O' || c == 'R' || c == 'P' || c == 'Q'); } //to sort the array with better method public static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } //sort long public static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } //for calculating binomialCoeff public static int binomialCoeff(int n, int k) { int C[] = new int[k + 1]; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous row for (int j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k]; } //Pair with int int public static class Pair { public int a; public int b; public String s; public long l; Pair(int a, int b) { this.a = a; this.b = b; } Pair(long a, int b) { this.l = a; this.b = b; } Pair(int a, String b) { this.a = a; this.s = b; } public int getA() { return this.a; } @Override public String toString() { return a + " -> " + b; } } //Triplet with int int int public static class Triplet { public int a; public int b; public int c; public String name; Triplet(String name, int a, int b, int c) { this.a = a; this.b = b; this.c = c; this.name = name; } public int getA() { return a; } public int getB() { return b; } public int getC() { return c; } public String getName() { return name; } @Override public String toString() { return "Triplet{" + "a=" + a + ", b=" + b + ", c=" + c + ", name='" + name + '\'' + '}'; } } //Shortcut function public static long lcm(long a, long b) { return a * (b / gcd(a, b)); } //let's make one for calculating lcm basically public static int lcm(int a, int b) { return (a * b) / gcd(a, b); } //int version for gcd public static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } //long version for gcd public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } //for ncr calculator(ignore this code) public static long __gcd(long n1, long n2) { long gcd = 1; for (int i = 1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if (n1 % i == 0 && n2 % i == 0) { gcd = i; } } return gcd; } static boolean isOddBitsSet(int n) { if (Integer.bitCount(n) % 2 == 0) return true; return false; } //swapping two elements in an array public static void swap(int[] arr, int left, int right) { int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } public static void swap(long[] arr, int left, int right) { long temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //for char array public static void swap(char[] arr, int left, int right) { char temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //reversing an array public static void reverse(int[] arr) { int left = 0; int right = arr.length - 1; while (left <= right) { swap(arr, left, right); left++; right--; } } public static void reverse(long[] arr) { int left = 0; int right = arr.length - 1; while (left <= right) { swap(arr, left, right); left++; right--; } } public static long expo(long a, long b, long mod) { long res = 1; while (b > 0) { if ((b & 1) == 1L) res = (res * a) % mod; //think about this one for a second a = (a * a) % mod; b = b >> 1; } return res; } //SOME EXTRA DOPE FUNCTIONS public static long mminvprime(long a, long b) { return expo(a, b - 2, b); } public static long mod_add(long a, long b, long m) { a = a % m; b = b % m; return (((a + b) % m) + m) % m; } public static long mod_sub(long a, long b, long m) { a = a % m; b = b % m; return (((a - b) % m) + m) % m; } public static long mod_mul(long a, long b, long m) { a = a % m; b = b % m; return (((a * b) % m) + m) % m; } public static long mod_div(long a, long b, long m) { a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m; } //O(n) every single time remember that public static long nCr(long N, long K, long mod) { long upper = 1L; long lower = 1L; long lowerr = 1L; for (long i = 1; i <= N; i++) { upper = mod_mul(upper, i, mod); } for (long i = 1; i <= K; i++) { lower = mod_mul(lower, i, mod); } for (long i = 1; i <= (N - K); i++) { lowerr = mod_mul(lowerr, i, mod); } // out.println(upper + " " + lower + " " + lowerr); long answer = mod_mul(lower, lowerr, mod); answer = mod_div(upper, answer, mod); return answer; } // ll *fact = new ll[2 * n + 1]; // ll *ifact = new ll[2 * n + 1]; // fact[0] = 1; // ifact[0] = 1; // for (ll i = 1; i <= 2 * n; i++) // { // fact[i] = mod_mul(fact[i - 1], i, MOD1); // ifact[i] = mminvprime(fact[i], MOD1); // } //ifact is basically inverse factorial in here!!!!!(imp) public static long combination(long n, long r, long m, long[] fact, long[] ifact) { long val1 = fact[(int) n]; long val2 = ifact[(int) (n - r)]; long val3 = ifact[(int) r]; return (((val1 * val2) % m) * val3) % m; } static int[] readArray(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) sc.nextInt(); } return res; } static double[] readArrayDouble(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = sc.nextDouble(); } return res; } static long[] readArrayLong(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = sc.nextLong(); } return res; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } } import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.DecimalFormat; import java.util.*; public class Main { //class Codechef { static FastReader sc; static StringBuilder sb = new StringBuilder(); static int mod = (int) (Math.pow(10, 9) + 7); static final int dx[] = {-1, 0, 1, 0}, dy[] = {0, -1, 0, 1}; static final int[] dx8 = {-1, -1, -1, 0, 0, 1, 1, 1}, dy8 = {-1, 0, 1, -1, 1, -1, 0, 1}; static final int[] dx9 = {-1, -1, -1, 0, 0, 0, 1, 1, 1}, dy9 = {-1, 0, 1, -1, 0, 1, -1, 0, 1}; static HashSet<Character> set; static final double eps = 1e-10; static long[] arr = new long[100001]; static List<Integer> primeNumbers = new ArrayList<>(); static int cnt = 0; static HashSet<Character> hor = new HashSet<>(); static HashSet<Character> ver = new HashSet<>(); public static void main(String[] args) { sc = new FastReader(); int testCases = 1; hor.add('L'); hor.add('R'); ver.add('U'); ver.add('D'); //primeSieve(40000000); //testCases = sc.nextInt(); while (testCases-- > 0) compute(); //sb.append(cnt); System.out.println(sb.toString()); } public static void compute() { //Arrays.sort(al,Comparator.comparingInt(ar -> ar.value)); //Arrays.sort(al,Comparator.comparingInt(ar -> ar.index)); //shortestCompletingWord() // String s="1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"; int n=sc.nextInt(); sb.append("3."); for(int i=0;i<n;i++){ sb.append(s.charAt(i)); } /*res.append(s.charAt(i)); if(i<l-2 && check(s.substring(i,i+3))) i+=2;*/ //sb.append(((risk^x)&risk)>0?(-1):(risk^x)).append("\n"); //sb.append(isValid(x,y,z)).append("\n"); // int sec = Arrays.stream(arr).sorted().distinct().skip(1).findFirst().getAsInt(); } public int numberOfEmployeesWhoMetTarget(int[] hours, int target) { return ((int) Arrays.stream(hours).filter(i -> i >= target).count()); } public boolean isSame(String a,String b){ int l1 = a.length(),l2=b.length(); if(l1!=l2) return false; for(int i=0;i<l1;i++){ if(a.charAt(i)!=b.charAt(l1-i-1)) return false; } return true; } public int findDelayedArrivalTime(int arrivalTime, int delayedTime) { return (delayedTime+arrivalTime)%24; } public String makeSmallestPalindrome(String s) { StringBuilder res = new StringBuilder(); int l=s.length(); for(int i=0;i<=l/2;i++){ if(s.charAt(i)==s.charAt(l-1-i)) res.append(s.charAt(i)); else res.append(s.charAt(i)<s.charAt(l-1-i)?s.charAt(i):s.charAt(l-i-1)); } if(l%2==0) return res.toString()+res.reverse().toString(); return res.toString()+s.charAt(l/2)+res.reverse().toString(); } public int minimizedStringLength(String s) { int[] arr = new int[26]; for (char c : s.toCharArray()) arr[c - 'a']++; int res = 0; for (int i : arr) { if (i > 0) res++; } return res; } private static int findsum(int n) { int res = 0; while (n > 0) { res++; n /= 10; } return res; } public static boolean check(char a, char b) { if (a == '0' || a == 'o') { if (b != '0' && b != 'o') return false; return true; } if (a == '1' || a == 'l') { if (b != '1' && b != 'l') return false; return true; } return false; } public String removeTrailingZeros(String num) { int l = num.length(); while (num.charAt(l--) == '0') ; return num.substring(0, l); } public int buyChoco(int[] prices, int money) { int sum = Arrays.stream(prices).sorted().limit(2).sum(); return money >= sum ? money - sum : money; } public static long nChooseK(int n, int k) { if (k > n) { return 0; // invalid input } long numerator = 1L; for (int i = 1; i <= k; i++) { numerator *= (n - (k - i)); numerator /= i; } return numerator; } public int maximizeSum(int[] nums, int k) { int max = Arrays.stream(nums).max().getAsInt(); max *= 2; max += (k - 1); max *= k; max /= 2; return max; } public static boolean check(String s) { //System.out.println(s); if (s.equalsIgnoreCase("and") || s.equalsIgnoreCase("not") || s.equalsIgnoreCase("that") || s.equalsIgnoreCase("the") || s.equalsIgnoreCase("you")) return true; return false; } public int minNumber(int[] nums1, int[] nums2) { int min1 = Arrays.stream(nums1).min().getAsInt(); int min2 = Arrays.stream(nums1).min().getAsInt(); Arrays.sort(nums1); Arrays.sort(nums2); for (int i : nums1) { for (int ii : nums2) { if (i == ii) return i; } } int m1 = Math.min(min1, min2); int m2 = min2 + min1 - m1; return 10 * m1 + m2; } public int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) { int res = 0; if (k <= numOnes) return Math.min(k, numOnes); else { res += numOnes; k -= numOnes; } if (k <= numZeros) return res; else k -= numZeros; if (k <= numNegOnes) return res - numNegOnes; return -1 * (numNegOnes - res); } public int passThePillow(int n, int time) { int q = time / n; if (q % 2 == 0) return time % n; return n - time % n; } public static boolean match(Character c, Character d) { if (ver.contains(c) && ver.contains(d)) return true; if (hor.contains(c) && hor.contains(d)) return true; return false; } public int[] evenOddBit(int n) { int[] res = new int[2]; int odd = 0, even = 0; String s = Integer.toBinaryString(n); System.out.println(s); int l = s.length(), t = 0; for (int i = l - 1; i >= 0; i--) { System.out.println(s.charAt(i)); if (s.charAt(i) == 1) { if (t % 2 == 0) even++; else odd++; t++; } } res[0] = even; res[1] = odd; return res; } public int maxScore(int[] nums) { long res = 0; int rr = 0; ArrayList<Integer> negs = new ArrayList<>(); for (int i : nums) { if (i >= 0) { rr++; res += i; } else negs.add(i); } Collections.sort(negs, Collections.reverseOrder()); for (int i : negs) { res += i; if (res > 0) rr++; else break; } return rr; } public int vowelStrings(String[] words, int left, int right) { int res = 0; for (int i = left; i <= right; i++) { if (isVowel(words[i].charAt(0)) && isVowel(words[i].charAt(words[i].length() - 1))) res++; } return res; } static int nCr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } // Returns factorial of n static int fact(int n) { if (n == 0) return 1; int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res; } public int splitNum(int num) { StringBuilder n1 = new StringBuilder(); StringBuilder n2 = new StringBuilder(); ArrayList<Integer> list = new ArrayList<>(); while (num > 0) { list.add(num % 10); num /= 10; } Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < list.size(); i++) { if (i % 2 == 0) n1.append(list.get(i)); else n2.append(list.get(i)); } System.out.println(n1.toString() + " " + n2.toString()); return Integer.parseInt(n1.toString()) + Integer.parseInt(n2.toString()); } public int minMaxDifference(int num) { int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int i = 0; i < 10; i++) { min = Math.min(min, Integer.parseInt(String.valueOf(num).replaceAll(Integer.toString(i), "0"))); max = Math.max(max, Integer.parseInt(String.valueOf(num).replaceAll(Integer.toString(i), "9"))); } return max - min; } public int[] leftRigthDifference(int[] nums) { int l = nums.length; int[] lsum = new int[l]; int[] rsum = new int[l]; int[] res = new int[l]; for (int i = 1; i < l; i++) lsum[i] += (nums[i - 1] + lsum[i - 1]); for (int i = l - 2; i >= 0; i--) rsum[i] += (nums[i + 1] + rsum[i + 1]); for (int i = 0; i < l; i++) res[i] = Math.abs(lsum[i] - rsum[i]); return res; } public static String isValid(int x, int y, int z) { if (x == y && x == z) return "YES"; else if (x != y && y != z && x != z) return "NO"; else { if (x == y && x != z && z > x) return "YES"; else if (x == z && x != y && y > x) return "YES"; else if (y == z && y != x && x > y) return "YES"; } return "NO"; } public long findTheArrayConcVal(int[] nums) { long res = 0; int l = nums.length; for (int i = 0; i < l / 2; i++) { res += concat(nums[i], nums[l - i - 1]); } if (l % 2 == 0) res += nums[l / 2]; return res; } public int concat(int a, int b) { StringBuilder res = new StringBuilder(); res.append(a).append(b); System.out.println(res.toString()); return Integer.parseInt(res.toString()); } public int[] vowelStrings(String[] words, int[][] queries) { int l = words.length; int ql = queries.length; int[] rll = new int[l + 1]; int[] res = new int[ql]; for (int i = 1; i <= l; i++) { if (isVowel(words[i - 1].charAt(0)) && isVowel(words[i - 1].charAt(words[i - 1].length() - 1))) rll[i]++; rll[i] += rll[i - 1]; } for (int i = 0; i < ql; i++) { res[i] = (rll[queries[i][1] + 1] - rll[queries[i][0]]); } return res; } public int getCommon(int[] nums1, int[] nums2) { int l1 = nums1.length, l2 = nums2.length; int s1 = 0, s2 = 0; while (s1 < l1 && s2 < l2) { System.out.println(nums1[s1] + " " + nums2[s2]); if (nums1[s1] == nums2[s2]) return nums1[s1]; else if (nums1[s1] < nums2[s2]) return s1++; else s2++; } return -1; } public int closetTarget(String[] words, String target, int startIndex) { int n = words.length; int dis1 = 0, dis2 = 0; boolean ispresent = false; for (String s : words) { if (s.equals(target)) { ispresent = true; break; } } if (!ispresent) return -1; for (int i = startIndex; i < words.length; i++) { if (words[i].equals(target)) break; dis1++; } dis1 = Math.min(dis1, n + 1 - dis1); for (int i = startIndex; i >= 0; i--) { if (words[i].equals(target)) break; dis2++; } dis2 = Math.min(dis2, n + 1 - dis2); return Math.min(dis1, dis2); } public int[] plusOne(int[] a) { int[] arr = new int[a.length + 1]; int carry = 1, l = a.length; for (int i = l - 1; i >= 0; i--) { arr[i + 1] = a[i] + carry; if (arr[i + 1] == 10) { arr[i + 1] = 0; carry = 1; } else carry = 0; } System.out.println(carry); arr[0] = carry; if (arr[0] == 0) { int[] res = new int[l]; for (int i = 1; i < l; i++) res[i - 1] = arr[i]; return res; } return arr; } public int captureForts(int[] forts) { int sp = 0, ep = forts.length - 1; while (forts[sp] == 0) sp++; while (forts[ep] == 0) ep--; if (sp + 1 <= ep) return 0; int max = 0, t = 0; System.out.println(sp + " " + ep); for (int i = sp + 1; i < ep; i++) { while (forts[i] == 0) { i++; t++; } max = Math.max(max, t); t = 0; } return max; } public boolean check(int[] arr) { int l = arr.length; int si = l / 2; int sum = 0; for (int i : arr) sum += i; if (sum % 2 == 1 && si != 1) return false; if (sum % si != 0) return false; int val = sum / si; Arrays.sort(arr); for (int i = 0; i < l / 2; i++) { if (arr[i] + arr[l - 1 - i] != val) return false; } return true; } public int similarPairs(String[] words) { int res = 0, l = words.length; for (int i = 0; i < l - 1; i++) { for (int j = i + 1; j < l; j++) { if (similar(words[i], words[j])) { res++; System.out.println(words[i] + " " + words[j]); } } } return res; } public static boolean similar(String a, String j) { int[] arr = new int[26]; for (char c : a.toCharArray()) arr[c - 'a']++; for (char c : j.toCharArray()) { if (arr[c - 'a'] == 0) return false; } for (char c : j.toCharArray()) arr[c - 'a'] = 0; for (int i : arr) { if (i == 0) return false; } return true; } public boolean validPalindrome(String s) { if (isPalindrome(s)) return true; String result; for (int i = 0; i < s.length(); i++) { result = s.substring(0, i) + s.substring(i + 1); if (isPalindrome(result)) return true; } return false; } public int distinctAverages(int[] nums) { HashSet<Double> set = new HashSet<>(); Arrays.sort(nums); int l = nums.length; double t; for (int i = 0; i < l / 2; i++) { t = nums[i] + nums[l - i - 1]; t /= 2; set.add(t); } return set.size(); } public double[] convertTemperature(double celsius) { double[] res = {celsius + 273.15, (celsius * 1.8) + 32}; return res; } public int unequalTriplets(int[] nums) { int res = 0, l = nums.length; for (int i = 0; i < l; i++) { for (int j = i + 1; j < l; j++) { if (nums[i] != nums[j]) { for (int k = j + 1; k < l; k++) { if (nums[i] != nums[k] && nums[k] != nums[j]) res++; } } } } return res; } public int maximumValue(String[] strs) { int res = 0; for (String s : strs) { if (isNumber(s)) res = Math.max(res, Integer.parseInt(s)); else res = Math.max(res, s.length()); } return res; } public boolean isNumber(String s) { for (char c : s.toCharArray()) { if (!Character.isDigit(c)) return false; } return true; } public static boolean isPerfectSquare(int n) { int nn = (int) Math.sqrt(n); if (nn * nn == n) return true; return false; } public int garbageCollection(String[] garbage, int[] travel) { int res = 0; int gi = -1, mi = -1, pi = -1; int gl = garbage.length; for (int i = gl - 1; i >= 0; i--) { if (garbage[i].contains("G")) { gi = i; break; } } for (int i = gl - 1; i >= 0; i--) { if (garbage[i].contains("P")) { pi = i; break; } } for (int i = gl - 1; i >= 0; i--) { if (garbage[i].contains("M")) { mi = i; break; } } System.out.println(gi + " " + pi + " " + mi); for (int i = 1; i <= gi; i++) { res += travel[i - 1]; if (garbage[i].contains("G")) res += count(garbage[i], 'G'); } for (int i = 1; i <= mi; i++) { res += travel[i - 1]; if (garbage[i].contains("M")) res += count(garbage[i], 'M'); } for (int i = 1; i <= pi; i++) { res += travel[i - 1]; if (garbage[i].contains("P")) res += count(garbage[i], 'P'); } if (garbage[0].contains("P")) res += count(garbage[0], 'P'); if (garbage[0].contains("M")) res += count(garbage[0], 'M'); if (garbage[0].contains("G")) res += count(garbage[0], 'G'); return res; } public int count(String s, char p) { int res = 0; for (char c : s.toCharArray()) { if (c == (p)) res++; } return res; } public int reverseInt(int n) { StringBuffer sbr = new StringBuffer(String.valueOf(n)); return Integer.parseInt(sbr.reverse().toString()); } public boolean equalFrequency(String word) { int[] arr = new int[26]; for (char c : word.toCharArray()) arr[c - 'a']++; HashSet<Integer> set = new HashSet<>(); int max = -1; for (int i : arr) { if (i > 0) set.add(i); max = Math.max(max, i); } Integer[] inset = set.toArray(new Integer[set.size()]); if (set.size() != 2) return false; if (Math.abs(inset[0] - inset[1]) != 1) return false; int maxcnt = 0; for (int i : arr) { if (i == max) maxcnt++; } return maxcnt == 1 ? true : false; } public List<Boolean> prefixesDivBy5(int[] nums) { int l = nums.length; List<Boolean> ar = new ArrayList<>(); StringBuilder res = new StringBuilder(); for (int i : nums) { res.append(i); if (Integer.parseInt(res.toString(), 2) % 5 == 0) ar.add(true); else ar.add(false); } return ar; } static long factorial(int i) { long result = 1; for (int factor = 2; factor <= i; factor++) { result *= factor; } return result; } static void reverseRange(int[] arr, int start, int end) { int[] res = new int[end - start + 1]; for (int i = start; i < end; i++) res[i - start] = arr[i]; reverse(res); for (int i : res) System.out.print(i + "--"); System.out.println(""); for (int i = start; i < end; i++) arr[i] = res[i - start]; } class LRU { /* Pseudo code int size; // size of cache double linked list // maintains elements; head tail // constructor { size = n dll = new dll head = tail } boolean checkforhit(int k){ for(tail -> head) if(hit){ updatedll() return true; } return false } void put(int k){ if(checkforhit(k)) get(k) else head = k tail --; } int get(dll) search and return k void updatedll(int k){ //find node where val == k; from val to head shift values back head = k } */ } class Bitset { int[] arr; boolean allv; boolean onev; int cnt; int l; public Bitset(int size) { arr = new int[size]; l = size; Arrays.fill(arr, 0); allv = false; onev = false; cnt = 0; } public void fix(int idx) { if (idx <= this.arr.length && arr[idx] == 0) { arr[idx] = 1; onev = true; cnt++; } if (cnt == l) allv = true; } public void unfix(int idx) { if (idx <= this.arr.length && arr[idx] == 1) { arr[idx] = 0; allv = false; cnt--; } if (cnt == 0) onev = false; } public void flip() { for (int i = 0; i < l; i++) { if (arr[i] == 0) arr[i] = 1; else arr[i] = 0; } cnt = l - cnt; if (cnt == 0) onev = false; else onev = true; if (cnt == l) allv = true; else allv = false; } public boolean all() { return this.allv; } public boolean one() { return this.onev; } public int count() { return cnt; } public String toString() { StringBuilder sb = new StringBuilder(); for (int i : arr) sb.append(i); return sb.toString(); } } public long smallestNumber(long num) { long res = 0; //Arrays.sort(pl,Comparator.comparingInt(ar -> ar.b).thenComparingInt()); ArrayList<Long> arr = new ArrayList<>(); long n = Math.abs(num); int zc = 0; if (num == 0) return 0; StringBuilder sb = new StringBuilder(); while (n > 0) { arr.add(n % 10); if (n % 10 == 0) zc++; n /= 10; } if (num > 0) { Collections.sort(arr); sb.append(arr.get(zc)); for (int i = 0; i < zc; i++) sb.append(0); for (int i = zc + 1; i < arr.size(); i++) sb.append(arr.get(i)); } else { Collections.sort(arr, Collections.reverseOrder()); for (int i = 0; i < arr.size(); i++) sb.append(arr.get(i)); } res = Long.parseLong(sb.toString()); if (num < 0) res *= (-1); return res; } static int getDigitSum(long n) { int t = 0; while (n > 0) { t += (n % 10); n /= 10; } return t; } static class Node { int n; int a; int s; public int getA() { return a; } public int getAvg() { return s; } Node(int a, int s, int n) { this.a = a; this.s = s; this.n = n; } } /* sorting based on number then age Comparator<Triplet> employeeAgeComparator = Comparator.comparingInt(Triplet::getA).reversed(); final Function<Triplet, String> byTheirName = person -> person.getName(); Arrays.sort(tarr,employeeAgeComparator.thenComparing(byTheirName)); */ //Updation Required //Fenwick Tree (customisable) //Segment Tree (customisable) //-----CURRENTLY PRESENT-------// //Graph //DSU //powerMODe //power //Segment Tree (work on this one) //Prime Sieve //Count Divisors //Next Permutation //Get NCR //isVowel //Sort (int) //Sort (long) //Binomial Coefficient //Pair //Triplet //lcm (int & long) //gcd (int & long) //gcd (for binomial coefficient) //swap (int & char) //reverse //Fast input and output //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- static boolean isPrime(long n) { if (n < 2) return false; if (n == 2 || n == 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; long sqrtN = (long) Math.sqrt(n) + 1; for (long i = 6L; i <= sqrtN; i += 6) { if (n % (i - 1) == 0 || n % (i + 1) == 0) return false; } return true; } static boolean isPalindrome(String str) { int i = 0, j = str.length() - 1; while (i < j) { if (str.charAt(i) != str.charAt(j)) return false; i++; j--; } return true; } //GRAPH (basic structure) public static class Graph { public int V; public ArrayList<ArrayList<Integer>> edges; //2 -> [0,1,2] (current) Graph(int V) { this.V = V; edges = new ArrayList<>(V + 1); for (int i = 0; i <= V; i++) { edges.add(new ArrayList<>()); } } public void addEdge(int from, int to) { edges.get(from).add(to); } } //DSU (path and rank optimised) public static class DisjointUnionSets { int[] rank, parent; int n; public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; Arrays.fill(rank, 1); Arrays.fill(parent, -1); this.n = n; } public int find(int curr) { if (parent[curr] == -1) return curr; //path compression optimisation return parent[curr] = find(parent[curr]); } public void union(int a, int b) { int s1 = find(a); int s2 = find(b); if (s1 != s2) { if (rank[s1] < rank[s2]) { parent[s1] = s2; rank[s2] += rank[s1]; } else { parent[s2] = s1; rank[s1] += rank[s2]; } } } } //with mod public static long powerMOD(long x, long y) { long res = 1L; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) { x %= mod; res %= mod; res = (res * x) % mod; } // y must be even now y = y >> 1; // y = y/2 x %= mod; x = (x * x) % mod; // Change x to x^2 } return res % mod; } //without mod public static long power(long x, long y) { long res = 1L; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) { res = (res * x); } // y must be even now y = y >> 1; // y = y/ x = (x * x); } return res; } public static class segmentTree { public long[] arr; public long[] tree; public long[] lazy; segmentTree(long[] array) { int n = array.length; arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = array[i]; tree = new long[4 * n + 1]; lazy = new long[4 * n + 1]; } public void build(int[] arr, int s, int e, int[] tree, int index) { if (s == e) { tree[index] = arr[s]; return; } //otherwise divide in two parts and fill both sides simply int mid = (s + e) / 2; build(arr, s, mid, tree, 2 * index); build(arr, mid + 1, e, tree, 2 * index + 1); //who will build the current position dude tree[index] = Math.min(tree[2 * index], tree[2 * index + 1]); } public int query(int sr, int er, int sc, int ec, int index, int[] tree) { if (lazy[index] != 0) { tree[index] += lazy[index]; if (sc != ec) { lazy[2 * index + 1] += lazy[index]; lazy[2 * index] += lazy[index]; } lazy[index] = 0; } //no overlap if (sr > ec || sc > er) return Integer.MAX_VALUE; //found the index baby if (sr <= sc && ec <= er) return tree[index]; //finding the index on both sides hehehehhe int mid = (sc + ec) / 2; int left = query(sr, er, sc, mid, 2 * index, tree); int right = query(sr, er, mid + 1, ec, 2 * index + 1, tree); return Integer.min(left, right); } //now we will do point update implementation //it should be simple then we expected for sure public void update(int index, int indexr, int increment, int[] tree, int s, int e) { if (lazy[index] != 0) { tree[index] += lazy[index]; if (s != e) { lazy[2 * index + 1] = lazy[index]; lazy[2 * index] = lazy[index]; } lazy[index] = 0; } //no overlap if (indexr < s || indexr > e) return; //found the required index if (s == e) { tree[index] += increment; return; } //search for the index on both sides int mid = (s + e) / 2; update(2 * index, indexr, increment, tree, s, mid); update(2 * index + 1, indexr, increment, tree, mid + 1, e); //now update the current range simply tree[index] = Math.min(tree[2 * index + 1], tree[2 * index]); } public void rangeUpdate(int[] tree, int index, int s, int e, int sr, int er, int increment) { //if not at all in the same range if (e < sr || er < s) return; //complete then also move forward if (s == e) { tree[index] += increment; return; } //otherwise move in both subparts int mid = (s + e) / 2; rangeUpdate(tree, 2 * index, s, mid, sr, er, increment); rangeUpdate(tree, 2 * index + 1, mid + 1, e, sr, er, increment); //update current range too na //i always forget this step for some reasons hehehe, idiot tree[index] = Math.min(tree[2 * index], tree[2 * index + 1]); } public void rangeUpdateLazy(int[] tree, int index, int s, int e, int sr, int er, int increment) { //update lazy values //resolve lazy value before going down if (lazy[index] != 0) { tree[index] += lazy[index]; if (s != e) { lazy[2 * index + 1] += lazy[index]; lazy[2 * index] += lazy[index]; } lazy[index] = 0; } //no overlap case if (sr > e || s > er) return; //complete overlap if (sr <= s && er >= e) { tree[index] += increment; if (s != e) { lazy[2 * index + 1] += increment; lazy[2 * index] += increment; } return; } //otherwise go on both left and right side and do your shit int mid = (s + e) / 2; rangeUpdateLazy(tree, 2 * index, s, mid, sr, er, increment); rangeUpdateLazy(tree, 2 * index + 1, mid + 1, e, sr, er, increment); tree[index] = Math.min(tree[2 * index + 1], tree[2 * index]); return; } } //ceil int static int ceil(int x, int y) { return (x % y == 0 ? x / y : (x / y + 1)); } //ceil long static long ceil(long x, long y) { return (x % y == 0 ? x / y : (x / y + 1)); } //sqrt static long sqrt(long z) { long sqz = (long) Math.sqrt(z); while (sqz * 1L * sqz < z) { sqz++; } while (sqz * 1L * sqz > z) { sqz--; } return sqz; } //log base 2 static int log2(int N) { int result = (int) (Math.log(N) / Math.log(2)); return result; } //power of two static boolean isPowerOfTwo(int n) { if (n == 0) return false; while (n != 1) { if (n % 2 != 0) return false; n = n / 2; } return true; } public static int lower_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = -1; while (low <= high) { mid = (low + high) / 2; if (arr[mid] > x) { high = mid - 1; } else { ans = mid; low = mid + 1; } } return ans; } public static int upper_bound(int[] arr, int x) { int low = 0, high = arr.length - 1, mid = -1; int ans = arr.length; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) { ans = mid; high = mid - 1; } else { low = mid + 1; } } return ans; } //prime sieve public static void primeSieve(int n) { BitSet bitset = new BitSet(n + 1); for (long i = 0; i < n; i++) { if (i == 0 || i == 1) { bitset.set((int) i); continue; } if (bitset.get((int) i)) continue; primeNumbers.add((int) i); for (long j = i; j <= n; j += i) bitset.set((int) j); } } //number of divisors public static int countDivisors(long number) { if (number == 1) return 1; List<Integer> primeFactors = new ArrayList<>(); int index = 0; long curr = primeNumbers.get(index); while (curr * curr <= number) { while (number % curr == 0) { number = number / curr; primeFactors.add((int) curr); } index++; curr = primeNumbers.get(index); } if (number != 1) primeFactors.add((int) number); int current = primeFactors.get(0); int totalDivisors = 1; int currentCount = 2; for (int i = 1; i < primeFactors.size(); i++) { if (primeFactors.get(i) == current) { currentCount++; } else { totalDivisors *= currentCount; currentCount = 2; current = primeFactors.get(i); } } totalDivisors *= currentCount; return totalDivisors; } //now adding next permutation function to java hehe public static boolean next_permutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1; ; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } //finding the value of NCR in O(RlogN) time and O(1) space public static long getNcR(int n, int r) { long p = 1, k = 1; if (n - r < r) r = n - r; if (r != 0) { while (r > 0) { p *= n; k *= r; long m = __gcd(p, k); p /= m; k /= m; n--; r--; } } else { p = 1; } return p; } //is vowel function public static boolean isVowel(char c) { return (c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O' || c == 'u' || c == 'U'); } public static boolean isSingleHole(char c) { return (c == 'A' || c == 'D' || c == 'O' || c == 'R' || c == 'P' || c == 'Q'); } //to sort the array with better method public static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } //sort long public static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } //for calculating binomialCoeff public static int binomialCoeff(int n, int k) { int C[] = new int[k + 1]; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous row for (int j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k]; } //Pair with int int public static class Pair { public int a; public int b; public String s; public long l; Pair(int a, int b) { this.a = a; this.b = b; } Pair(long a, int b) { this.l = a; this.b = b; } Pair(int a, String b) { this.a = a; this.s = b; } public int getA() { return this.a; } @Override public String toString() { return a + " -> " + b; } } //Triplet with int int int public static class Triplet { public int a; public int b; public int c; public String name; Triplet(String name, int a, int b, int c) { this.a = a; this.b = b; this.c = c; this.name = name; } public int getA() { return a; } public int getB() { return b; } public int getC() { return c; } public String getName() { return name; } @Override public String toString() { return "Triplet{" + "a=" + a + ", b=" + b + ", c=" + c + ", name='" + name + '\'' + '}'; } } //Shortcut function public static long lcm(long a, long b) { return a * (b / gcd(a, b)); } //let's make one for calculating lcm basically public static int lcm(int a, int b) { return (a * b) / gcd(a, b); } //int version for gcd public static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } //long version for gcd public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } //for ncr calculator(ignore this code) public static long __gcd(long n1, long n2) { long gcd = 1; for (int i = 1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if (n1 % i == 0 && n2 % i == 0) { gcd = i; } } return gcd; } static boolean isOddBitsSet(int n) { if (Integer.bitCount(n) % 2 == 0) return true; return false; } //swapping two elements in an array public static void swap(int[] arr, int left, int right) { int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } public static void swap(long[] arr, int left, int right) { long temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //for char array public static void swap(char[] arr, int left, int right) { char temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //reversing an array public static void reverse(int[] arr) { int left = 0; int right = arr.length - 1; while (left <= right) { swap(arr, left, right); left++; right--; } } public static void reverse(long[] arr) { int left = 0; int right = arr.length - 1; while (left <= right) { swap(arr, left, right); left++; right--; } } public static long expo(long a, long b, long mod) { long res = 1; while (b > 0) { if ((b & 1) == 1L) res = (res * a) % mod; //think about this one for a second a = (a * a) % mod; b = b >> 1; } return res; } //SOME EXTRA DOPE FUNCTIONS public static long mminvprime(long a, long b) { return expo(a, b - 2, b); } public static long mod_add(long a, long b, long m) { a = a % m; b = b % m; return (((a + b) % m) + m) % m; } public static long mod_sub(long a, long b, long m) { a = a % m; b = b % m; return (((a - b) % m) + m) % m; } public static long mod_mul(long a, long b, long m) { a = a % m; b = b % m; return (((a * b) % m) + m) % m; } public static long mod_div(long a, long b, long m) { a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m; } //O(n) every single time remember that public static long nCr(long N, long K, long mod) { long upper = 1L; long lower = 1L; long lowerr = 1L; for (long i = 1; i <= N; i++) { upper = mod_mul(upper, i, mod); } for (long i = 1; i <= K; i++) { lower = mod_mul(lower, i, mod); } for (long i = 1; i <= (N - K); i++) { lowerr = mod_mul(lowerr, i, mod); } // out.println(upper + " " + lower + " " + lowerr); long answer = mod_mul(lower, lowerr, mod); answer = mod_div(upper, answer, mod); return answer; } // ll *fact = new ll[2 * n + 1]; // ll *ifact = new ll[2 * n + 1]; // fact[0] = 1; // ifact[0] = 1; // for (ll i = 1; i <= 2 * n; i++) // { // fact[i] = mod_mul(fact[i - 1], i, MOD1); // ifact[i] = mminvprime(fact[i], MOD1); // } //ifact is basically inverse factorial in here!!!!!(imp) public static long combination(long n, long r, long m, long[] fact, long[] ifact) { long val1 = fact[(int) n]; long val2 = ifact[(int) (n - r)]; long val3 = ifact[(int) r]; return (((val1 * val2) % m) * val3) % m; } static int[] readArray(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) sc.nextInt(); } return res; } static double[] readArrayDouble(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = sc.nextDouble(); } return res; } static long[] readArrayLong(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = sc.nextLong(); } return res; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
ConDefects/ConDefects/Code/abc314_a/Java/44552478
condefects-java_data_692
import java.util.*; public class Main { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); String pi = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"; for (int i = 0; i <= N; i++) { System.out.print(pi.charAt(i)); } } } import java.util.*; public class Main { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); String pi = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"; for (int i = 0; i < N + 2; i++) { System.out.print(pi.charAt(i)); } } }
ConDefects/ConDefects/Code/abc314_a/Java/44702275
condefects-java_data_693
import java.util.*; import java.io.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st = null; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { if(st != null && st.hasMoreTokens()){ str = st.nextToken("\n"); } else{ str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) throws IOException { FastReader fr = new FastReader(); int n = fr.nextInt(); String pi = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"; System.out.println(pi.substring(n+2)); } } import java.util.*; import java.io.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st = null; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { if(st != null && st.hasMoreTokens()){ str = st.nextToken("\n"); } else{ str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) throws IOException { FastReader fr = new FastReader(); int n = fr.nextInt(); String pi = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679"; System.out.println(pi.substring(0,n+2)); } }
ConDefects/ConDefects/Code/abc314_a/Java/44588194
condefects-java_data_694
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; /** * @author YC * @version 1.0 */ public class Main { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static PII[] a = new PII[27]; public static void main(String[] args) throws IOException { String s = br.readLine(); for(int i = 1; i <= 26 ; i ++) { a[i] = new PII(i, 0); } for(int i = 0 ; i < s.length(); i ++) { int index = s.charAt(i) - 'a' + 1; a[index] = new PII(index, a[index].cnt + 1); } Arrays.sort(a,1, 26); System.out.println((char) (a[1].id + 'a' - 1)); } public static class PII implements Comparable<PII> { int id; int cnt; public PII(int id, int cnt) { this.id = id; this.cnt = cnt; } @Override public int compareTo(PII o) { if(this.cnt == o.cnt) return Integer.compare(this.id,o.id); return Integer.compare(o.cnt,this.cnt); } } } import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; /** * @author YC * @version 1.0 */ public class Main { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static PII[] a = new PII[27]; public static void main(String[] args) throws IOException { String s = br.readLine(); for(int i = 1; i <= 26 ; i ++) { a[i] = new PII(i, 0); } for(int i = 0 ; i < s.length(); i ++) { int index = s.charAt(i) - 'a' + 1; a[index] = new PII(index, a[index].cnt + 1); } Arrays.sort(a,1, 27); System.out.println((char) (a[1].id + 'a' - 1)); } public static class PII implements Comparable<PII> { int id; int cnt; public PII(int id, int cnt) { this.id = id; this.cnt = cnt; } @Override public int compareTo(PII o) { if(this.cnt == o.cnt) return Integer.compare(this.id,o.id); return Integer.compare(o.cnt,this.cnt); } } }
ConDefects/ConDefects/Code/abc338_b/Java/53977411
condefects-java_data_695
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String S = scanner.next(); scanner.close(); HashMap<Character, Integer> frequency = new HashMap<Character, Integer>(); for (int i = 0; i < S.length(); i++) { char temp = S.charAt(i); if(frequency.containsKey(temp)) { frequency.put(temp, frequency.get(temp) + 1); } else { frequency.put(temp, 1); } } // System.out.println(getKeyWithHighestValue(frequency)); } public static Character getKeyWithHighestValue(HashMap<Character, Integer> map) { Character keyWithHighestValue = null; int highestValue = 0; for (Map.Entry<Character, Integer> e : map.entrySet()) { if (keyWithHighestValue == null) { keyWithHighestValue = e.getKey(); highestValue = e.getValue(); } else if (e.getValue() > highestValue) { keyWithHighestValue = e.getKey(); highestValue = e.getValue(); } else if (e.getValue().equals(highestValue) && e.getKey() < keyWithHighestValue) { keyWithHighestValue = e.getKey(); highestValue = e.getValue(); } } return keyWithHighestValue; } } import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String S = scanner.next(); scanner.close(); HashMap<Character, Integer> frequency = new HashMap<Character, Integer>(); for (int i = 0; i < S.length(); i++) { char temp = S.charAt(i); if(frequency.containsKey(temp)) { frequency.put(temp, frequency.get(temp) + 1); } else { frequency.put(temp, 1); } } System.out.println(getKeyWithHighestValue(frequency)); } public static Character getKeyWithHighestValue(HashMap<Character, Integer> map) { Character keyWithHighestValue = null; int highestValue = 0; for (Map.Entry<Character, Integer> e : map.entrySet()) { if (keyWithHighestValue == null) { keyWithHighestValue = e.getKey(); highestValue = e.getValue(); } else if (e.getValue() > highestValue) { keyWithHighestValue = e.getKey(); highestValue = e.getValue(); } else if (e.getValue().equals(highestValue) && e.getKey() < keyWithHighestValue) { keyWithHighestValue = e.getKey(); highestValue = e.getValue(); } } return keyWithHighestValue; } }
ConDefects/ConDefects/Code/abc338_b/Java/52248729
condefects-java_data_696
import java.util.*; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); String S = input.next(); var frequency = new HashMap<Character, Integer>(); char maxChar = S.charAt(0); for (char c : S.toCharArray()) { frequency.put(c, frequency.getOrDefault(c, 0) + 1); if (frequency.get(c) > frequency.get(maxChar) || ((frequency.get(c) == frequency.get(maxChar) ) && c < maxChar)){ maxChar = c; } } System.out.printf("%c\n", maxChar); input.close(); } } import java.util.*; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); String S = input.next(); var frequency = new HashMap<Character, Integer>(); char maxChar = S.charAt(0); for (char c : S.toCharArray()) { frequency.put(c, frequency.getOrDefault(c, 0) + 1); if (frequency.get(c) > frequency.get(maxChar) || ((frequency.get(c).equals(frequency.get(maxChar)) ) && c < maxChar)){ maxChar = c; } } System.out.printf("%c\n", maxChar); input.close(); } }
ConDefects/ConDefects/Code/abc338_b/Java/53685370
condefects-java_data_697
import java.math.BigInteger; import java.util.*; public class Main { public static void main (String [] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); long lower = 1; long answer = 0; long upper = 1; for(int i = 1; i <= 18 && lower < n; i++) { if(i == 18) { upper = n; } else { upper = lower * 10; upper = Math.min(n, upper - 1); } long numofnums = upper - lower + 1; answer += (((numofnums + 1)% 998244353)* (numofnums % 998244353) /2); answer %= 998244353; lower *= 10; } answer %= 998244353; double epsilon = 0.00001; double min = 10000000; for (int i = 0; i <= 18; i++) { min = Math.min(min, Math.abs(n - Math.pow(10, i))); } if(n == 1) System.out.print(1); else if(min < epsilon) System.out.print(answer + 1); else System.out.print(answer); } } import java.math.BigInteger; import java.util.*; public class Main { public static void main (String [] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); long lower = 1; long answer = 0; long upper = 1; for(int i = 1; i <= 18 && lower < n; i++) { if(i == 18) { upper = n; } else { upper = lower * 10; upper = Math.min(n, upper - 1); } long numofnums = upper - lower + 1; answer += (((numofnums + 1)% 998244353)* (numofnums % 998244353) /2); answer %= 998244353; lower *= 10; } answer %= 998244353; double epsilon = 0.00001; double min = 10000000; for (int i = 0; i <= 18; i++) { min = Math.min(min, Math.abs(n - (long)Math.pow(10, i))); } if(n == 1) System.out.print(1); else if(min < epsilon) System.out.print(answer + 1); else System.out.print(answer); } }
ConDefects/ConDefects/Code/abc238_c/Java/36391601
condefects-java_data_698
import java.util.Scanner; public class Main { static final int mod = 992844353; public static void main(String[] args) { Scanner scan = new Scanner(System.in); long n = scan.nextLong(); long res = 0, p = 10, q = 1; while (true) { long m = Math.min(n, p - 1) - q + 1; m %= mod; res = (res + (m * (m + 1) / 2) % mod) % mod; if (p > n) break; p *= 10; q *= 10; } System.out.println(res); } } import java.util.Scanner; public class Main { static final int mod = 998244353; public static void main(String[] args) { Scanner scan = new Scanner(System.in); long n = scan.nextLong(); long res = 0, p = 10, q = 1; while (true) { long m = Math.min(n, p - 1) - q + 1; m %= mod; res = (res + (m * (m + 1) / 2) % mod) % mod; if (p > n) break; p *= 10; q *= 10; } System.out.println(res); } }
ConDefects/ConDefects/Code/abc238_c/Java/42014458
condefects-java_data_699
import java.util.*; import java.io.*; import java.math.*; import java.util.function.*; public class Main implements Runnable { static boolean DEBUG; public static void main(String[] args) { DEBUG = args.length > 0 && args[0].equals("-DEBUG"); Thread.setDefaultUncaughtExceptionHandler((t, e) -> { e.printStackTrace(); System.exit(1); }); new Thread(null, new Main(), "", 1 << 31).start(); } public void run() { Solver solver = new Solver(); solver.solve(); solver.exit(); } static class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int pointer = 0; private int buflen = 0; private boolean hasNextByte() { if(pointer < buflen) return true; else { pointer = 0; try { buflen = in.read(buffer); }catch (IOException e) { e.printStackTrace(); } return buflen > 0; } } private int readByte() { if(hasNextByte()) return buffer[pointer ++]; else return -1; } private boolean isPrintableChar(int c) { return isPrintableChar(c, false); } private boolean isPrintableChar(int c, boolean includingSpace) { return (includingSpace ? 32 : 33) <= c && c <= 126; } private void skipUnprintable() { skipUnprintable(false); } private void skipUnprintable(boolean includingSpace) { while(hasNextByte() && !isPrintableChar(buffer[pointer], includingSpace)) pointer ++; } private boolean hasNext() { return hasNext(false); } private boolean hasNext(boolean includingSpace) { skipUnprintable(includingSpace); return hasNextByte(); } private StringBuilder sb = new StringBuilder(); public String next() { return next(false); } public String next(boolean includingSpace) { if(!hasNext(includingSpace)) throw new NoSuchElementException(); sb.setLength(0); int b = readByte(); while(isPrintableChar(b, includingSpace)) { 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 = n * 10 + b - '0'; else if(b == -1 || !isPrintableChar(b)) return minus ? - n : n; else throw new NumberFormatException(); b = readByte(); } } } static class Solver { final FastScanner sc = new FastScanner(); public Solver() { } final String ns() { return ns(false); } final String ns(boolean includingSpace) { return sc.next(includingSpace); } final String[] ns(int n) { return ns(n, false); } final String[] ns(int n, boolean includingSpace) { String a[] = new String[n]; for(int i = 0; i < n; i ++) a[i] = ns(includingSpace); return a; } final String[][] ns(int n, int m) { return ns(n, m, false); } final String[][] ns(int n, int m, boolean includingSpace) { String a[][] = new String[n][m]; for(int i = 0; i < n; i ++) a[i] = ns(m, includingSpace); return a; } final char nc() { return ns().charAt(0); } final char[] nc(int n) { String str = ns(); if(n < 0) n = str.length(); char a[] = new char[n]; for(int i = 0; i < n; i ++) a[i] = str.charAt(i); return a; } final char[][] nc(int n, int m) { char a[][] = new char[n][m]; for(int i = 0; i < n; i ++) a[i] = nc(m); return a; } final boolean[] nb(int n, char t) { char c[] = nc(-1); if(n < 0) n = c.length; boolean a[] = new boolean[n]; for(int i = 0; i < n; i ++) a[i] = c[i] == t; return a; } final boolean[][] nb(int n, int m, char t) { boolean a[][] = new boolean[n][m]; for(int i = 0; i < n; i ++) a[i] = nb(m, t); return a; } final int ni() { return Math.toIntExact(sc.nextLong()); } final int[] ni(int n) { int a[] = new int[n]; for(int i = 0; i < n; i ++) a[i] = ni(); return a; } final int[][] ni(int n, int m) { int a[][] = new int[n][m]; for(int i = 0; i < n; i ++) a[i] = ni(m); return a; } final long nl() { return sc.nextLong(); } final long[] nl(int n) { long a[] = new long[n]; for(int i = 0; i < n; i ++) a[i] = nl(); return a; } final long[][] nl(int n, int m) { long a[][] = new long[n][m]; for(int i = 0; i < n; i ++) a[i] = nl(m); return a; } final double nd() { return Double.parseDouble(sc.next()); } final double[] nd(int n) { double a[] = new double[n]; for(int i = 0; i < n; i ++) a[i] = nd(); return a; } final double[][] nd(int n, int m) { double a[][] = new double[n][m]; for(int i = 0; i < n; i ++) a[i] = nd(m); return a; } final String booleanToString(boolean b) { return b ? "#" : "."; } final PrintWriter out = new PrintWriter(System.out); final PrintWriter err = new PrintWriter(System.err); final StringBuilder sb4prtln = new StringBuilder(); final void prt() { out.print(""); } final <T> void prt(T a) { out.print(a); } final void prtln() { out.println(""); } final <T> void prtln(T a) { out.println(a); } final void prtln(int... a) { sb4prtln.setLength(0); for(int ele : a) { sb4prtln.append(ele); sb4prtln.append(" "); } sb4prtln.deleteCharAt(sb4prtln.length() - 1); prtln(sb4prtln); } final void prtln(long... a) { sb4prtln.setLength(0); for(long ele : a) { sb4prtln.append(ele); sb4prtln.append(" "); } sb4prtln.deleteCharAt(sb4prtln.length() - 1); prtln(sb4prtln); } final void prtln(double... a) { sb4prtln.setLength(0); for(double ele : a) { sb4prtln.append(ele); sb4prtln.append(" "); } sb4prtln.deleteCharAt(sb4prtln.length() - 1); prtln(sb4prtln); } final void prtln(String... a) { sb4prtln.setLength(0); for(String ele : a) { sb4prtln.append(ele); sb4prtln.append(" "); } sb4prtln.deleteCharAt(sb4prtln.length() - 1); prtln(sb4prtln); } final void prtln(char... a) { sb4prtln.setLength(0); for(char ele : a) sb4prtln.append(ele); prtln(sb4prtln); } final void prtln(boolean... a) { sb4prtln.setLength(0); for(boolean ele : a) sb4prtln.append(booleanToString(ele)); prtln(sb4prtln); } final void prtlns(int... a) { sb4prtln.setLength(0); for(int ele : a) { sb4prtln.append(ele); sb4prtln.append("\n"); } prt(sb4prtln); } final void prtlns(long... a) { sb4prtln.setLength(0); for(long ele : a) { sb4prtln.append(ele); sb4prtln.append("\n"); } prt(sb4prtln); } final void prtlns(double... a) { sb4prtln.setLength(0); for(double ele : a) { sb4prtln.append(ele); sb4prtln.append("\n"); } prt(sb4prtln); } final void prtlns(String... a) { sb4prtln.setLength(0); for(String ele : a) { sb4prtln.append(ele); sb4prtln.append("\n"); } prt(sb4prtln); } final void prtlns(char... a) { sb4prtln.setLength(0); for(char ele : a) { sb4prtln.append(ele); sb4prtln.append("\n"); } prt(sb4prtln); } final void prtlns(boolean... a) { sb4prtln.setLength(0); for(boolean ele : a) { sb4prtln.append(booleanToString(ele)); sb4prtln.append("\n"); } prt(sb4prtln); } final void prtln(int[][] a) { for(int[] ele : a) prtln(ele); } final void prtln(long[][] a) { for(long[] ele : a) prtln(ele); } final void prtln(double[][] a) { for(double[] ele : a) prtln(ele); } final void prtln(String[][] a) { for(String[] ele : a) prtln(ele); } final void prtln(char[][] a) { for(char[] ele : a) prtln(ele); } final void prtln(boolean[][] a) { for(boolean[] ele : a) prtln(ele); } final String errconvert(int a) { return isINF(a) ? "_" : String.valueOf(a); } final String errconvert(long a) { return isINF(a) ? "_" : String.valueOf(a); } final void errprt(int a) { if(DEBUG) err.print(errconvert(a)); } final void errprt(long a) { if(DEBUG) err.print(errconvert(a)); } final void errprt() { if(DEBUG) err.print(""); } final <T> void errprt(T a) { if(DEBUG) err.print(a); } final void errprt(boolean a) { if(DEBUG) errprt(booleanToString(a)); } final void errprtln() { if(DEBUG) err.println(""); } final void errprtln(int a) { if(DEBUG) err.println(errconvert(a)); } final void errprtln(long a) { if(DEBUG) err.println(errconvert(a)); } final <T> void errprtln(T a) { if(DEBUG) err.println(a); } final void errprtln(boolean a) { if(DEBUG) errprtln(booleanToString(a)); } final void errprtln(int... a) { if(DEBUG) { sb4prtln.setLength(0); for(int ele : a) { sb4prtln.append(errconvert(ele)); sb4prtln.append(" "); } errprtln(sb4prtln.toString().trim()); } } final void errprtln(long... a) { if(DEBUG) { sb4prtln.setLength(0); for(long ele : a) { sb4prtln.append(errconvert(ele)); sb4prtln.append(" "); } errprtln(sb4prtln.toString().trim()); } } final void errprtln(double... a) { if(DEBUG) { sb4prtln.setLength(0); for(double ele : a) { sb4prtln.append(ele); sb4prtln.append(" "); } errprtln(sb4prtln.toString().trim()); } } final void errprtln(String... a) { if(DEBUG) { sb4prtln.setLength(0); for(String ele : a) { sb4prtln.append(ele); sb4prtln.append(" "); } errprtln(sb4prtln.toString().trim()); } } final void errprtln(char... a) { if(DEBUG) { sb4prtln.setLength(0); for(char ele : a) sb4prtln.append(ele); errprtln(sb4prtln.toString()); } } final void errprtln(boolean... a) { if(DEBUG) { sb4prtln.setLength(0); for(boolean ele : a) sb4prtln.append(booleanToString(ele)); errprtln(sb4prtln.toString()); } } final void errprtlns(int... a) { if(DEBUG) { sb4prtln.setLength(0); for(int ele : a) { sb4prtln.append(errconvert(ele)); sb4prtln.append("\n"); } errprt(sb4prtln.toString()); } } final void errprtlns(long... a) { if(DEBUG) { sb4prtln.setLength(0); for(long ele : a) { sb4prtln.append(errconvert(ele)); sb4prtln.append("\n"); } errprt(sb4prtln.toString()); } } final void errprtlns(double... a) { if(DEBUG) { sb4prtln.setLength(0); for(double ele : a) { sb4prtln.append(ele); sb4prtln.append("\n"); } errprt(sb4prtln.toString()); } } final void errprtlns(String... a) { if(DEBUG) { sb4prtln.setLength(0); for(String ele : a) { sb4prtln.append(ele); sb4prtln.append("\n"); } errprt(sb4prtln.toString()); } } final void errprtlns(char... a) { if(DEBUG) { sb4prtln.setLength(0); for(char ele : a) { sb4prtln.append(ele); sb4prtln.append("\n"); } errprt(sb4prtln.toString()); } } final void errprtlns(boolean... a) { if(DEBUG) { sb4prtln.setLength(0); for(boolean ele : a) { sb4prtln.append(booleanToString(ele)); sb4prtln.append("\n"); } errprt(sb4prtln.toString()); } } final void errprtln(Object[] a) { if(DEBUG) for(Object ele : a) errprtln(ele); } final void errprtln(int[][] a) { if(DEBUG) for(int[] ele : a) errprtln(ele); } final void errprtln(long[][] a) { if(DEBUG) for(long[] ele : a) errprtln(ele); } final void errprtln(double[][] a) { if(DEBUG) for(double[] ele : a) errprtln(ele); } final void errprtln(String[][] a) { if(DEBUG) for(String[] ele : a) errprtln(ele); } final void errprtln(char[][] a) { if(DEBUG) for(char[] ele : a) errprtln(ele); } final void errprtln(boolean[][] a) { if(DEBUG) for(boolean[] ele : a) errprtln(ele); } final void errprtln(Object[][] a) { if(DEBUG) for(Object ele : a) { errprtln(ele); errprtln(); } } final void reply(boolean b) { prtln(b ? "Yes" : "No"); } final void REPLY(boolean b) { prtln(b ? "YES" : "NO"); } final void flush() { out.flush(); if(DEBUG) err.flush(); } final void assertion(boolean b) { if(!b) { flush(); throw new AssertionError(); } } final <T> void assertion(boolean b, T a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, int... a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, long... a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, double... a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, String... a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, char... a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, boolean... a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, int[][] a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, long[][] a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, double[][] a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, String[][] a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, char[][] a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, boolean[][] a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void inclusiveRangeCheck(int i, int max) { inclusiveRangeCheck(i, 0, max); } final void inclusiveRangeCheck(int i, int min, int max) { rangeCheck(i, min, max + 1); } final void inclusiveRangeCheck(long i, long max) { inclusiveRangeCheck(i, 0, max); } final void inclusiveRangeCheck(long i, long min, long max) { rangeCheck(i, min, max + 1); } final void rangeCheck(int i, int max) { rangeCheck(i, 0, max); } final void rangeCheck(int i, int min, int max) { if(i < min || i >= max) throw new IndexOutOfBoundsException(String.format("Index %d out of bounds for length %d", i, max)); } final void rangeCheck(long i, long max) { rangeCheck(i, 0, max); } final void rangeCheck(long i, long min, long max) { if(i < min || i >= max) throw new IndexOutOfBoundsException(String.format("Index %d out of bounds for length %d", i, max)); } final void nonNegativeCheck(long x) { nonNegativeCheck(x, "the argument"); } final void nonNegativeCheck(long x, String attribute) { if(x < 0) throw new IllegalArgumentException(String.format("%s %d is negative", attribute, x)); } final void positiveCheck(long x) { positiveCheck(x, "the argument"); } final void positiveCheck(long x, String attribute) { if(x <= 0) throw new IllegalArgumentException(String.format("%s %d is negative", attribute, x)); } final void exit() { flush(); System.exit(0); } final <T> void exit(T a) { prtln(a); exit(); } final void exit(int... a) { prtln(a); exit(); } final void exit(long... a) { prtln(a); exit(); } final void exit(double... a) { prtln(a); exit(); } final void exit(String... a) { prtln(a); exit(); } final void exit(char... a) { prtln(a); exit(); } final void exit(boolean... a) { prtln(a); exit(); } final void exit(int[][] a) { prtln(a); exit(); } final void exit(long[][] a) { prtln(a); exit(); } final void exit(double[][] a) { prtln(a); exit(); } final void exit(String[][] a) { prtln(a); exit(); } final void exit(char[][] a) { prtln(a); exit(); } final void exit(boolean[][] a) { prtln(a); exit(); } final long INF = (long)1e18 + 7; final boolean isPlusINF(long a) { return a > INF / 10; } final boolean isMinusINF(long a) { return isPlusINF(- a); } final boolean isINF(long a) { return isPlusINF(a) || isMinusINF(a); } final int I_INF = (int)1e9 + 7; final boolean isPlusINF(int a) { return a > I_INF / 10; } final boolean isMinusINF(int a) { return isPlusINF(- a); } final boolean isINF(int a) { return isPlusINF(a) || isMinusINF(a); } final int min(int a, int b) { return Math.min(a, b); } final long min(long a, long b) { return Math.min(a, b); } final double min(double a, double b) { return Math.min(a, b); } final <T extends Comparable<T>> T min(T a, T b) { return a.compareTo(b) <= 0 ? a : b; } final int min(int... x) { int min = x[0]; for(int val : x) min = min(min, val); return min; } final long min(long... x) { long min = x[0]; for(long val : x) min = min(min, val); return min; } final double min(double... x) { double min = x[0]; for(double val : x) min = min(min, val); return min; } final int max(int a, int b) { return Math.max(a, b); } final long max(long a, long b) { return Math.max(a, b); } final double max(double a, double b) { return Math.max(a, b); } final <T extends Comparable<T>> T max(T a, T b) { return a.compareTo(b) >= 0 ? a : b; } final int max(int... x) { int max = x[0]; for(int val : x) max = max(max, val); return max; } final long max(long... x) { long max = x[0]; for(long val : x) max = max(max, val); return max; } final double max(double... x) { double max = x[0]; for(double val : x) max = max(max, val); return max; } final <T extends Comparable<T>> T max(T[] x) { T max = x[0]; for(T val : x) max = max(max, val); return max; } final int max(int[][] a) { int max = a[0][0]; for(int[] ele : a) max = max(max, max(ele)); return max; } final long max(long[][] a) { long max = a[0][0]; for(long[] ele : a) max = max(max, max(ele)); return max; } final double max(double[][] a) { double max = a[0][0]; for(double[] ele : a) max = max(max, max(ele)); return max; } final <T extends Comparable<T>> T max(T[][] a) { T max = a[0][0]; for(T[] ele : a) max = max(max, max(ele)); return max; } final long sum(int... a) { long sum = 0; for(int ele : a) sum += ele; return sum; } final long sum(long... a) { long sum = 0; for(long ele : a) sum += ele; return sum; } final double sum(double... a) { double sum = 0; for(double ele : a) sum += ele; return sum; } final long sum(boolean... a) { long sum = 0; for(boolean ele : a) sum += ele ? 1 : 0; return sum; } final long[] sums(int[] a) { long sum[] = new long[a.length + 1]; sum[0] = 0; for(int i = 0; i < a.length; i ++) sum[i + 1] = sum[i] + a[i]; return sum; } final long[] sums(long[] a) { long sum[] = new long[a.length + 1]; sum[0] = 0; for(int i = 0; i < a.length; i ++) sum[i + 1] = sum[i] + a[i]; return sum; } final double[] sums(double[] a) { double sum[] = new double[a.length + 1]; sum[0] = 0; for(int i = 0; i < a.length; i ++) sum[i + 1] = sum[i] + a[i]; return sum; } final long[] sums(boolean[] a) { long sum[] = new long[a.length + 1]; sum[0] = 0; for(int i = 0; i < a.length; i ++) sum[i + 1] = sum[i] + (a[i] ? 1 : 0); return sum; } final long[][] sums(int[][] a) { long sum[][] = new long[a.length + 1][a[0].length + 1]; for(int i = 0; i < a.length; i ++) { for(int j = 0; j < a[i].length; j ++) sum[i + 1][j + 1] = sum[i + 1][j] + sum[i][j + 1] - sum[i][j] + a[i][j]; } return sum; } final long[][] sums(long[][] a) { long sum[][] = new long[a.length + 1][a[0].length + 1]; for(int i = 0; i < a.length; i ++) { for(int j = 0; j < a[i].length; j ++) sum[i + 1][j + 1] = sum[i + 1][j] + sum[i][j + 1] - sum[i][j] + a[i][j]; } return sum; } final double[][] sums(double[][] a) { double sum[][] = new double[a.length + 1][a[0].length + 1]; for(int i = 0; i < a.length; i ++) { for(int j = 0; j < a[i].length; j ++) sum[i + 1][j + 1] = sum[i + 1][j] + sum[i][j + 1] - sum[i][j] + a[i][j]; } return sum; } final long[][] sums(boolean[][] a) { long sum[][] = new long[a.length + 1][a[0].length + 1]; for(int i = 0; i < a.length; i ++) { for(int j = 0; j < a[i].length; j ++) sum[i + 1][j + 1] = sum[i + 1][j] + sum[i][j + 1] - sum[i][j] + (a[i][j] ? 1 : 0); } return sum; } final int constrain(int x, int l, int r) { return min(max(x, min(l, r)), max(l, r)); } final long constrain(long x, long l, long r) { return min(max(x, min(l, r)), max(l, r)); } final double constrain(double x, double l, double r) { return min(max(x, min(l, r)), max(l, r)); } final int abs(int x) { return x >= 0 ? x : - x; } final long abs(long x) { return x >= 0 ? x : - x; } final double abs(double x) { return x >= 0 ? x : - x; } final int signum(int x) { return x > 0 ? 1 : x < 0 ? -1 : 0; } final int signum(long x) { return x > 0 ? 1 : x < 0 ? -1 : 0; } final int signum(double x) { return x > 0 ? 1 : x < 0 ? -1 : 0; } final long round(double x) { return Math.round(x); } final long floor(double x) { return round(Math.floor(x)); } final int divfloor(int a, int b) { return signum(a) == signum(b) ? a / b : - divceil(abs(a), abs(b)); } final long divfloor(long a, long b) { return signum(a) == signum(b) ? a / b : - divceil(abs(a), abs(b)); } final long ceil(double x) { return round(Math.ceil(x)); } final int divceil(int a, int b) { return a >= 0 && b > 0 ? (a + b - 1) / b : a < 0 && b < 0 ? divceil(abs(a), abs(b)) : - divfloor(abs(a), abs(b)); } final long divceil(long a, long b) { return a >= 0 && b > 0 ? (a + b - 1) / b : a < 0 && b < 0 ? divceil(abs(a), abs(b)) : - divfloor(abs(a), abs(b)); } final boolean mulGreater(long a, long b, long c) { return b == 0 ? c < 0 : b < 0 ? mulLess(a, - b, - c) : a > divfloor(c, b); } // a * b > c final boolean mulGreaterEquals(long a, long b, long c) { return b == 0 ? c <= 0 : b < 0 ? mulLessEquals(a, - b, - c) : a >= divceil(c, b); } // a * b >= c final boolean mulLess(long a, long b, long c) { return !mulGreaterEquals(a, b, c); } // a * b < c final boolean mulLessEquals(long a, long b, long c) { return !mulGreater(a, b, c); } // a * b <= c final double sqrt(int x) { return Math.sqrt((double)x); } final double sqrt(long x) { return Math.sqrt((double)x); } final double sqrt(double x) { return Math.sqrt(x); } final int floorsqrt(int x) { int s = (int)floor(sqrt(x)) + 1; while(s * s > x) s --; return s; } final long floorsqrt(long x) { long s = floor(sqrt(x)) + 1; while(s * s > x) s --; return s; } final int ceilsqrt(int x) { int s = (int)ceil(sqrt(x)); while(s * s >= x) s --; s ++; return s; } final long ceilsqrt(long x) { long s = ceil(sqrt(x)); while(s * s >= x) s --; s ++; return s; } final long fact(int n) { long ans = 1; for(int i = 1; i <= n; i ++) ans = Math.multiplyExact(ans, i); return ans; } final long naiveP(long n, long r) { long ans = 1; for(int i = 0; i < r; i ++) ans = Math.multiplyExact(ans, n - i); return ans; } final long naiveC(long n, long r) { long ans = 1; for(int i = 0; i < r; i ++) { ans = Math.multiplyExact(ans, n - i); ans /= (i + 1); } return ans; } final double pow(double x, double y) { return Math.pow(x, y); } final long pow(long x, long y) { long ans = 1; while(true) { if((y & 1) != 0) ans = Math.multiplyExact(ans, x); y >>= 1; if(y <= 0) return ans; x = Math.multiplyExact(x, x); } } final double pow(double x, long y) { double ans = 1; while(true) { if((y & 1) != 0) ans *= x; y >>= 1; if(y <= 0) return ans; x *= x; } } final int gcd(int a, int b) { while(true) { if(b == 0) return a; int tmp = a; a = b; b = tmp % b; } } final long gcd(long a, long b) { while(true) { if(b == 0) return a; long tmp = a; a = b; b = tmp % b; } } final long lcm(long a, long b) { return a / gcd(a, b) * b; } final int gcd(int... a) { int gcd = 0; for(int i = 0; i < a.length; i ++) gcd = gcd(gcd, a[i]); return gcd; } final long gcd(long... a) { long gcd = 0; for(int i = 0; i < a.length; i ++) gcd = gcd(gcd, a[i]); return gcd; } final double random() { return Math.random(); } final int random(int max) { return (int)floor(random() * max); } final long random(long max) { return floor(random() * max); } final double random(double max) { return random() * max; } final int random(int min, int max) { return random(max - min) + min; } final long random(long min, long max) { return random(max - min) + min; } final double random(double min, double max) { return random(max - min) + min; } final boolean isUpper(char a) { return a >= 'A' && a <= 'Z'; } final boolean isLower(char a) { return a >= 'a' && a <= 'z'; } final int upperToInt(char a) { return a - 'A'; } final int lowerToInt(char a) { return a - 'a'; } final int numToInt(char a) { return a - '0'; } final int charToInt(char a) { return isLower(a) ? lowerToInt(a) : isUpper(a) ? upperToInt(a) : numToInt(a); } final int alphabetToInt(char a) { return isLower(a) ? lowerToInt(a) : isUpper(a) ? upperToInt(a) + 26 : 52; } final char intToUpper(int a) { return (char)(a + 'A'); } final char intToLower(int a) { return (char)(a + 'a'); } final char intToNum(int a) { return (char)(a + '0'); } final int[] charToInt(char[] a) { int array[] = new int[a.length]; for(int i = 0; i < a.length; i ++) array[i] = charToInt(a[i]); return array; } final long[] div(long a) { nonNegativeCheck(a); List<Long> divList = new ArrayList<>(); for(long i = 1; i * i <= a; i ++) if(a % i == 0) { divList.add(i); if(i * i != a) divList.add(a / i); } long div[] = new long[divList.size()]; for(int i = 0; i < divList.size(); i ++) div[i] = divList.get(i); Arrays.sort(div); return div; } final PairLL[] factor(long a) { nonNegativeCheck(a); List<PairLL> factorList = new ArrayList<>(); for(long i = 2; i * i <= a; i ++) { if(a % i == 0) { long cnt = 0; while(a % i == 0) { a /= i; cnt ++; } factorList.add(new PairLL(i, cnt)); } } if(a > 1) factorList.add(new PairLL(a, 1)); PairLL factor[] = new PairLL[factorList.size()]; for(int i = 0; i < factorList.size(); i ++) factor[i] = factorList.get(i); Arrays.sort(factor); return factor; } final boolean isPrime(long x) { boolean ok = x > 1; for(long i = 2; i * i <= x; i ++) { ok &= x % i != 0; if(!ok) return ok; } return ok; } final boolean[] prime(int num) { nonNegativeCheck(num); boolean prime[] = new boolean[num]; fill(prime, true); if(num > 0) prime[0] = false; if(num > 1) prime[1] = false; for(int i = 2; i < num; i ++) if(prime[i]) for(int j = 2; i * j < num; j ++) prime[i * j] = false; return prime; } final PairIL[] countElements(int[] a, boolean sort) { int len = a.length; int array[] = new int[len]; for(int i = 0; i < len; i ++) array[i] = a[i]; if(sort) Arrays.sort(array); List<PairIL> cntsList = new ArrayList<>(); long tmp = 1; for(int i = 1; i <= len; i ++) { if(i == len || array[i] != array[i - 1]) { cntsList.add(new PairIL(array[i - 1], tmp)); tmp = 1; }else tmp ++; } PairIL cnts[] = new PairIL[cntsList.size()]; for(int i = 0; i < cntsList.size(); i ++) cnts[i] = cntsList.get(i); return cnts; } final PairLL[] countElements(long[] a, boolean sort) { int len = a.length; long array[] = new long[len]; for(int i = 0; i < len; i ++) array[i] = a[i]; if(sort) Arrays.sort(array); List<PairLL> cntsList = new ArrayList<>(); long tmp = 1; for(int i = 1; i <= len; i ++) { if(i == len || array[i] != array[i - 1]) { cntsList.add(new PairLL(array[i - 1], tmp)); tmp = 1; }else tmp ++; } PairLL cnts[] = new PairLL[cntsList.size()]; for(int i = 0; i < cntsList.size(); i ++) cnts[i] = cntsList.get(i); return cnts; } final PairIL[] countElements(String s, boolean sort) { int len = s.length(); char array[] = s.toCharArray(); if(sort) Arrays.sort(array); List<PairIL> cntsList = new ArrayList<>(); long tmp = 1; for(int i = 1; i <= len; i ++) { if(i == len || array[i] != array[i - 1]) { cntsList.add(new PairIL((int)array[i - 1], tmp)); tmp = 1; }else tmp ++; } PairIL cnts[] = new PairIL[cntsList.size()]; for(int i = 0; i < cntsList.size(); i ++) cnts[i] = cntsList.get(i); return cnts; } long triangular(long n) { return n * (n + 1) / 2; } long arctriangularfloor(long m) { long n = (floor(sqrt(m * 8 + 1)) - 1) / 2 + 1; while(triangular(n) > m) n --; return n; } long arctriangularceil(long m) { long n = max(0, (ceil(sqrt(m * 8 + 1)) + 1) / 2 - 1); while(triangular(n) < m) n ++; return n; } final int[] baseConvert(long x, int n, int len) { nonNegativeCheck(x); nonNegativeCheck(n); nonNegativeCheck(len); int digit[] = new int[len]; int i = 0; long tmp = x; while(tmp > 0 && i < len) { digit[i ++] = (int)(tmp % n); tmp /= n; } return digit; } final int[] baseConvert(long x, int n) { nonNegativeCheck(x); nonNegativeCheck(n); long tmp = x; int len = 0; while(tmp > 0) { tmp /= n; len ++; } return baseConvert(x, n, len); } final int[] baseConvert(int x, int n, int len) { nonNegativeCheck(x); nonNegativeCheck(n); nonNegativeCheck(len); int digit[] = new int[len]; int i = 0; int tmp = x; while(tmp > 0 && i < len) { digit[i ++] = (int)(tmp % n); tmp /= n; } return digit; } final int[] baseConvert(int x, int n) { nonNegativeCheck(x); nonNegativeCheck(n); int tmp = x; int len = 0; while(tmp > 0) { tmp /= n; len ++; } return baseConvert(x, n, len); } final long[] baseConvert(long x, long n, int len) { nonNegativeCheck(x); nonNegativeCheck(n); nonNegativeCheck(len); long digit[] = new long[len]; int i = 0; long tmp = x; while(tmp > 0 && i < len) { digit[i ++] = tmp % n; tmp /= n; } return digit; } final long[] baseConvert(long x, long n) { nonNegativeCheck(x); nonNegativeCheck(n); long tmp = x; int len = 0; while(tmp > 0) { tmp /= n; len ++; } return baseConvert(x, n, len); } final int numDigits(long a) { nonNegativeCheck(a); return Long.toString(a).length(); } final long bitFlag(int a) { nonNegativeCheck(a); return 1L << (long)a; } final boolean isFlagged(long x, int a) { nonNegativeCheck(x); nonNegativeCheck(a); return (x & bitFlag(a)) != 0; } final long countString(String s, String a) { return (s.length() - s.replace(a, "").length()) / a.length(); } final long countStringAll(String s, String a) { return s.length() - s.replaceAll(a, "").length(); } final String reverse(String s) { return (new StringBuilder(s)).reverse().toString(); } final String[] reverse(String[] a) { for(int i = 0; i < a.length / 2; i ++) swap(a, i, a.length - i - 1); return a; } final int[] reverse(int[] a) { for(int i = 0; i < a.length / 2; i ++) swap(a, i, a.length - i - 1); return a; } final long[] reverse(long[] a) { for(int i = 0; i < a.length / 2; i ++) swap(a, i, a.length - i - 1); return a; } final double[] reverse(double[] a) { for(int i = 0; i < a.length / 2; i ++) swap(a, i, a.length - i - 1); return a; } final char[] reverse(char[] a) { for(int i = 0; i < a.length / 2; i ++) swap(a, i, a.length - i - 1); return a; } final boolean[] reverse(boolean[] a) { for(int i = 0; i < a.length / 2; i ++) swap(a, i, a.length - i - 1); return a; } final <T> T[] reverse(T[] a) { for(int i = 0; i < a.length / 2; i ++) swap(a, i, a.length - i - 1); return a; } final void fill(int[] a, int x) { Arrays.fill(a, x); } final void fill(long[] a, long x) { Arrays.fill(a, x); } final void fill(double[] a, double x) { Arrays.fill(a, x); } final void fill(char[] a, char x) { Arrays.fill(a, x); } final void fill(boolean[] a, boolean x) { Arrays.fill(a, x); } final void fill(int[][] a, int x) { for(int[] ele : a) fill(ele, x); } final void fill(long[][] a, long x) { for(long[] ele : a) fill(ele, x); } final void fill(double[][] a, double x) { for(double[] ele : a) fill(ele, x); } final void fill(char[][] a, char x) { for(char[] ele : a) fill(ele, x); } final void fill(boolean[][] a, boolean x) { for(boolean[] ele : a) fill(ele, x); } final void fill(int[][][] a, int x) { for(int[][] ele : a) fill(ele, x); } final void fill(long[][][] a, long x) { for(long[][] ele : a) fill(ele, x); } final void fill(double[][][] a, double x) { for(double[][] ele : a) fill(ele, x); } final void fill(char[][][] a, char x) { for(char[][] ele : a) fill(ele, x); } final void fill(boolean[][][] a, boolean x) { for(boolean[][] ele : a) fill(ele, x); } final int[] resize(int[] a, int m, int x) { nonNegativeCheck(m); int resized[] = new int[m]; for(int i = max(0, - x); i < a.length && i + x < m; i ++) resized[i + x] = a[i]; return resized; } final long[] resize(long[] a, int m, int x) { nonNegativeCheck(m); long resized[] = new long[m]; for(int i = max(0, - x); i < a.length && i + x < m; i ++) resized[i + x] = a[i]; return resized; } final double[] resize(double[] a, int m, int x) { nonNegativeCheck(m); double resized[] = new double[m]; for(int i = max(0, - x); i < a.length && i + x < m; i ++) resized[i + x] = a[i]; return resized; } final char[] resize(char[] a, int m, int x) { nonNegativeCheck(m); char resized[] = new char[m]; for(int i = max(0, - x); i < a.length && i + x < m; i ++) resized[i + x] = a[i]; return resized; } final boolean[] resize(boolean[] a, int m, int x) { nonNegativeCheck(m); boolean resized[] = new boolean[m]; for(int i = max(0, - x); i < a.length && i + x < m; i ++) resized[i + x] = a[i]; return resized; } final Object[] resize(Object[] a, int m, int x) { nonNegativeCheck(m); Object resized[] = new Object[m]; for(int i = max(0, - x); i < a.length && i + x < m; i ++) resized[i + x] = a[i]; return resized; } final int[] toIntArray(List<Integer> list) { int a[] = new int[list.size()]; int idx = 0; for(int ele : list) a[idx ++] = ele; return a; } final long[] toLongArray(List<Long> list) { long a[] = new long[list.size()]; int idx = 0; for(long ele : list) a[idx ++] = ele; return a; } final double[] toDoubleArray(List<Double> list) { double a[] = new double[list.size()]; int idx = 0; for(double ele : list) a[idx ++] = ele; return a; } final char[] toCharArray(List<Character> list) { char a[] = new char[list.size()]; int idx = 0; for(char ele : list) a[idx ++] = ele; return a; } final boolean[] toBooleanArray(List<Boolean> list) { boolean a[] = new boolean[list.size()]; int idx = 0; for(boolean ele : list) a[idx ++] = ele; return a; } final String[] toStringArray(List<String> list) { String a[] = new String[list.size()]; int idx = 0; for(String ele : list) a[idx ++] = ele; return a; } final <T> void toArray(List<T> list, T a[]) { int idx = 0; for(T ele : list) a[idx ++] = ele; } final void shuffleArray(int[] a) { for(int i = 0; i < a.length; i ++){ int tmp = a[i]; int idx = random(i, a.length); a[i] = a[idx]; a[idx] = tmp; } } final void shuffleArray(long[] a) { for(int i = 0; i < a.length; i ++){ long tmp = a[i]; int idx = random(i, a.length); a[i] = a[idx]; a[idx] = tmp; } } final void shuffleArray(double[] a) { for(int i = 0; i < a.length; i ++){ double tmp = a[i]; int idx = random(i, a.length); a[i] = a[idx]; a[idx] = tmp; } } final int[] randomi(int n, int max) { nonNegativeCheck(n); int a[] = new int[n]; for(int i = 0; i < n; i ++) a[i] = random(max); return a; } final long[] randoml(int n, long max) { nonNegativeCheck(n); long a[] = new long[n]; for(int i = 0; i < n; i ++) a[i] = random(max); return a; } final double[] randomd(int n, double max) { nonNegativeCheck(n); double a[] = new double[n]; for(int i = 0; i < n; i ++) a[i] = random(max); return a; } final int[] randomi(int n, int min, int max) { nonNegativeCheck(n); int a[] = new int[n]; for(int i = 0; i < n; i ++) a[i] = random(min, max); return a; } final long[] randoml(int n, long min, long max) { nonNegativeCheck(n); long a[] = new long[n]; for(int i = 0; i < n; i ++) a[i] = random(min, max); return a; } final double[] randomd(int n, double min, double max) { nonNegativeCheck(n); double a[] = new double[n]; for(int i = 0; i < n; i ++) a[i] = random(min, max); return a; } final void swap(String[] a, int i, int j) { rangeCheck(i, a.length); rangeCheck(j, a.length); String tmp = a[i]; a[i] = a[j]; a[j] = tmp; } final void swap(int[] a, int i, int j) { rangeCheck(i, a.length); rangeCheck(j, a.length); int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } final void swap(long[] a, int i, int j) { rangeCheck(i, a.length); rangeCheck(j, a.length); long tmp = a[i]; a[i] = a[j]; a[j] = tmp; } final void swap(double[] a, int i, int j) { rangeCheck(i, a.length); rangeCheck(j, a.length); double tmp = a[i]; a[i] = a[j]; a[j] = tmp; } final void swap(char[] a, int i, int j) { rangeCheck(i, a.length); rangeCheck(j, a.length); char tmp = a[i]; a[i] = a[j]; a[j] = tmp; } final void swap(boolean[] a, int i, int j) { rangeCheck(i, a.length); rangeCheck(j, a.length); boolean tmp = a[i]; a[i] = a[j]; a[j] = tmp; } final <T> void swap(T[] a, int i, int j) { rangeCheck(i, a.length); rangeCheck(j, a.length); T tmp = a[i]; a[i] = a[j]; a[j] = tmp; } final int[][] rotate(int[][] a) { int[][] ans = new int[a[0].length][a.length]; for(int i = 0; i < a.length; i ++) for(int j = 0; j < a[i].length; j ++) ans[j][a.length - i - 1] = a[i][j]; return ans; } final long[][] rotate(long[][] a) { long[][] ans = new long[a[0].length][a.length]; for(int i = 0; i < a.length; i ++) for(int j = 0; j < a[i].length; j ++) ans[j][a.length - i - 1] = a[i][j]; return ans; } final double[][] rotate(double[][] a) { double[][] ans = new double[a[0].length][a.length]; for(int i = 0; i < a.length; i ++) for(int j = 0; j < a[i].length; j ++) ans[j][a.length - i - 1] = a[i][j]; return ans; } final char[][] rotate(char[][] a) { char[][] ans = new char[a[0].length][a.length]; for(int i = 0; i < a.length; i ++) for(int j = 0; j < a[i].length; j ++) ans[j][a.length - i - 1] = a[i][j]; return ans; } final boolean[][] rotate(boolean[][] a) { boolean[][] ans = new boolean[a[0].length][a.length]; for(int i = 0; i < a.length; i ++) for(int j = 0; j < a[i].length; j ++) ans[j][a.length - i - 1] = a[i][j]; return ans; } final Object[][] rotate(Object[][] a) { Object[][] ans = new Object[a[0].length][a.length]; for(int i = 0; i < a.length; i ++) for(int j = 0; j < a[i].length; j ++) ans[j][a.length - i - 1] = a[i][j]; return ans; } final int[] compress(int[] a) { int n = a.length; Set<Integer> ts = new TreeSet<>(); for(int i = 0; i < n; i ++) ts.add(a[i]); int compressed[] = new int[ts.size()]; int j = 0; for(int x : ts) compressed[j ++] = x; for(int i = 0; i < n; i ++) a[i] = lowerBound(compressed, a[i]); return compressed; } final long[] compress(long[] a) { int n = a.length; Set<Long> ts = new TreeSet<>(); for(int i = 0; i < n; i ++) ts.add(a[i]); long compressed[] = new long[ts.size()]; int j = 0; for(long x : ts) compressed[j ++] = x; for(int i = 0; i < n; i ++) a[i] = lowerBound(compressed, a[i]); return compressed; } final double[] compress(double[] a) { int n = a.length; Set<Double> ts = new TreeSet<>(); for(int i = 0; i < n; i ++) ts.add(a[i]); double compressed[] = new double[ts.size()]; int j = 0; for(double x : ts) compressed[j ++] = x; for(int i = 0; i < n; i ++) a[i] = lowerBound(compressed, a[i]); return compressed; } final int lowerBound(int[] a, int key) { return BS(a, key, true, true, true); } final int lowerBound(int[] a, int key, int ng, int ok) { return BS(a, key, true, true, true, ng, ok); } final int upperBound(int[] a, int key) { return BS(a, key, true, true, false); } final int upperBound(int[] a, int key, int ng, int ok) { return BS(a, key, true, true, false, ng, ok); } final int cntBS(int[] a, int key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, true); } final int cntBS(int[] a, int key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, true, ng, ok); } final int BS(int[] a, int key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, false); } final int BS(int[] a, int key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, false, ng, ok); } final int BS(int[] a, int key, boolean asc, boolean gt, boolean eq, boolean cnt) { return BS(a, key, asc, gt, eq, cnt, asc ^ gt ? a.length : -1, asc ^ gt ? -1 : a.length); } final int BS(int[] a, int key, boolean asc, boolean gt, boolean eq, boolean cnt, int ng, int ok) { int index = binarySearch(a, key, gt, eq, ng, ok); return cnt ? (int)abs(ok - index) : index; } final int binarySearch(int[] a, int key, boolean gt, boolean eq, int ng, int ok) { while (abs(ok - ng) > 1) { int mid = (ok + ng) / 2; if(isOKforBS(a, mid, key, gt, eq)) ok = mid; else ng = mid; } return ok; } final boolean isOKforBS(int[] a, int index, int key, boolean gt, boolean eq) { return (a[index] > key && gt) || (a[index] < key && !gt) || (a[index] == key && eq); } final int lowerBound(long[] a, long key) { return BS(a, key, true, true, true); } final int lowerBound(long[] a, long key, int ng, int ok) { return BS(a, key, true, true, true, ng, ok); } final int upperBound(long[] a, long key) { return BS(a, key, true, true, false); } final int upperBound(long[] a, long key, int ng, int ok) { return BS(a, key, true, true, false, ng, ok); } final int cntBS(long[] a, long key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, true); } final int cntBS(long[] a, long key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, true, ng, ok); } final int BS(long[] a, long key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, false); } final int BS(long[] a, long key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, false, ng, ok); } final int BS(long[] a, long key, boolean asc, boolean gt, boolean eq, boolean cnt) { return BS(a, key, asc, gt, eq, cnt, asc ^ gt ? a.length : -1, asc ^ gt ? -1 : a.length); } final int BS(long[] a, long key, boolean asc, boolean gt, boolean eq, boolean cnt, int ng, int ok) { int index = binarySearch(a, key, gt, eq, ng, ok); return cnt ? (int)abs(ok - index) : index; } final int binarySearch(long[] a, long key, boolean gt, boolean eq, int ng, int ok) { while (abs(ok - ng) > 1) { int mid = (ok + ng) / 2; if(isOKforBS(a, mid, key, gt, eq)) ok = mid; else ng = mid; } return ok; } final boolean isOKforBS(long[] a, int index, long key, boolean gt, boolean eq) { return (a[index] > key && gt) || (a[index] < key && !gt) || (a[index] == key && eq); } final int lowerBound(double[] a, double key) { return BS(a, key, true, true, true); } final int lowerBound(double[] a, double key, int ng, int ok) { return BS(a, key, true, true, true, ng, ok); } final int upperBound(double[] a, double key) { return BS(a, key, true, true, false); } final int upperBound(double[] a, double key, int ng, int ok) { return BS(a, key, true, true, false, ng, ok); } final int cntBS(double[] a, double key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, true); } final int cntBS(double[] a, double key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, true, ng, ok); } final int BS(double[] a, double key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, false); } final int BS(double[] a, double key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, false, ng, ok); } final int BS(double[] a, double key, boolean asc, boolean gt, boolean eq, boolean cnt) { return BS(a, key, asc, gt, eq, cnt, asc ^ gt ? a.length : -1, asc ^ gt ? -1 : a.length); } final int BS(double[] a, double key, boolean asc, boolean gt, boolean eq, boolean cnt, int ng, int ok) { int index = binarySearch(a, key, gt, eq, ng, ok); return cnt ? (int)abs(ok - index) : index; } final int binarySearch(double[] a, double key, boolean gt, boolean eq, int ng, int ok) { while (abs(ok - ng) > 1) { int mid = (ok + ng) / 2; if(isOKforBS(a, mid, key, gt, eq)) ok = mid; else ng = mid; } return ok; } final boolean isOKforBS(double[] a, int index, double key, boolean gt, boolean eq) { return (a[index] > key && gt) || (a[index] < key && !gt) || (a[index] == key && eq); } final <T extends Comparable<? super T>> int lowerBound(T[] a, T key) { return BS(a, key, true, true, true); } final <T extends Comparable<? super T>> int lowerBound(T[] a, T key, int ng, int ok) { return BS(a, key, true, true, true, ng, ok); } final <T extends Comparable<? super T>> int upperBound(T[] a, T key) { return BS(a, key, true, true, false); } final <T extends Comparable<? super T>> int upperBound(T[] a, T key, int ng, int ok) { return BS(a, key, true, true, false, ng, ok); } final <T extends Comparable<? super T>> int cntBS(T[] a, T key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, true); } final <T extends Comparable<? super T>> int cntBS(T[] a, T key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, true, ng, ok); } final <T extends Comparable<? super T>> int BS(T[] a, T key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, false); } final <T extends Comparable<? super T>> int BS(T[] a, T key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, false, ng, ok); } final <T extends Comparable<? super T>> int BS(T[] a, T key, boolean asc, boolean gt, boolean eq, boolean cnt) { return BS(a, key, asc, gt, eq, cnt, asc ^ gt ? a.length : -1, asc ^ gt ? -1 : a.length); } final <T extends Comparable<? super T>> int BS(T[] a, T key, boolean asc, boolean gt, boolean eq, boolean cnt, int ng, int ok) { int index = binarySearch(a, key, gt, eq, ng, ok); return cnt ? (int)abs(ok - index) : index; } final <T extends Comparable<? super T>> int binarySearch(T[] a, T key, boolean gt, boolean eq, int ng, int ok) { while (abs(ok - ng) > 1) { int mid = (ok + ng) / 2; if(isOKforBS(a, mid, key, gt, eq)) ok = mid; else ng = mid; } return ok; } final <T extends Comparable<? super T>> boolean isOKforBS(T[] a, int index, T key, boolean gt, boolean eq) { int compare = a[index].compareTo(key); return (compare > 0 && gt) || (compare < 0 && !gt) || (compare == 0 && eq); } final <T> int lowerBound(T[] a, T key, Comparator<? super T> c) { return BS(a, key, true, true, true, c); } final <T> int lowerBound(T[] a, T key, int ng, int ok, Comparator<? super T> c) { return BS(a, key, true, true, true, ng, ok, c); } final <T> int upperBound(T[] a, T key, Comparator<? super T> c) { return BS(a, key, true, true, false, c); } final <T> int upperBound(T[] a, T key, int ng, int ok, Comparator<? super T> c) { return BS(a, key, true, true, false, ng, ok, c); } final <T> int cntBS(T[] a, T key, boolean asc, boolean gt, boolean eq, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, true, c); } final <T> int cntBS(T[] a, T key, boolean asc, boolean gt, boolean eq, int ng, int ok, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, true, ng, ok, c); } final <T> int BS(T[] a, T key, boolean asc, boolean gt, boolean eq, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, false, c); } final <T> int BS(T[] a, T key, boolean asc, boolean gt, boolean eq, int ng, int ok, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, false, ng, ok, c); } final <T> int BS(T[] a, T key, boolean asc, boolean gt, boolean eq, boolean cnt, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, cnt, asc ^ gt ? a.length : -1, asc ^ gt ? -1 : a.length, c); } final <T> int BS(T[] a, T key, boolean asc, boolean gt, boolean eq, boolean cnt, int ng, int ok, Comparator<? super T> c) { int index = binarySearch(a, key, gt, eq, ng, ok, c); return cnt ? (int)abs(ok - index) : index; } final <T> int binarySearch(T[] a, T key, boolean gt, boolean eq, int ng, int ok, Comparator<? super T> c) { while (abs(ok - ng) > 1) { int mid = (ok + ng) / 2; if(isOKforBS(a, mid, key, gt, eq, c)) ok = mid; else ng = mid; } return ok; } final <T> boolean isOKforBS(T[] a, int index, T key, boolean gt, boolean eq, Comparator<? super T> c) { int compare = c.compare(a[index], key); return (compare > 0 && gt) || (compare < 0 && !gt) || (compare == 0 && eq); } final <T extends Comparable<? super T>> int lowerBound(List<T> a, T key) { return BS(a, key, true, true, true); } final <T extends Comparable<? super T>> int lowerBound(List<T> a, T key, int ng, int ok) { return BS(a, key, true, true, true, ng, ok); } final <T extends Comparable<? super T>> int upperBound(List<T> a, T key) { return BS(a, key, true, true, false); } final <T extends Comparable<? super T>> int upperBound(List<T> a, T key, int ng, int ok) { return BS(a, key, true, true, false, ng, ok); } final <T extends Comparable<? super T>> int cntBS(List<T> a, T key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, true); } final <T extends Comparable<? super T>> int cntBS(List<T> a, T key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, true, ng, ok); } final <T extends Comparable<? super T>> int BS(List<T> a, T key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, false); } final <T extends Comparable<? super T>> int BS(List<T> a, T key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, false, ng, ok); } final <T extends Comparable<? super T>> int BS(List<T> a, T key, boolean asc, boolean gt, boolean eq, boolean cnt) { return BS(a, key, asc, gt, eq, cnt, asc ^ gt ? a.size() : -1, asc ^ gt ? -1 : a.size()); } final <T extends Comparable<? super T>> int BS(List<T> a, T key, boolean asc, boolean gt, boolean eq, boolean cnt, int ng, int ok) { int index = binarySearch(a, key, gt, eq, ng, ok); return cnt ? (int)abs(ok - index) : index; } final <T extends Comparable<? super T>> int binarySearch(List<T> a, T key, boolean gt, boolean eq, int ng, int ok) { while (abs(ok - ng) > 1) { int mid = (ok + ng) / 2; if(isOKforBS(a, mid, key, gt, eq)) ok = mid; else ng = mid; } return ok; } final <T extends Comparable<? super T>> boolean isOKforBS(List<T> a, int index, T key, boolean gt, boolean eq) { int compare = a.get(index).compareTo(key); return (compare > 0 && gt) || (compare < 0 && !gt) || (compare == 0 && eq); } final <T> int lowerBound(List<T> a, T key, Comparator<? super T> c) { return BS(a, key, true, true, true, c); } final <T> int lowerBound(List<T> a, T key, int ng, int ok, Comparator<? super T> c) { return BS(a, key, true, true, true, ng, ok, c); } final <T> int upperBound(List<T> a, T key, Comparator<? super T> c) { return BS(a, key, true, true, false, c); } final <T> int upperBound(List<T> a, T key, int ng, int ok, Comparator<? super T> c) { return BS(a, key, true, true, false, ng, ok, c); } final <T> int cntBS(List<T> a, T key, boolean asc, boolean gt, boolean eq, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, true, c); } final <T> int cntBS(List<T> a, T key, boolean asc, boolean gt, boolean eq, int ng, int ok, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, true, ng, ok, c); } final <T> int BS(List<T> a, T key, boolean asc, boolean gt, boolean eq, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, false, c); } final <T> int BS(List<T> a, T key, boolean asc, boolean gt, boolean eq, int ng, int ok, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, false, ng, ok, c); } final <T> int BS(List<T> a, T key, boolean asc, boolean gt, boolean eq, boolean cnt, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, cnt, asc ^ gt ? a.size() : -1, asc ^ gt ? -1 : a.size(), c); } final <T> int BS(List<T> a, T key, boolean asc, boolean gt, boolean eq, boolean cnt, int ng, int ok, Comparator<? super T> c) { int index = binarySearch(a, key, gt, eq, ng, ok, c); return cnt ? (int)abs(ok - index) : index; } final <T> int binarySearch(List<T> a, T key, boolean gt, boolean eq, int ng, int ok, Comparator<? super T> c) { while (abs(ok - ng) > 1) { int mid = (ok + ng) / 2; if(isOKforBS(a, mid, key, gt, eq, c)) ok = mid; else ng = mid; } return ok; } final <T> boolean isOKforBS(List<T> a, int index, T key, boolean gt, boolean eq, Comparator<? super T> c) { int compare = c.compare(a.get(index), key); return (compare > 0 && gt) || (compare < 0 && !gt) || (compare == 0 && eq); } final PairLL binaryRangeSearch(long left, long right, UnaryOperator<Long> op, boolean minimize) { long ok1 = right, ng1 = left; while(abs(ok1 - ng1) > 1) { long mid = (ok1 + ng1) / 2; boolean isOK = (op.apply(mid + 1) - op.apply(mid)) * (minimize ? 1 : -1) >= 0; if(isOK) ok1 = mid; else ng1 = mid; } long ok2 = left, ng2 = right; while(abs(ok2 - ng2) > 1) { long mid = (ok2 + ng2) / 2; boolean isOK = (op.apply(mid - 1) - op.apply(mid)) * (minimize ? 1 : -1) >= 0; if(isOK) ok2 = mid; else ng2 = mid; } return new PairLL(ok1, ok2); //[l, r] } final double ternarySearch(double left, double right, UnaryOperator<Double> op, boolean minimize, int loop) { for(int cnt = 0; cnt < loop; cnt ++) { double m1 = (left * 2 + right) / 3.0; double m2 = (left + right * 2) / 3.0; if(op.apply(m1) > op.apply(m2) ^ minimize) right = m2; else left = m1; } return (left + right) / 2.0; } // mods Mod md = new Mod(); // class Mod107 extends Mod { Mod107() { super(1_000_000_007); } } Mod107 md = new Mod107(); // class Mod998 extends Mod { Mod998() { super(998244353); } } Mod998 md = new Mod998(); class Mod { final long MOD = 1_000_000_007; Mod() { MH = 0; ML = 0; IS_MOD_CONST = true; } // final long MOD = 998244353; Mod() { MH = 0; ML = 0; IS_MOD_CONST = true; } // final long MOD; Mod(long mod) { MOD = mod; IS_MOD_CONST = false; long a = (1l << 32) / MOD; long b = (1l << 32) % MOD; long m = a * a * MOD + 2 * a * b + (b * b) / MOD; MH = m >>> 32; ML = m & MASK; } static final long MASK = 0xffff_ffffl; final long MH; final long ML; final boolean IS_MOD_CONST; final long reduce(long x) { if(MOD == 1) return 0; if(x < 0) return (x = reduce(- x)) == 0 ? 0 : MOD - x; long z = (x & MASK) * ML; z = (x & MASK) * MH + (x >>> 32) * ML + (z >>> 32); z = (x >>> 32) * MH + (z >>> 32); x -= z * MOD; return x < MOD ? x : x - MOD; } final long mod(long x) { if(0 <= x && x < MOD) return x; if(- MOD <= x && x < 0) return x + MOD; return IS_MOD_CONST ? ((x %= MOD) < 0 ? x + MOD : x) : reduce(x); } final long[] mod(long[] a) { for(int i = 0; i < a.length; i ++) a[i] = mod(a[i]); return a; } final long[][] mod(long[][] a) { for(int i = 0; i < a.length; i ++) mod(a[i]); return a; } final long[][][] mod(long[][][] a) { for(int i = 0; i < a.length; i ++) mod(a[i]); return a; } final long add(long x, long y) { return (x += y) >= MOD * 2 || x < 0 ? mod(x) : x >= MOD ? x - MOD : x; } final long sum(long... x) { long sum = 0; for(long ele : x) sum = add(sum, ele); return sum; } final long sub(long x, long y) { return (x -= y) < - MOD || x >= MOD ? mod(x) : x < 0 ? x + MOD : x; } final long pow(long x, long y) { nonNegativeCheck(y); x = mod(x); long ans = 1; for(; y > 0; y >>= 1) { if((y & 1) != 0) ans = mul(ans, x); x = mul(x, x); } return ans; } final long mul(long x, long y) { if(x >= 0 && x < MOD && y >= 0 && y < MOD) return IS_MOD_CONST ? (x * y) % MOD : reduce(x * y); x = mod(x); y = mod(y); return IS_MOD_CONST ? (x * y) % MOD : reduce(x * y); } final long mul(long... x) { long ans = 1; for(long ele : x) ans = mul(ans, ele); return ans; } final long div(long x, long y) { return mul(x, inv(y)); } final long[] pows(long x, int max) { x = mod(x); long pow[] = new long[max + 1]; pow[0] = 1; for(int i = 0; i < max; i ++) pow[i + 1] = mul(pow[i], x); return pow; } final long fact(int n) { nonNegativeCheck(n); prepareFact(); if(n < MAX_FACT1) return fact[n]; else { long ans = fact[MAX_FACT1 - 1]; for(int i = MAX_FACT1; i <= n; i ++) ans = mul(ans, i); return ans; } } final long invFact(int n) { nonNegativeCheck(n); prepareFact(); if(n < MAX_FACT1) return invFact[n]; else return inv(fact(n)); } static final int MAX_INV_SIZE = 100_100; final Map<Long, Long> invMap = new HashMap<>(); final long inv(long x) { x = mod(x); if(invMap.containsKey(x)) return invMap.get(x); if(invMap.size() >= MAX_INV_SIZE) return calInv(x); invMap.put(x, calInv(x)); return invMap.get(x); } final long calInv(long x) { // O(logM) PairLL s = new PairLL(MOD, 0); PairLL t = new PairLL(mod(x), 1); while(t.a > 0) { long tmp = s.a / t.a; PairLL u = new PairLL(s.a - t.a * tmp, s.b - t.b * tmp); s = t; t = u; } if(s.b < 0) s.b += MOD / s.a; return s.b; } final long[] invs(int n) { // O(N) positiveCheck(n); long inv[] = new long[n + 1]; inv[1] = 1; for(int i = 2; i <= n; i ++) inv[i] = mul(inv[(int)(MOD % i)], (MOD - MOD / i)); return inv; } static final int MAX_FACT1 = 5_000_100; static final int MAX_FACT2 = 500_100; static final int MAX_FACT_MAP_SIZE = 100; long fact[]; long invFact[]; boolean isFactPrepared = false; final Map<Long, long[]> factMap = new HashMap<>(); final void prepareFact() { if(isFactPrepared) return; fact = new long[MAX_FACT1]; invFact = new long[MAX_FACT1]; fill(fact, 0); fill(invFact, 0); fact[0] = 1; int maxIndex = min(MAX_FACT1, (int)MOD); for(int i = 1; i < maxIndex; i ++) fact[i] = mul(fact[i - 1], i); invFact[maxIndex - 1] = inv(fact[maxIndex - 1]); for(int i = maxIndex - 1; i > 0; i --) invFact[i - 1] = mul(invFact[i], i); isFactPrepared = true; } final long P(long n, long r) { if(!isFactPrepared) prepareFact(); if(n < 0 || r < 0 || n < r) return 0; if(n < MAX_FACT1 && n < MOD) return mul(fact[(int)n], invFact[(int)(n - r)]); if(!factMap.containsKey(n)) { long largeFact[] = new long[MAX_FACT2]; factMap.put(n, largeFact); fill(largeFact, -1); largeFact[0] = 1; } long largeFact[] = factMap.get(n); if(r >= MAX_FACT2) { long ans = 1; for(long i = n - r + 1; i <= n; i ++) ans = mul(ans, i); return ans; }else { int i = (int)r; while(largeFact[i] < 0) i --; for(; i < r; i ++) largeFact[i + 1] = mul(largeFact[i], n - i); if(factMap.size() > MAX_FACT_MAP_SIZE) factMap.remove(n); return largeFact[(int)r]; } } final long C(long n, long r) { if(!isFactPrepared) prepareFact(); if(n < 0) return mod(C(- n + r - 1, - n - 1) * ((r & 1) == 0 ? 1 : -1)); if(r < 0 || n < r) return 0; r = min(r, n - r); if(n < MOD) return mul(P(n, r), r < MAX_FACT1 ? invFact[(int)r] : inv(fact((int)r))); long digitN[] = baseConvert(n, MOD); long digitR[] = baseConvert(r, MOD); int len = digitN.length; digitR = resize(digitR, len, 0); long ans = 1; for(int i = 0; i < len; i ++) ans = mul(ans, C(digitN[i], digitR[i])); return ans; } final long H(long n, long r) { return C(n - 1 + r, r); } final long sqrt(long x) { x = mod(x); long p = (MOD - 1) >> 1; if(pow(x, p) != 1) return -1; long q = MOD - 1; int m = 1; while(((q >>= 1) & 1) == 0) m ++; long z = 1; while(pow(z, p) == 1) z = random(1, MOD); long c = pow(z, q); long t = pow(x, q); long r = pow(x, (q + 1) >> 1); if(t == 0) return 0; m -= 2; while(t != 1) { long pows[] = new long[m + 1]; pows[0] = t; for(int i = 0; i < m; i ++) pows[i + 1] = mul(pows[i], pows[i]); while(pows[m --] == 1) c = mul(c, c); r = mul(r, c); c = mul(c, c); t = mul(t, c); } return r; } } final long mod(long x, long mod) { if(0 <= x && x < mod) return x; if(- mod <= x && x < 0) return x + mod; return (x %= mod) < 0 ? x + mod : x; } final long pow(long x, long y, long mod) { nonNegativeCheck(y); x = mod(x, mod); long ans = 1; for(; y > 0; y >>= 1) { if((y & 1) != 0) ans = mod(ans * x, mod); x = mod(x * x, mod); } return ans; } // grid class Grids { int h, w; Grid[][] gs; Grid[] gi; Grids(int h, int w) { nonNegativeCheck(h); nonNegativeCheck(w); this.h = h; this.w = w; gs = new Grid[h][w]; gi = new Grid[h * w]; for(int i = 0; i < h; i ++) { for(int j = 0; j < w; j ++) { gs[i][j] = new Grid(i, j, h, w); gi[gs[i][j].i] = gs[i][j]; } } } void init(boolean[][] b) { for(int i = 0; i < h; i ++) for(int j = 0; j < w; j ++) gs[i][j].b = b[i][j]; } void init(long[][] val) { for(int i = 0; i < h; i ++) for(int j = 0; j < w; j ++) gs[i][j].val = val[i][j]; } Grid get(int x, int y) { return isValid(x, y, h, w) ? gs[x][y] : null; } Grid get(int i) { return get(i / w, i % w); } int dx[] = {0, -1, 1, 0, 0, -1, 1, -1, 1}; int dy[] = {0, 0, 0, -1, 1, -1, -1, 1, 1}; Grid next(int x, int y, int i) { return next(gs[x][y], i); } Grid next(Grid g, int i) { return isValid(g.x + dx[i], g.y + dy[i], g.h, g.w) ? gs[g.x + dx[i]][g.y + dy[i]] : null; } } class Grid implements Comparable<Grid> { int x, y, h, w, i; boolean b; long val; Grid() { } Grid(int x, int y, int h, int w) { init(x, y, h, w, false, 0); } Grid(int x, int y, int h, int w, boolean b) { init(x, y, h, w, b, 0); } Grid(int x, int y, int h, int w, long val) { init(x, y, h, w, false, val); } Grid(int x, int y, int h, int w, boolean b, long val) { init(x, y, h, w, b, val); } void init(int x, int y, int h, int w, boolean b, long val) { this.x = x; this.y = y; this.h = h; this.w = w; this.b = b; this.val = val; this.i = x * w + y; } @Override public String toString() { return "("+x+", "+y+")"+" "+booleanToString(b)+" "+val; } @Override public int hashCode() { return Objects.hash(x, y, h, w, b, val); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; Grid that = (Grid) obj; if(this.x != that.x) return false; if(this.y != that.y) return false; if(this.h != that.h) return false; if(this.w != that.w) return false; if(this.b != that.b) return false; if(this.val != that.val) return false; return true; } @Override public int compareTo(Grid that) { int c = Long.compare(this.val, that.val); if(c == 0) c = Integer.compare(this.x, that.x); if(c == 0) c = Integer.compare(this.y, that.y); return c; } } final boolean isValid(int x, int y, int h, int w) { return x >= 0 && x < h && y >= 0 && y < w; } final boolean isValid(Grid g) { return isValid(g.x, g.y, g.h, g.w); } // graph class Graph { int numNode, numEdge; boolean directed; List<Edge> edges = new ArrayList<>(); Node nodes[]; Node reversedNodes[]; Graph(int numNode, int numEdge, boolean directed) { nonNegativeCheck(numNode); this.numNode = numNode; this.numEdge = numEdge; this.directed = directed; nodes = new Node[numNode]; reversedNodes = new Node[numNode]; for(int i = 0; i < numNode; i ++) { nodes[i] = new Node(i); reversedNodes[i] = new Node(i); } } void init(List<Edge> edges) { this.edges = edges; for(Edge e : edges) add(e); } void add(int source, int target, long cost) { add(new Edge(source, target, cost)); } void add(Edge e) { rangeCheck(e.source, numNode); rangeCheck(e.target, numNode); edges.add(e); nodes[e.source].add(e.target, e.cost); if(directed) reversedNodes[e.target].add(e.source, e.cost); else nodes[e.target].add(e.source, e.cost); numEdge = edges.size(); } void clearNodes() { edges.clear(); numEdge = 0; for(Node n : nodes) n.clear(); for(Node n : reversedNodes) n.clear(); } } class Node extends ArrayList<Edge> { int id; Node(int id) { this.id = id; } void add(int target, long cost) { add(new Edge(id, target, cost)); } } class Edge implements Comparable<Edge> { int source; int target; long cost; Edge(int source, int target, long cost) { this.source = source; this.target = target; this.cost = cost; } @Override public String toString() { return source+" - "+cost+" -> "+target; } @Override public int hashCode() { return Objects.hash(source, target); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; Edge that = (Edge) obj; if(this.source != that.source) return false; if(this.target != that.target) return false; return true; } @Override public int compareTo(Edge that) { int c = Long.compare(this.cost, that.cost); if(c == 0) c = Integer.compare(this.source, that.source); if(c == 0) c = Integer.compare(this.target, that.target); return c; } } // Pair class Pair<T extends Comparable<? super T>, U extends Comparable<? super U>> implements Comparable<Pair<T, U>> { T a; U b; Pair() { } Pair(T a, U b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a.toString()+", "+b.toString()+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; Pair that = (Pair) obj; if(this.a.getClass() != that.a.getClass()) return false; if(this.b.getClass() != that.b.getClass()) return false; if(!this.a.equals(that.a)) return false; if(!this.b.equals(that.b)) return false; return true; } @Override public int compareTo(Pair<T, U> that) { int c = (this.a).compareTo(that.a); if(c == 0) c = (this.b).compareTo(that.b); return c; } } final PairII npii() { return new PairII(ni(), ni()); } final PairII[] npii(int n) { PairII a[] = new PairII[n]; for(int i = 0; i < n; i ++) a[i] = npii(); return a; } final PairII[][] npii(int n, int m) { PairII a[][] = new PairII[n][m]; for(int i = 0; i < n; i ++) a[i] = npii(m); return a; } class PairII implements Comparable<PairII> { int a; int b; PairII() { } PairII(int a, int b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a+", "+b+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; PairII that = (PairII) obj; if(this.a != that.a || this.b != that.b) return false; return true; } @Override public int compareTo(PairII that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); return c; } } final PairIL npil() { return new PairIL(ni(), nl()); } final PairIL[] npil(int n) { PairIL a[] = new PairIL[n]; for(int i = 0; i < n; i ++) a[i] = npil(); return a; } final PairIL[][] npil(int n, int m) { PairIL a[][] = new PairIL[n][m]; for(int i = 0; i < n; i ++) a[i] = npil(m); return a; } class PairIL implements Comparable<PairIL> { int a; long b; PairIL() { } PairIL(int a, long b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a+", "+b+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; PairIL that = (PairIL) obj; if(this.a != that.a || this.b != that.b) return false; return true; } @Override public int compareTo(PairIL that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); return c; } } final PairID npid() { return new PairID(ni(), nd()); } final PairID[] npid(int n) { PairID a[] = new PairID[n]; for(int i = 0; i < n; i ++) a[i] = npid(); return a; } final PairID[][] npid(int n, int m) { PairID a[][] = new PairID[n][m]; for(int i = 0; i < n; i ++) a[i] = npid(m); return a; } class PairID implements Comparable<PairID> { int a; double b; PairID() { } PairID(int a, double b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a+", "+b+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; PairID that = (PairID) obj; if(this.a != that.a || this.b != that.b) return false; return true; } @Override public int compareTo(PairID that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); return c; } } final PairLI npli() { return new PairLI(nl(), ni()); } final PairLI[] npli(int n) { PairLI a[] = new PairLI[n]; for(int i = 0; i < n; i ++) a[i] = npli(); return a; } final PairLI[][] npli(int n, int m) { PairLI a[][] = new PairLI[n][m]; for(int i = 0; i < n; i ++) a[i] = npli(m); return a; } class PairLI implements Comparable<PairLI> { long a; int b; PairLI() { } PairLI(long a, int b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a+", "+b+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; PairLI that = (PairLI) obj; if(this.a != that.a || this.b != that.b) return false; return true; } @Override public int compareTo(PairLI that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); return c; } } final PairLL npll() { return new PairLL(nl(), nl()); } final PairLL[] npll(int n) { PairLL a[] = new PairLL[n]; for(int i = 0; i < n; i ++) a[i] = npll(); return a; } final PairLL[][] npll(int n, int m) { PairLL a[][] = new PairLL[n][m]; for(int i = 0; i < n; i ++) a[i] = npll(m); return a; } class PairLL implements Comparable<PairLL> { long a; long b; PairLL() { } PairLL(long a, long b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a+", "+b+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; PairLL that = (PairLL) obj; if(this.a != that.a || this.b != that.b) return false; return true; } @Override public int compareTo(PairLL that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); return c; } } final PairLD npld() { return new PairLD(nl(), nd()); } final PairLD[] npld(int n) { PairLD a[] = new PairLD[n]; for(int i = 0; i < n; i ++) a[i] = npld(); return a; } final PairLD[][] npld(int n, int m) { PairLD a[][] = new PairLD[n][m]; for(int i = 0; i < n; i ++) a[i] = npld(m); return a; } class PairLD implements Comparable<PairLD> { long a; double b; PairLD() { } PairLD(long a, double b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a+", "+b+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; PairLD that = (PairLD) obj; if(this.a != that.a || this.b != that.b) return false; return true; } @Override public int compareTo(PairLD that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); return c; } } final PairDI npdi() { return new PairDI(nd(), ni()); } final PairDI[] npdi(int n) { PairDI a[] = new PairDI[n]; for(int i = 0; i < n; i ++) a[i] = npdi(); return a; } final PairDI[][] npdi(int n, int m) { PairDI a[][] = new PairDI[n][m]; for(int i = 0; i < n; i ++) a[i] = npdi(m); return a; } class PairDI implements Comparable<PairDI> { double a; int b; PairDI() { } PairDI(double a, int b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a+", "+b+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; PairDI that = (PairDI) obj; if(this.a != that.a || this.b != that.b) return false; return true; } @Override public int compareTo(PairDI that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); return c; } } final PairDL npdl() { return new PairDL(nd(), nl()); } final PairDL[] npdl(int n) { PairDL a[] = new PairDL[n]; for(int i = 0; i < n; i ++) a[i] = npdl(); return a; } final PairDL[][] npdl(int n, int m) { PairDL a[][] = new PairDL[n][m]; for(int i = 0; i < n; i ++) a[i] = npdl(m); return a; } class PairDL implements Comparable<PairDL> { double a; long b; PairDL() { } PairDL(double a, long b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a+", "+b+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; PairDL that = (PairDL) obj; if(this.a != that.a || this.b != that.b) return false; return true; } @Override public int compareTo(PairDL that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); return c; } } final PairDD npdd() { return new PairDD(nd(), nd()); } final PairDD[] npdd(int n) { PairDD a[] = new PairDD[n]; for(int i = 0; i < n; i ++) a[i] = npdd(); return a; } final PairDD[][] npdd(int n, int m) { PairDD a[][] = new PairDD[n][m]; for(int i = 0; i < n; i ++) a[i] = npdd(m); return a; } class PairDD implements Comparable<PairDD> { double a; double b; PairDD() { } PairDD(double a, double b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a+", "+b+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; PairDD that = (PairDD) obj; if(this.a != that.a || this.b != that.b) return false; return true; } @Override public int compareTo(PairDD that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); return c; } } interface ITuple { public StringBuilder toStringBuilder(); @Override public String toString(); @Override public int hashCode(); @Override public boolean equals(Object obj); } class BasicTuple<T extends ITuple & Comparable<? super T>, V extends Comparable<? super V>> implements Comparable<BasicTuple> { T t; V a; BasicTuple() { } StringBuilder sbTuple = new StringBuilder(); public StringBuilder toStringBuilder() { sbTuple.setLength(0); return sbTuple.append(t.toStringBuilder()).append(", ").append(a); } @Override public String toString() { return "("+toStringBuilder().toString()+")"; } @Override public int hashCode() { return Objects.hash(t, a); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; BasicTuple that = (BasicTuple) obj; if(this.t.getClass() != that.t.getClass()) return false; if(this.a.getClass() != that.a.getClass()) return false; if(!this.t.equals(that.t)) return false; if(!this.a.equals(that.a)) return false; return true; } @Override @SuppressWarnings("unchecked") public int compareTo(BasicTuple that) { int c = (this.t).compareTo((T) (Object) that.t); if(c == 0) c = (this.a).compareTo((V) (Object) that.a); return c; } } class UniqueTuple<V extends Comparable<? super V>> implements ITuple, Comparable<UniqueTuple> { V a; UniqueTuple() { } final StringBuilder sbTuple = new StringBuilder(); public StringBuilder toStringBuilder() { sbTuple.setLength(0); return sbTuple.append(a); } @Override public String toString() { return "("+toStringBuilder().toString()+")"; } @Override public int hashCode() { return Objects.hash(a); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; UniqueTuple that = (UniqueTuple) obj; if(this.a.getClass() != that.a.getClass()) return false; if(!this.a.equals(that.a)) return false; return true; } @Override @SuppressWarnings("unchecked") public int compareTo(UniqueTuple that) { return (this.a).compareTo((V) (Object) that.a); } } class Tuple1<T0 extends Comparable<? super T0>> extends UniqueTuple<T0> implements ITuple { Tuple1() { super(); } Tuple1(T0 a0) { super(); this.a = a0; } T0 get0() { return a; } void set0(T0 x) { a = x; } } class Tuple2< T0 extends Comparable<? super T0>, T1 extends Comparable<? super T1>> extends BasicTuple<Tuple1<T0>, T1> implements ITuple { Tuple2() { super(); } @SuppressWarnings("unchecked") Tuple2(T0 a0, T1 a1) { super(); this.t = new Tuple1(a0); this.a = a1; } T0 get0() { return t.get0(); } T1 get1() { return a; } void set0(T0 x) { t.set0(x); } void set1(T1 x) { a = x; } } class Tuple3< T0 extends Comparable<? super T0>, T1 extends Comparable<? super T1>, T2 extends Comparable<? super T2>> extends BasicTuple<Tuple2<T0, T1>, T2> implements ITuple { Tuple3() { super(); } @SuppressWarnings("unchecked") Tuple3(T0 a0, T1 a1, T2 a2) { super(); this.t = new Tuple2(a0, a1); this.a = a2; } T0 get0() { return t.get0(); } T1 get1() { return t.get1(); } T2 get2() { return a; } void set0(T0 x) { t.set0(x); } void set1(T1 x) { t.set1(x); } void set2(T2 x) { a = x; } } class Tuple4< T0 extends Comparable<? super T0>, T1 extends Comparable<? super T1>, T2 extends Comparable<? super T2>, T3 extends Comparable<? super T3>> extends BasicTuple<Tuple3<T0, T1, T2>, T3> implements ITuple { Tuple4() { super(); } @SuppressWarnings("unchecked") Tuple4(T0 a0, T1 a1, T2 a2, T3 a3) { super(); this.t = new Tuple3(a0, a1, a2); this.a = a3; } T0 get0() { return t.get0(); } T1 get1() { return t.get1(); } T2 get2() { return t.get2(); } T3 get3() { return a; } void set0(T0 x) { t.set0(x); } void set1(T1 x) { t.set1(x); } void set2(T2 x) { t.set2(x); } void set3(T3 x) { a = x; } } class Tuple5< T0 extends Comparable<? super T0>, T1 extends Comparable<? super T1>, T2 extends Comparable<? super T2>, T3 extends Comparable<? super T3>, T4 extends Comparable<? super T4>> extends BasicTuple<Tuple4<T0, T1, T2, T3>, T4> implements ITuple { Tuple5() { super(); } @SuppressWarnings("unchecked") Tuple5(T0 a0, T1 a1, T2 a2, T3 a3, T4 a4) { super(); this.t = new Tuple4(a0, a1, a2, a3); this.a = a4; } T0 get0() { return t.get0(); } T1 get1() { return t.get1(); } T2 get2() { return t.get2(); } T3 get3() { return t.get3(); } T4 get4() { return a; } void set0(T0 x) { t.set0(x); } void set1(T1 x) { t.set1(x); } void set2(T2 x) { t.set2(x); } void set3(T3 x) { t.set3(x); } void set4(T4 x) { a = x; } } class Tuple6< T0 extends Comparable<? super T0>, T1 extends Comparable<? super T1>, T2 extends Comparable<? super T2>, T3 extends Comparable<? super T3>, T4 extends Comparable<? super T4>, T5 extends Comparable<? super T5>> extends BasicTuple<Tuple5<T0, T1, T2, T3, T4>, T5> implements ITuple { Tuple6() { super(); } @SuppressWarnings("unchecked") Tuple6(T0 a0, T1 a1, T2 a2, T3 a3, T4 a4, T5 a5) { super(); this.t = new Tuple5(a0, a1, a2, a3, a4); this.a = a5; } T0 get0() { return t.get0(); } T1 get1() { return t.get1(); } T2 get2() { return t.get2(); } T3 get3() { return t.get3(); } T4 get4() { return t.get4(); } T5 get5() { return a; } void set0(T0 x) { t.set0(x); } void set1(T1 x) { t.set1(x); } void set2(T2 x) { t.set2(x); } void set3(T3 x) { t.set3(x); } void set4(T4 x) { t.set4(x); } void set5(T5 x) { a = x; } } class Tuple7< T0 extends Comparable<? super T0>, T1 extends Comparable<? super T1>, T2 extends Comparable<? super T2>, T3 extends Comparable<? super T3>, T4 extends Comparable<? super T4>, T5 extends Comparable<? super T5>, T6 extends Comparable<? super T6>> extends BasicTuple<Tuple6<T0, T1, T2, T3, T4, T5>, T6> implements ITuple { Tuple7() { super(); } @SuppressWarnings("unchecked") Tuple7(T0 a0, T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T6 a6) { super(); this.t = new Tuple6(a0, a1, a2, a3, a4, a5); this.a = a6; } T0 get0() { return t.get0(); } T1 get1() { return t.get1(); } T2 get2() { return t.get2(); } T3 get3() { return t.get3(); } T4 get4() { return t.get4(); } T5 get5() { return t.get5(); } T6 get6() { return a; } void set0(T0 x) { t.set0(x); } void set1(T1 x) { t.set1(x); } void set2(T2 x) { t.set2(x); } void set3(T3 x) { t.set3(x); } void set4(T4 x) { t.set4(x); } void set5(T5 x) { t.set5(x); } void set6(T6 x) { a = x; } } class Tuple8< T0 extends Comparable<? super T0>, T1 extends Comparable<? super T1>, T2 extends Comparable<? super T2>, T3 extends Comparable<? super T3>, T4 extends Comparable<? super T4>, T5 extends Comparable<? super T5>, T6 extends Comparable<? super T6>, T7 extends Comparable<? super T7>> extends BasicTuple<Tuple7<T0, T1, T2, T3, T4, T5, T6>, T7> implements ITuple { Tuple8() { super(); } @SuppressWarnings("unchecked") Tuple8(T0 a0, T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T6 a6, T7 a7) { super(); this.t = new Tuple7(a0, a1, a2, a3, a4, a5, a6); this.a = a7; } T0 get0() { return t.get0(); } T1 get1() { return t.get1(); } T2 get2() { return t.get2(); } T3 get3() { return t.get3(); } T4 get4() { return t.get4(); } T5 get5() { return t.get5(); } T6 get6() { return t.get6(); } T7 get7() { return a; } void set0(T0 x) { t.set0(x); } void set1(T1 x) { t.set1(x); } void set2(T2 x) { t.set2(x); } void set3(T3 x) { t.set3(x); } void set4(T4 x) { t.set4(x); } void set5(T5 x) { t.set5(x); } void set6(T6 x) { t.set6(x); } void set7(T7 x) { a = x; } } class TupleIII implements Comparable<TupleIII> { int a; int b; int c; TupleIII() { } TupleIII(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleIII that = (TupleIII) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleIII that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); if(c == 0) c = Integer.compare(this.c, that.c); return c; } } class TupleIIL implements Comparable<TupleIIL> { int a; int b; long c; TupleIIL() { } TupleIIL(int a, int b, long c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleIIL that = (TupleIIL) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleIIL that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); if(c == 0) c = Long.compare(this.c, that.c); return c; } } class TupleIID implements Comparable<TupleIID> { int a; int b; double c; TupleIID() { } TupleIID(int a, int b, double c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleIID that = (TupleIID) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleIID that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); if(c == 0) c = Double.compare(this.c, that.c); return c; } } class TupleILI implements Comparable<TupleILI> { int a; long b; int c; TupleILI() { } TupleILI(int a, long b, int c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleILI that = (TupleILI) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleILI that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); if(c == 0) c = Integer.compare(this.c, that.c); return c; } } class TupleILL implements Comparable<TupleILL> { int a; long b; long c; TupleILL() { } TupleILL(int a, long b, long c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleILL that = (TupleILL) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleILL that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); if(c == 0) c = Long.compare(this.c, that.c); return c; } } class TupleILD implements Comparable<TupleILD> { int a; long b; double c; TupleILD() { } TupleILD(int a, long b, double c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleILD that = (TupleILD) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleILD that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); if(c == 0) c = Double.compare(this.c, that.c); return c; } } class TupleIDI implements Comparable<TupleIDI> { int a; double b; int c; TupleIDI() { } TupleIDI(int a, double b, int c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleIDI that = (TupleIDI) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleIDI that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); if(c == 0) c = Integer.compare(this.c, that.c); return c; } } class TupleIDL implements Comparable<TupleIDL> { int a; double b; long c; TupleIDL() { } TupleIDL(int a, double b, long c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleIDL that = (TupleIDL) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleIDL that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); if(c == 0) c = Long.compare(this.c, that.c); return c; } } class TupleIDD implements Comparable<TupleIDD> { int a; double b; double c; TupleIDD() { } TupleIDD(int a, double b, double c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleIDD that = (TupleIDD) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleIDD that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); if(c == 0) c = Double.compare(this.c, that.c); return c; } } class TupleLII implements Comparable<TupleLII> { long a; int b; int c; TupleLII() { } TupleLII(long a, int b, int c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleLII that = (TupleLII) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleLII that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); if(c == 0) c = Integer.compare(this.c, that.c); return c; } } class TupleLIL implements Comparable<TupleLIL> { long a; int b; long c; TupleLIL() { } TupleLIL(long a, int b, long c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleLIL that = (TupleLIL) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleLIL that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); if(c == 0) c = Long.compare(this.c, that.c); return c; } } class TupleLID implements Comparable<TupleLID> { long a; int b; double c; TupleLID() { } TupleLID(long a, int b, double c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleLID that = (TupleLID) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleLID that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); if(c == 0) c = Double.compare(this.c, that.c); return c; } } class TupleLLI implements Comparable<TupleLLI> { long a; long b; int c; TupleLLI() { } TupleLLI(long a, long b, int c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleLLI that = (TupleLLI) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleLLI that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); if(c == 0) c = Integer.compare(this.c, that.c); return c; } } class TupleLLL implements Comparable<TupleLLL> { long a; long b; long c; TupleLLL() { } TupleLLL(long a, long b, long c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleLLL that = (TupleLLL) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleLLL that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); if(c == 0) c = Long.compare(this.c, that.c); return c; } } class TupleLLD implements Comparable<TupleLLD> { long a; long b; double c; TupleLLD() { } TupleLLD(long a, long b, double c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleLLD that = (TupleLLD) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleLLD that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); if(c == 0) c = Double.compare(this.c, that.c); return c; } } class TupleLDI implements Comparable<TupleLDI> { long a; double b; int c; TupleLDI() { } TupleLDI(long a, double b, int c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleLDI that = (TupleLDI) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleLDI that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); if(c == 0) c = Integer.compare(this.c, that.c); return c; } } class TupleLDL implements Comparable<TupleLDL> { long a; double b; long c; TupleLDL() { } TupleLDL(long a, double b, long c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleLDL that = (TupleLDL) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleLDL that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); if(c == 0) c = Long.compare(this.c, that.c); return c; } } class TupleLDD implements Comparable<TupleLDD> { long a; double b; double c; TupleLDD() { } TupleLDD(long a, double b, double c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleLDD that = (TupleLDD) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleLDD that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); if(c == 0) c = Double.compare(this.c, that.c); return c; } } class TupleDII implements Comparable<TupleDII> { double a; int b; int c; TupleDII() { } TupleDII(double a, int b, int c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleDII that = (TupleDII) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleDII that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); if(c == 0) c = Integer.compare(this.c, that.c); return c; } } class TupleDIL implements Comparable<TupleDIL> { double a; int b; long c; TupleDIL() { } TupleDIL(double a, int b, long c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleDIL that = (TupleDIL) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleDIL that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); if(c == 0) c = Long.compare(this.c, that.c); return c; } } class TupleDID implements Comparable<TupleDID> { double a; int b; double c; TupleDID() { } TupleDID(double a, int b, double c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleDID that = (TupleDID) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleDID that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); if(c == 0) c = Double.compare(this.c, that.c); return c; } } class TupleDLI implements Comparable<TupleDLI> { double a; long b; int c; TupleDLI() { } TupleDLI(double a, long b, int c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleDLI that = (TupleDLI) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleDLI that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); if(c == 0) c = Integer.compare(this.c, that.c); return c; } } class TupleDLL implements Comparable<TupleDLL> { double a; long b; long c; TupleDLL() { } TupleDLL(double a, long b, long c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleDLL that = (TupleDLL) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleDLL that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); if(c == 0) c = Long.compare(this.c, that.c); return c; } } class TupleDLD implements Comparable<TupleDLD> { double a; long b; double c; TupleDLD() { } TupleDLD(double a, long b, double c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleDLD that = (TupleDLD) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleDLD that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); if(c == 0) c = Double.compare(this.c, that.c); return c; } } class TupleDDI implements Comparable<TupleDDI> { double a; double b; int c; TupleDDI() { } TupleDDI(double a, double b, int c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleDDI that = (TupleDDI) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleDDI that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); if(c == 0) c = Integer.compare(this.c, that.c); return c; } } class TupleDDL implements Comparable<TupleDDL> { double a; double b; long c; TupleDDL() { } TupleDDL(double a, double b, long c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleDDL that = (TupleDDL) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleDDL that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); if(c == 0) c = Long.compare(this.c, that.c); return c; } } class TupleDDD implements Comparable<TupleDDD> { double a; double b; double c; TupleDDD() { } TupleDDD(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleDDD that = (TupleDDD) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleDDD that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); if(c == 0) c = Double.compare(this.c, that.c); return c; } } public void solve() { long n = nl(); int m = ni(); int d = ni(); long r[] = nl(m + 1); r = resize(r, m * 2, m - 1); for(int i = 0; i < m; i ++) r[i] = - r[m * 2 - i - 1]; for(int i = 0; i < m; i ++) r[m + i] ++; long s[] = nl(m); s = resize(s, m * 2 + 1, m); for(int i = 1; i <= m; i ++) s[i] = s[m * 2 - i]; for(int i = m * 2; i > 0; i --) s[i] -= s[i - 1]; for(int i = 0; i <= m * 2; i ++) s[i] *= -1; long sum[] = new long[d + 1]; long x = - divfloor(n * d, 2); for(int i = 0; i < m * 2; i ++) { long r1 = constrain(divceil(r[i] - x, d), 0, n); long r2 = constrain(divceil(r[i] - x - d + 1, d), 0, n); sum[0] += r1 * s[i + 1]; int j = (int)((r[i] - x) % d); if(j < 0) j += d; sum[j + 1] += (r2 - r1) * s[i + 1]; sum[d] -= r2 * s[i + 1]; } for(int i = 0; i < d; i ++) sum[i + 1] += sum[i]; prtln(max(sum)); } } } import java.util.*; import java.io.*; import java.math.*; import java.util.function.*; public class Main implements Runnable { static boolean DEBUG; public static void main(String[] args) { DEBUG = args.length > 0 && args[0].equals("-DEBUG"); Thread.setDefaultUncaughtExceptionHandler((t, e) -> { e.printStackTrace(); System.exit(1); }); new Thread(null, new Main(), "", 1 << 31).start(); } public void run() { Solver solver = new Solver(); solver.solve(); solver.exit(); } static class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int pointer = 0; private int buflen = 0; private boolean hasNextByte() { if(pointer < buflen) return true; else { pointer = 0; try { buflen = in.read(buffer); }catch (IOException e) { e.printStackTrace(); } return buflen > 0; } } private int readByte() { if(hasNextByte()) return buffer[pointer ++]; else return -1; } private boolean isPrintableChar(int c) { return isPrintableChar(c, false); } private boolean isPrintableChar(int c, boolean includingSpace) { return (includingSpace ? 32 : 33) <= c && c <= 126; } private void skipUnprintable() { skipUnprintable(false); } private void skipUnprintable(boolean includingSpace) { while(hasNextByte() && !isPrintableChar(buffer[pointer], includingSpace)) pointer ++; } private boolean hasNext() { return hasNext(false); } private boolean hasNext(boolean includingSpace) { skipUnprintable(includingSpace); return hasNextByte(); } private StringBuilder sb = new StringBuilder(); public String next() { return next(false); } public String next(boolean includingSpace) { if(!hasNext(includingSpace)) throw new NoSuchElementException(); sb.setLength(0); int b = readByte(); while(isPrintableChar(b, includingSpace)) { 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 = n * 10 + b - '0'; else if(b == -1 || !isPrintableChar(b)) return minus ? - n : n; else throw new NumberFormatException(); b = readByte(); } } } static class Solver { final FastScanner sc = new FastScanner(); public Solver() { } final String ns() { return ns(false); } final String ns(boolean includingSpace) { return sc.next(includingSpace); } final String[] ns(int n) { return ns(n, false); } final String[] ns(int n, boolean includingSpace) { String a[] = new String[n]; for(int i = 0; i < n; i ++) a[i] = ns(includingSpace); return a; } final String[][] ns(int n, int m) { return ns(n, m, false); } final String[][] ns(int n, int m, boolean includingSpace) { String a[][] = new String[n][m]; for(int i = 0; i < n; i ++) a[i] = ns(m, includingSpace); return a; } final char nc() { return ns().charAt(0); } final char[] nc(int n) { String str = ns(); if(n < 0) n = str.length(); char a[] = new char[n]; for(int i = 0; i < n; i ++) a[i] = str.charAt(i); return a; } final char[][] nc(int n, int m) { char a[][] = new char[n][m]; for(int i = 0; i < n; i ++) a[i] = nc(m); return a; } final boolean[] nb(int n, char t) { char c[] = nc(-1); if(n < 0) n = c.length; boolean a[] = new boolean[n]; for(int i = 0; i < n; i ++) a[i] = c[i] == t; return a; } final boolean[][] nb(int n, int m, char t) { boolean a[][] = new boolean[n][m]; for(int i = 0; i < n; i ++) a[i] = nb(m, t); return a; } final int ni() { return Math.toIntExact(sc.nextLong()); } final int[] ni(int n) { int a[] = new int[n]; for(int i = 0; i < n; i ++) a[i] = ni(); return a; } final int[][] ni(int n, int m) { int a[][] = new int[n][m]; for(int i = 0; i < n; i ++) a[i] = ni(m); return a; } final long nl() { return sc.nextLong(); } final long[] nl(int n) { long a[] = new long[n]; for(int i = 0; i < n; i ++) a[i] = nl(); return a; } final long[][] nl(int n, int m) { long a[][] = new long[n][m]; for(int i = 0; i < n; i ++) a[i] = nl(m); return a; } final double nd() { return Double.parseDouble(sc.next()); } final double[] nd(int n) { double a[] = new double[n]; for(int i = 0; i < n; i ++) a[i] = nd(); return a; } final double[][] nd(int n, int m) { double a[][] = new double[n][m]; for(int i = 0; i < n; i ++) a[i] = nd(m); return a; } final String booleanToString(boolean b) { return b ? "#" : "."; } final PrintWriter out = new PrintWriter(System.out); final PrintWriter err = new PrintWriter(System.err); final StringBuilder sb4prtln = new StringBuilder(); final void prt() { out.print(""); } final <T> void prt(T a) { out.print(a); } final void prtln() { out.println(""); } final <T> void prtln(T a) { out.println(a); } final void prtln(int... a) { sb4prtln.setLength(0); for(int ele : a) { sb4prtln.append(ele); sb4prtln.append(" "); } sb4prtln.deleteCharAt(sb4prtln.length() - 1); prtln(sb4prtln); } final void prtln(long... a) { sb4prtln.setLength(0); for(long ele : a) { sb4prtln.append(ele); sb4prtln.append(" "); } sb4prtln.deleteCharAt(sb4prtln.length() - 1); prtln(sb4prtln); } final void prtln(double... a) { sb4prtln.setLength(0); for(double ele : a) { sb4prtln.append(ele); sb4prtln.append(" "); } sb4prtln.deleteCharAt(sb4prtln.length() - 1); prtln(sb4prtln); } final void prtln(String... a) { sb4prtln.setLength(0); for(String ele : a) { sb4prtln.append(ele); sb4prtln.append(" "); } sb4prtln.deleteCharAt(sb4prtln.length() - 1); prtln(sb4prtln); } final void prtln(char... a) { sb4prtln.setLength(0); for(char ele : a) sb4prtln.append(ele); prtln(sb4prtln); } final void prtln(boolean... a) { sb4prtln.setLength(0); for(boolean ele : a) sb4prtln.append(booleanToString(ele)); prtln(sb4prtln); } final void prtlns(int... a) { sb4prtln.setLength(0); for(int ele : a) { sb4prtln.append(ele); sb4prtln.append("\n"); } prt(sb4prtln); } final void prtlns(long... a) { sb4prtln.setLength(0); for(long ele : a) { sb4prtln.append(ele); sb4prtln.append("\n"); } prt(sb4prtln); } final void prtlns(double... a) { sb4prtln.setLength(0); for(double ele : a) { sb4prtln.append(ele); sb4prtln.append("\n"); } prt(sb4prtln); } final void prtlns(String... a) { sb4prtln.setLength(0); for(String ele : a) { sb4prtln.append(ele); sb4prtln.append("\n"); } prt(sb4prtln); } final void prtlns(char... a) { sb4prtln.setLength(0); for(char ele : a) { sb4prtln.append(ele); sb4prtln.append("\n"); } prt(sb4prtln); } final void prtlns(boolean... a) { sb4prtln.setLength(0); for(boolean ele : a) { sb4prtln.append(booleanToString(ele)); sb4prtln.append("\n"); } prt(sb4prtln); } final void prtln(int[][] a) { for(int[] ele : a) prtln(ele); } final void prtln(long[][] a) { for(long[] ele : a) prtln(ele); } final void prtln(double[][] a) { for(double[] ele : a) prtln(ele); } final void prtln(String[][] a) { for(String[] ele : a) prtln(ele); } final void prtln(char[][] a) { for(char[] ele : a) prtln(ele); } final void prtln(boolean[][] a) { for(boolean[] ele : a) prtln(ele); } final String errconvert(int a) { return isINF(a) ? "_" : String.valueOf(a); } final String errconvert(long a) { return isINF(a) ? "_" : String.valueOf(a); } final void errprt(int a) { if(DEBUG) err.print(errconvert(a)); } final void errprt(long a) { if(DEBUG) err.print(errconvert(a)); } final void errprt() { if(DEBUG) err.print(""); } final <T> void errprt(T a) { if(DEBUG) err.print(a); } final void errprt(boolean a) { if(DEBUG) errprt(booleanToString(a)); } final void errprtln() { if(DEBUG) err.println(""); } final void errprtln(int a) { if(DEBUG) err.println(errconvert(a)); } final void errprtln(long a) { if(DEBUG) err.println(errconvert(a)); } final <T> void errprtln(T a) { if(DEBUG) err.println(a); } final void errprtln(boolean a) { if(DEBUG) errprtln(booleanToString(a)); } final void errprtln(int... a) { if(DEBUG) { sb4prtln.setLength(0); for(int ele : a) { sb4prtln.append(errconvert(ele)); sb4prtln.append(" "); } errprtln(sb4prtln.toString().trim()); } } final void errprtln(long... a) { if(DEBUG) { sb4prtln.setLength(0); for(long ele : a) { sb4prtln.append(errconvert(ele)); sb4prtln.append(" "); } errprtln(sb4prtln.toString().trim()); } } final void errprtln(double... a) { if(DEBUG) { sb4prtln.setLength(0); for(double ele : a) { sb4prtln.append(ele); sb4prtln.append(" "); } errprtln(sb4prtln.toString().trim()); } } final void errprtln(String... a) { if(DEBUG) { sb4prtln.setLength(0); for(String ele : a) { sb4prtln.append(ele); sb4prtln.append(" "); } errprtln(sb4prtln.toString().trim()); } } final void errprtln(char... a) { if(DEBUG) { sb4prtln.setLength(0); for(char ele : a) sb4prtln.append(ele); errprtln(sb4prtln.toString()); } } final void errprtln(boolean... a) { if(DEBUG) { sb4prtln.setLength(0); for(boolean ele : a) sb4prtln.append(booleanToString(ele)); errprtln(sb4prtln.toString()); } } final void errprtlns(int... a) { if(DEBUG) { sb4prtln.setLength(0); for(int ele : a) { sb4prtln.append(errconvert(ele)); sb4prtln.append("\n"); } errprt(sb4prtln.toString()); } } final void errprtlns(long... a) { if(DEBUG) { sb4prtln.setLength(0); for(long ele : a) { sb4prtln.append(errconvert(ele)); sb4prtln.append("\n"); } errprt(sb4prtln.toString()); } } final void errprtlns(double... a) { if(DEBUG) { sb4prtln.setLength(0); for(double ele : a) { sb4prtln.append(ele); sb4prtln.append("\n"); } errprt(sb4prtln.toString()); } } final void errprtlns(String... a) { if(DEBUG) { sb4prtln.setLength(0); for(String ele : a) { sb4prtln.append(ele); sb4prtln.append("\n"); } errprt(sb4prtln.toString()); } } final void errprtlns(char... a) { if(DEBUG) { sb4prtln.setLength(0); for(char ele : a) { sb4prtln.append(ele); sb4prtln.append("\n"); } errprt(sb4prtln.toString()); } } final void errprtlns(boolean... a) { if(DEBUG) { sb4prtln.setLength(0); for(boolean ele : a) { sb4prtln.append(booleanToString(ele)); sb4prtln.append("\n"); } errprt(sb4prtln.toString()); } } final void errprtln(Object[] a) { if(DEBUG) for(Object ele : a) errprtln(ele); } final void errprtln(int[][] a) { if(DEBUG) for(int[] ele : a) errprtln(ele); } final void errprtln(long[][] a) { if(DEBUG) for(long[] ele : a) errprtln(ele); } final void errprtln(double[][] a) { if(DEBUG) for(double[] ele : a) errprtln(ele); } final void errprtln(String[][] a) { if(DEBUG) for(String[] ele : a) errprtln(ele); } final void errprtln(char[][] a) { if(DEBUG) for(char[] ele : a) errprtln(ele); } final void errprtln(boolean[][] a) { if(DEBUG) for(boolean[] ele : a) errprtln(ele); } final void errprtln(Object[][] a) { if(DEBUG) for(Object ele : a) { errprtln(ele); errprtln(); } } final void reply(boolean b) { prtln(b ? "Yes" : "No"); } final void REPLY(boolean b) { prtln(b ? "YES" : "NO"); } final void flush() { out.flush(); if(DEBUG) err.flush(); } final void assertion(boolean b) { if(!b) { flush(); throw new AssertionError(); } } final <T> void assertion(boolean b, T a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, int... a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, long... a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, double... a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, String... a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, char... a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, boolean... a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, int[][] a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, long[][] a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, double[][] a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, String[][] a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, char[][] a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void assertion(boolean b, boolean[][] a) { if(!b) { errprtln(a); flush(); throw new AssertionError(); } } final void inclusiveRangeCheck(int i, int max) { inclusiveRangeCheck(i, 0, max); } final void inclusiveRangeCheck(int i, int min, int max) { rangeCheck(i, min, max + 1); } final void inclusiveRangeCheck(long i, long max) { inclusiveRangeCheck(i, 0, max); } final void inclusiveRangeCheck(long i, long min, long max) { rangeCheck(i, min, max + 1); } final void rangeCheck(int i, int max) { rangeCheck(i, 0, max); } final void rangeCheck(int i, int min, int max) { if(i < min || i >= max) throw new IndexOutOfBoundsException(String.format("Index %d out of bounds for length %d", i, max)); } final void rangeCheck(long i, long max) { rangeCheck(i, 0, max); } final void rangeCheck(long i, long min, long max) { if(i < min || i >= max) throw new IndexOutOfBoundsException(String.format("Index %d out of bounds for length %d", i, max)); } final void nonNegativeCheck(long x) { nonNegativeCheck(x, "the argument"); } final void nonNegativeCheck(long x, String attribute) { if(x < 0) throw new IllegalArgumentException(String.format("%s %d is negative", attribute, x)); } final void positiveCheck(long x) { positiveCheck(x, "the argument"); } final void positiveCheck(long x, String attribute) { if(x <= 0) throw new IllegalArgumentException(String.format("%s %d is negative", attribute, x)); } final void exit() { flush(); System.exit(0); } final <T> void exit(T a) { prtln(a); exit(); } final void exit(int... a) { prtln(a); exit(); } final void exit(long... a) { prtln(a); exit(); } final void exit(double... a) { prtln(a); exit(); } final void exit(String... a) { prtln(a); exit(); } final void exit(char... a) { prtln(a); exit(); } final void exit(boolean... a) { prtln(a); exit(); } final void exit(int[][] a) { prtln(a); exit(); } final void exit(long[][] a) { prtln(a); exit(); } final void exit(double[][] a) { prtln(a); exit(); } final void exit(String[][] a) { prtln(a); exit(); } final void exit(char[][] a) { prtln(a); exit(); } final void exit(boolean[][] a) { prtln(a); exit(); } final long INF = (long)1e18 + 7; final boolean isPlusINF(long a) { return a > INF / 10; } final boolean isMinusINF(long a) { return isPlusINF(- a); } final boolean isINF(long a) { return isPlusINF(a) || isMinusINF(a); } final int I_INF = (int)1e9 + 7; final boolean isPlusINF(int a) { return a > I_INF / 10; } final boolean isMinusINF(int a) { return isPlusINF(- a); } final boolean isINF(int a) { return isPlusINF(a) || isMinusINF(a); } final int min(int a, int b) { return Math.min(a, b); } final long min(long a, long b) { return Math.min(a, b); } final double min(double a, double b) { return Math.min(a, b); } final <T extends Comparable<T>> T min(T a, T b) { return a.compareTo(b) <= 0 ? a : b; } final int min(int... x) { int min = x[0]; for(int val : x) min = min(min, val); return min; } final long min(long... x) { long min = x[0]; for(long val : x) min = min(min, val); return min; } final double min(double... x) { double min = x[0]; for(double val : x) min = min(min, val); return min; } final int max(int a, int b) { return Math.max(a, b); } final long max(long a, long b) { return Math.max(a, b); } final double max(double a, double b) { return Math.max(a, b); } final <T extends Comparable<T>> T max(T a, T b) { return a.compareTo(b) >= 0 ? a : b; } final int max(int... x) { int max = x[0]; for(int val : x) max = max(max, val); return max; } final long max(long... x) { long max = x[0]; for(long val : x) max = max(max, val); return max; } final double max(double... x) { double max = x[0]; for(double val : x) max = max(max, val); return max; } final <T extends Comparable<T>> T max(T[] x) { T max = x[0]; for(T val : x) max = max(max, val); return max; } final int max(int[][] a) { int max = a[0][0]; for(int[] ele : a) max = max(max, max(ele)); return max; } final long max(long[][] a) { long max = a[0][0]; for(long[] ele : a) max = max(max, max(ele)); return max; } final double max(double[][] a) { double max = a[0][0]; for(double[] ele : a) max = max(max, max(ele)); return max; } final <T extends Comparable<T>> T max(T[][] a) { T max = a[0][0]; for(T[] ele : a) max = max(max, max(ele)); return max; } final long sum(int... a) { long sum = 0; for(int ele : a) sum += ele; return sum; } final long sum(long... a) { long sum = 0; for(long ele : a) sum += ele; return sum; } final double sum(double... a) { double sum = 0; for(double ele : a) sum += ele; return sum; } final long sum(boolean... a) { long sum = 0; for(boolean ele : a) sum += ele ? 1 : 0; return sum; } final long[] sums(int[] a) { long sum[] = new long[a.length + 1]; sum[0] = 0; for(int i = 0; i < a.length; i ++) sum[i + 1] = sum[i] + a[i]; return sum; } final long[] sums(long[] a) { long sum[] = new long[a.length + 1]; sum[0] = 0; for(int i = 0; i < a.length; i ++) sum[i + 1] = sum[i] + a[i]; return sum; } final double[] sums(double[] a) { double sum[] = new double[a.length + 1]; sum[0] = 0; for(int i = 0; i < a.length; i ++) sum[i + 1] = sum[i] + a[i]; return sum; } final long[] sums(boolean[] a) { long sum[] = new long[a.length + 1]; sum[0] = 0; for(int i = 0; i < a.length; i ++) sum[i + 1] = sum[i] + (a[i] ? 1 : 0); return sum; } final long[][] sums(int[][] a) { long sum[][] = new long[a.length + 1][a[0].length + 1]; for(int i = 0; i < a.length; i ++) { for(int j = 0; j < a[i].length; j ++) sum[i + 1][j + 1] = sum[i + 1][j] + sum[i][j + 1] - sum[i][j] + a[i][j]; } return sum; } final long[][] sums(long[][] a) { long sum[][] = new long[a.length + 1][a[0].length + 1]; for(int i = 0; i < a.length; i ++) { for(int j = 0; j < a[i].length; j ++) sum[i + 1][j + 1] = sum[i + 1][j] + sum[i][j + 1] - sum[i][j] + a[i][j]; } return sum; } final double[][] sums(double[][] a) { double sum[][] = new double[a.length + 1][a[0].length + 1]; for(int i = 0; i < a.length; i ++) { for(int j = 0; j < a[i].length; j ++) sum[i + 1][j + 1] = sum[i + 1][j] + sum[i][j + 1] - sum[i][j] + a[i][j]; } return sum; } final long[][] sums(boolean[][] a) { long sum[][] = new long[a.length + 1][a[0].length + 1]; for(int i = 0; i < a.length; i ++) { for(int j = 0; j < a[i].length; j ++) sum[i + 1][j + 1] = sum[i + 1][j] + sum[i][j + 1] - sum[i][j] + (a[i][j] ? 1 : 0); } return sum; } final int constrain(int x, int l, int r) { return min(max(x, min(l, r)), max(l, r)); } final long constrain(long x, long l, long r) { return min(max(x, min(l, r)), max(l, r)); } final double constrain(double x, double l, double r) { return min(max(x, min(l, r)), max(l, r)); } final int abs(int x) { return x >= 0 ? x : - x; } final long abs(long x) { return x >= 0 ? x : - x; } final double abs(double x) { return x >= 0 ? x : - x; } final int signum(int x) { return x > 0 ? 1 : x < 0 ? -1 : 0; } final int signum(long x) { return x > 0 ? 1 : x < 0 ? -1 : 0; } final int signum(double x) { return x > 0 ? 1 : x < 0 ? -1 : 0; } final long round(double x) { return Math.round(x); } final long floor(double x) { return round(Math.floor(x)); } final int divfloor(int a, int b) { return signum(a) == signum(b) ? a / b : - divceil(abs(a), abs(b)); } final long divfloor(long a, long b) { return signum(a) == signum(b) ? a / b : - divceil(abs(a), abs(b)); } final long ceil(double x) { return round(Math.ceil(x)); } final int divceil(int a, int b) { return a >= 0 && b > 0 ? (a + b - 1) / b : a < 0 && b < 0 ? divceil(abs(a), abs(b)) : - divfloor(abs(a), abs(b)); } final long divceil(long a, long b) { return a >= 0 && b > 0 ? (a + b - 1) / b : a < 0 && b < 0 ? divceil(abs(a), abs(b)) : - divfloor(abs(a), abs(b)); } final boolean mulGreater(long a, long b, long c) { return b == 0 ? c < 0 : b < 0 ? mulLess(a, - b, - c) : a > divfloor(c, b); } // a * b > c final boolean mulGreaterEquals(long a, long b, long c) { return b == 0 ? c <= 0 : b < 0 ? mulLessEquals(a, - b, - c) : a >= divceil(c, b); } // a * b >= c final boolean mulLess(long a, long b, long c) { return !mulGreaterEquals(a, b, c); } // a * b < c final boolean mulLessEquals(long a, long b, long c) { return !mulGreater(a, b, c); } // a * b <= c final double sqrt(int x) { return Math.sqrt((double)x); } final double sqrt(long x) { return Math.sqrt((double)x); } final double sqrt(double x) { return Math.sqrt(x); } final int floorsqrt(int x) { int s = (int)floor(sqrt(x)) + 1; while(s * s > x) s --; return s; } final long floorsqrt(long x) { long s = floor(sqrt(x)) + 1; while(s * s > x) s --; return s; } final int ceilsqrt(int x) { int s = (int)ceil(sqrt(x)); while(s * s >= x) s --; s ++; return s; } final long ceilsqrt(long x) { long s = ceil(sqrt(x)); while(s * s >= x) s --; s ++; return s; } final long fact(int n) { long ans = 1; for(int i = 1; i <= n; i ++) ans = Math.multiplyExact(ans, i); return ans; } final long naiveP(long n, long r) { long ans = 1; for(int i = 0; i < r; i ++) ans = Math.multiplyExact(ans, n - i); return ans; } final long naiveC(long n, long r) { long ans = 1; for(int i = 0; i < r; i ++) { ans = Math.multiplyExact(ans, n - i); ans /= (i + 1); } return ans; } final double pow(double x, double y) { return Math.pow(x, y); } final long pow(long x, long y) { long ans = 1; while(true) { if((y & 1) != 0) ans = Math.multiplyExact(ans, x); y >>= 1; if(y <= 0) return ans; x = Math.multiplyExact(x, x); } } final double pow(double x, long y) { double ans = 1; while(true) { if((y & 1) != 0) ans *= x; y >>= 1; if(y <= 0) return ans; x *= x; } } final int gcd(int a, int b) { while(true) { if(b == 0) return a; int tmp = a; a = b; b = tmp % b; } } final long gcd(long a, long b) { while(true) { if(b == 0) return a; long tmp = a; a = b; b = tmp % b; } } final long lcm(long a, long b) { return a / gcd(a, b) * b; } final int gcd(int... a) { int gcd = 0; for(int i = 0; i < a.length; i ++) gcd = gcd(gcd, a[i]); return gcd; } final long gcd(long... a) { long gcd = 0; for(int i = 0; i < a.length; i ++) gcd = gcd(gcd, a[i]); return gcd; } final double random() { return Math.random(); } final int random(int max) { return (int)floor(random() * max); } final long random(long max) { return floor(random() * max); } final double random(double max) { return random() * max; } final int random(int min, int max) { return random(max - min) + min; } final long random(long min, long max) { return random(max - min) + min; } final double random(double min, double max) { return random(max - min) + min; } final boolean isUpper(char a) { return a >= 'A' && a <= 'Z'; } final boolean isLower(char a) { return a >= 'a' && a <= 'z'; } final int upperToInt(char a) { return a - 'A'; } final int lowerToInt(char a) { return a - 'a'; } final int numToInt(char a) { return a - '0'; } final int charToInt(char a) { return isLower(a) ? lowerToInt(a) : isUpper(a) ? upperToInt(a) : numToInt(a); } final int alphabetToInt(char a) { return isLower(a) ? lowerToInt(a) : isUpper(a) ? upperToInt(a) + 26 : 52; } final char intToUpper(int a) { return (char)(a + 'A'); } final char intToLower(int a) { return (char)(a + 'a'); } final char intToNum(int a) { return (char)(a + '0'); } final int[] charToInt(char[] a) { int array[] = new int[a.length]; for(int i = 0; i < a.length; i ++) array[i] = charToInt(a[i]); return array; } final long[] div(long a) { nonNegativeCheck(a); List<Long> divList = new ArrayList<>(); for(long i = 1; i * i <= a; i ++) if(a % i == 0) { divList.add(i); if(i * i != a) divList.add(a / i); } long div[] = new long[divList.size()]; for(int i = 0; i < divList.size(); i ++) div[i] = divList.get(i); Arrays.sort(div); return div; } final PairLL[] factor(long a) { nonNegativeCheck(a); List<PairLL> factorList = new ArrayList<>(); for(long i = 2; i * i <= a; i ++) { if(a % i == 0) { long cnt = 0; while(a % i == 0) { a /= i; cnt ++; } factorList.add(new PairLL(i, cnt)); } } if(a > 1) factorList.add(new PairLL(a, 1)); PairLL factor[] = new PairLL[factorList.size()]; for(int i = 0; i < factorList.size(); i ++) factor[i] = factorList.get(i); Arrays.sort(factor); return factor; } final boolean isPrime(long x) { boolean ok = x > 1; for(long i = 2; i * i <= x; i ++) { ok &= x % i != 0; if(!ok) return ok; } return ok; } final boolean[] prime(int num) { nonNegativeCheck(num); boolean prime[] = new boolean[num]; fill(prime, true); if(num > 0) prime[0] = false; if(num > 1) prime[1] = false; for(int i = 2; i < num; i ++) if(prime[i]) for(int j = 2; i * j < num; j ++) prime[i * j] = false; return prime; } final PairIL[] countElements(int[] a, boolean sort) { int len = a.length; int array[] = new int[len]; for(int i = 0; i < len; i ++) array[i] = a[i]; if(sort) Arrays.sort(array); List<PairIL> cntsList = new ArrayList<>(); long tmp = 1; for(int i = 1; i <= len; i ++) { if(i == len || array[i] != array[i - 1]) { cntsList.add(new PairIL(array[i - 1], tmp)); tmp = 1; }else tmp ++; } PairIL cnts[] = new PairIL[cntsList.size()]; for(int i = 0; i < cntsList.size(); i ++) cnts[i] = cntsList.get(i); return cnts; } final PairLL[] countElements(long[] a, boolean sort) { int len = a.length; long array[] = new long[len]; for(int i = 0; i < len; i ++) array[i] = a[i]; if(sort) Arrays.sort(array); List<PairLL> cntsList = new ArrayList<>(); long tmp = 1; for(int i = 1; i <= len; i ++) { if(i == len || array[i] != array[i - 1]) { cntsList.add(new PairLL(array[i - 1], tmp)); tmp = 1; }else tmp ++; } PairLL cnts[] = new PairLL[cntsList.size()]; for(int i = 0; i < cntsList.size(); i ++) cnts[i] = cntsList.get(i); return cnts; } final PairIL[] countElements(String s, boolean sort) { int len = s.length(); char array[] = s.toCharArray(); if(sort) Arrays.sort(array); List<PairIL> cntsList = new ArrayList<>(); long tmp = 1; for(int i = 1; i <= len; i ++) { if(i == len || array[i] != array[i - 1]) { cntsList.add(new PairIL((int)array[i - 1], tmp)); tmp = 1; }else tmp ++; } PairIL cnts[] = new PairIL[cntsList.size()]; for(int i = 0; i < cntsList.size(); i ++) cnts[i] = cntsList.get(i); return cnts; } long triangular(long n) { return n * (n + 1) / 2; } long arctriangularfloor(long m) { long n = (floor(sqrt(m * 8 + 1)) - 1) / 2 + 1; while(triangular(n) > m) n --; return n; } long arctriangularceil(long m) { long n = max(0, (ceil(sqrt(m * 8 + 1)) + 1) / 2 - 1); while(triangular(n) < m) n ++; return n; } final int[] baseConvert(long x, int n, int len) { nonNegativeCheck(x); nonNegativeCheck(n); nonNegativeCheck(len); int digit[] = new int[len]; int i = 0; long tmp = x; while(tmp > 0 && i < len) { digit[i ++] = (int)(tmp % n); tmp /= n; } return digit; } final int[] baseConvert(long x, int n) { nonNegativeCheck(x); nonNegativeCheck(n); long tmp = x; int len = 0; while(tmp > 0) { tmp /= n; len ++; } return baseConvert(x, n, len); } final int[] baseConvert(int x, int n, int len) { nonNegativeCheck(x); nonNegativeCheck(n); nonNegativeCheck(len); int digit[] = new int[len]; int i = 0; int tmp = x; while(tmp > 0 && i < len) { digit[i ++] = (int)(tmp % n); tmp /= n; } return digit; } final int[] baseConvert(int x, int n) { nonNegativeCheck(x); nonNegativeCheck(n); int tmp = x; int len = 0; while(tmp > 0) { tmp /= n; len ++; } return baseConvert(x, n, len); } final long[] baseConvert(long x, long n, int len) { nonNegativeCheck(x); nonNegativeCheck(n); nonNegativeCheck(len); long digit[] = new long[len]; int i = 0; long tmp = x; while(tmp > 0 && i < len) { digit[i ++] = tmp % n; tmp /= n; } return digit; } final long[] baseConvert(long x, long n) { nonNegativeCheck(x); nonNegativeCheck(n); long tmp = x; int len = 0; while(tmp > 0) { tmp /= n; len ++; } return baseConvert(x, n, len); } final int numDigits(long a) { nonNegativeCheck(a); return Long.toString(a).length(); } final long bitFlag(int a) { nonNegativeCheck(a); return 1L << (long)a; } final boolean isFlagged(long x, int a) { nonNegativeCheck(x); nonNegativeCheck(a); return (x & bitFlag(a)) != 0; } final long countString(String s, String a) { return (s.length() - s.replace(a, "").length()) / a.length(); } final long countStringAll(String s, String a) { return s.length() - s.replaceAll(a, "").length(); } final String reverse(String s) { return (new StringBuilder(s)).reverse().toString(); } final String[] reverse(String[] a) { for(int i = 0; i < a.length / 2; i ++) swap(a, i, a.length - i - 1); return a; } final int[] reverse(int[] a) { for(int i = 0; i < a.length / 2; i ++) swap(a, i, a.length - i - 1); return a; } final long[] reverse(long[] a) { for(int i = 0; i < a.length / 2; i ++) swap(a, i, a.length - i - 1); return a; } final double[] reverse(double[] a) { for(int i = 0; i < a.length / 2; i ++) swap(a, i, a.length - i - 1); return a; } final char[] reverse(char[] a) { for(int i = 0; i < a.length / 2; i ++) swap(a, i, a.length - i - 1); return a; } final boolean[] reverse(boolean[] a) { for(int i = 0; i < a.length / 2; i ++) swap(a, i, a.length - i - 1); return a; } final <T> T[] reverse(T[] a) { for(int i = 0; i < a.length / 2; i ++) swap(a, i, a.length - i - 1); return a; } final void fill(int[] a, int x) { Arrays.fill(a, x); } final void fill(long[] a, long x) { Arrays.fill(a, x); } final void fill(double[] a, double x) { Arrays.fill(a, x); } final void fill(char[] a, char x) { Arrays.fill(a, x); } final void fill(boolean[] a, boolean x) { Arrays.fill(a, x); } final void fill(int[][] a, int x) { for(int[] ele : a) fill(ele, x); } final void fill(long[][] a, long x) { for(long[] ele : a) fill(ele, x); } final void fill(double[][] a, double x) { for(double[] ele : a) fill(ele, x); } final void fill(char[][] a, char x) { for(char[] ele : a) fill(ele, x); } final void fill(boolean[][] a, boolean x) { for(boolean[] ele : a) fill(ele, x); } final void fill(int[][][] a, int x) { for(int[][] ele : a) fill(ele, x); } final void fill(long[][][] a, long x) { for(long[][] ele : a) fill(ele, x); } final void fill(double[][][] a, double x) { for(double[][] ele : a) fill(ele, x); } final void fill(char[][][] a, char x) { for(char[][] ele : a) fill(ele, x); } final void fill(boolean[][][] a, boolean x) { for(boolean[][] ele : a) fill(ele, x); } final int[] resize(int[] a, int m, int x) { nonNegativeCheck(m); int resized[] = new int[m]; for(int i = max(0, - x); i < a.length && i + x < m; i ++) resized[i + x] = a[i]; return resized; } final long[] resize(long[] a, int m, int x) { nonNegativeCheck(m); long resized[] = new long[m]; for(int i = max(0, - x); i < a.length && i + x < m; i ++) resized[i + x] = a[i]; return resized; } final double[] resize(double[] a, int m, int x) { nonNegativeCheck(m); double resized[] = new double[m]; for(int i = max(0, - x); i < a.length && i + x < m; i ++) resized[i + x] = a[i]; return resized; } final char[] resize(char[] a, int m, int x) { nonNegativeCheck(m); char resized[] = new char[m]; for(int i = max(0, - x); i < a.length && i + x < m; i ++) resized[i + x] = a[i]; return resized; } final boolean[] resize(boolean[] a, int m, int x) { nonNegativeCheck(m); boolean resized[] = new boolean[m]; for(int i = max(0, - x); i < a.length && i + x < m; i ++) resized[i + x] = a[i]; return resized; } final Object[] resize(Object[] a, int m, int x) { nonNegativeCheck(m); Object resized[] = new Object[m]; for(int i = max(0, - x); i < a.length && i + x < m; i ++) resized[i + x] = a[i]; return resized; } final int[] toIntArray(List<Integer> list) { int a[] = new int[list.size()]; int idx = 0; for(int ele : list) a[idx ++] = ele; return a; } final long[] toLongArray(List<Long> list) { long a[] = new long[list.size()]; int idx = 0; for(long ele : list) a[idx ++] = ele; return a; } final double[] toDoubleArray(List<Double> list) { double a[] = new double[list.size()]; int idx = 0; for(double ele : list) a[idx ++] = ele; return a; } final char[] toCharArray(List<Character> list) { char a[] = new char[list.size()]; int idx = 0; for(char ele : list) a[idx ++] = ele; return a; } final boolean[] toBooleanArray(List<Boolean> list) { boolean a[] = new boolean[list.size()]; int idx = 0; for(boolean ele : list) a[idx ++] = ele; return a; } final String[] toStringArray(List<String> list) { String a[] = new String[list.size()]; int idx = 0; for(String ele : list) a[idx ++] = ele; return a; } final <T> void toArray(List<T> list, T a[]) { int idx = 0; for(T ele : list) a[idx ++] = ele; } final void shuffleArray(int[] a) { for(int i = 0; i < a.length; i ++){ int tmp = a[i]; int idx = random(i, a.length); a[i] = a[idx]; a[idx] = tmp; } } final void shuffleArray(long[] a) { for(int i = 0; i < a.length; i ++){ long tmp = a[i]; int idx = random(i, a.length); a[i] = a[idx]; a[idx] = tmp; } } final void shuffleArray(double[] a) { for(int i = 0; i < a.length; i ++){ double tmp = a[i]; int idx = random(i, a.length); a[i] = a[idx]; a[idx] = tmp; } } final int[] randomi(int n, int max) { nonNegativeCheck(n); int a[] = new int[n]; for(int i = 0; i < n; i ++) a[i] = random(max); return a; } final long[] randoml(int n, long max) { nonNegativeCheck(n); long a[] = new long[n]; for(int i = 0; i < n; i ++) a[i] = random(max); return a; } final double[] randomd(int n, double max) { nonNegativeCheck(n); double a[] = new double[n]; for(int i = 0; i < n; i ++) a[i] = random(max); return a; } final int[] randomi(int n, int min, int max) { nonNegativeCheck(n); int a[] = new int[n]; for(int i = 0; i < n; i ++) a[i] = random(min, max); return a; } final long[] randoml(int n, long min, long max) { nonNegativeCheck(n); long a[] = new long[n]; for(int i = 0; i < n; i ++) a[i] = random(min, max); return a; } final double[] randomd(int n, double min, double max) { nonNegativeCheck(n); double a[] = new double[n]; for(int i = 0; i < n; i ++) a[i] = random(min, max); return a; } final void swap(String[] a, int i, int j) { rangeCheck(i, a.length); rangeCheck(j, a.length); String tmp = a[i]; a[i] = a[j]; a[j] = tmp; } final void swap(int[] a, int i, int j) { rangeCheck(i, a.length); rangeCheck(j, a.length); int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } final void swap(long[] a, int i, int j) { rangeCheck(i, a.length); rangeCheck(j, a.length); long tmp = a[i]; a[i] = a[j]; a[j] = tmp; } final void swap(double[] a, int i, int j) { rangeCheck(i, a.length); rangeCheck(j, a.length); double tmp = a[i]; a[i] = a[j]; a[j] = tmp; } final void swap(char[] a, int i, int j) { rangeCheck(i, a.length); rangeCheck(j, a.length); char tmp = a[i]; a[i] = a[j]; a[j] = tmp; } final void swap(boolean[] a, int i, int j) { rangeCheck(i, a.length); rangeCheck(j, a.length); boolean tmp = a[i]; a[i] = a[j]; a[j] = tmp; } final <T> void swap(T[] a, int i, int j) { rangeCheck(i, a.length); rangeCheck(j, a.length); T tmp = a[i]; a[i] = a[j]; a[j] = tmp; } final int[][] rotate(int[][] a) { int[][] ans = new int[a[0].length][a.length]; for(int i = 0; i < a.length; i ++) for(int j = 0; j < a[i].length; j ++) ans[j][a.length - i - 1] = a[i][j]; return ans; } final long[][] rotate(long[][] a) { long[][] ans = new long[a[0].length][a.length]; for(int i = 0; i < a.length; i ++) for(int j = 0; j < a[i].length; j ++) ans[j][a.length - i - 1] = a[i][j]; return ans; } final double[][] rotate(double[][] a) { double[][] ans = new double[a[0].length][a.length]; for(int i = 0; i < a.length; i ++) for(int j = 0; j < a[i].length; j ++) ans[j][a.length - i - 1] = a[i][j]; return ans; } final char[][] rotate(char[][] a) { char[][] ans = new char[a[0].length][a.length]; for(int i = 0; i < a.length; i ++) for(int j = 0; j < a[i].length; j ++) ans[j][a.length - i - 1] = a[i][j]; return ans; } final boolean[][] rotate(boolean[][] a) { boolean[][] ans = new boolean[a[0].length][a.length]; for(int i = 0; i < a.length; i ++) for(int j = 0; j < a[i].length; j ++) ans[j][a.length - i - 1] = a[i][j]; return ans; } final Object[][] rotate(Object[][] a) { Object[][] ans = new Object[a[0].length][a.length]; for(int i = 0; i < a.length; i ++) for(int j = 0; j < a[i].length; j ++) ans[j][a.length - i - 1] = a[i][j]; return ans; } final int[] compress(int[] a) { int n = a.length; Set<Integer> ts = new TreeSet<>(); for(int i = 0; i < n; i ++) ts.add(a[i]); int compressed[] = new int[ts.size()]; int j = 0; for(int x : ts) compressed[j ++] = x; for(int i = 0; i < n; i ++) a[i] = lowerBound(compressed, a[i]); return compressed; } final long[] compress(long[] a) { int n = a.length; Set<Long> ts = new TreeSet<>(); for(int i = 0; i < n; i ++) ts.add(a[i]); long compressed[] = new long[ts.size()]; int j = 0; for(long x : ts) compressed[j ++] = x; for(int i = 0; i < n; i ++) a[i] = lowerBound(compressed, a[i]); return compressed; } final double[] compress(double[] a) { int n = a.length; Set<Double> ts = new TreeSet<>(); for(int i = 0; i < n; i ++) ts.add(a[i]); double compressed[] = new double[ts.size()]; int j = 0; for(double x : ts) compressed[j ++] = x; for(int i = 0; i < n; i ++) a[i] = lowerBound(compressed, a[i]); return compressed; } final int lowerBound(int[] a, int key) { return BS(a, key, true, true, true); } final int lowerBound(int[] a, int key, int ng, int ok) { return BS(a, key, true, true, true, ng, ok); } final int upperBound(int[] a, int key) { return BS(a, key, true, true, false); } final int upperBound(int[] a, int key, int ng, int ok) { return BS(a, key, true, true, false, ng, ok); } final int cntBS(int[] a, int key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, true); } final int cntBS(int[] a, int key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, true, ng, ok); } final int BS(int[] a, int key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, false); } final int BS(int[] a, int key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, false, ng, ok); } final int BS(int[] a, int key, boolean asc, boolean gt, boolean eq, boolean cnt) { return BS(a, key, asc, gt, eq, cnt, asc ^ gt ? a.length : -1, asc ^ gt ? -1 : a.length); } final int BS(int[] a, int key, boolean asc, boolean gt, boolean eq, boolean cnt, int ng, int ok) { int index = binarySearch(a, key, gt, eq, ng, ok); return cnt ? (int)abs(ok - index) : index; } final int binarySearch(int[] a, int key, boolean gt, boolean eq, int ng, int ok) { while (abs(ok - ng) > 1) { int mid = (ok + ng) / 2; if(isOKforBS(a, mid, key, gt, eq)) ok = mid; else ng = mid; } return ok; } final boolean isOKforBS(int[] a, int index, int key, boolean gt, boolean eq) { return (a[index] > key && gt) || (a[index] < key && !gt) || (a[index] == key && eq); } final int lowerBound(long[] a, long key) { return BS(a, key, true, true, true); } final int lowerBound(long[] a, long key, int ng, int ok) { return BS(a, key, true, true, true, ng, ok); } final int upperBound(long[] a, long key) { return BS(a, key, true, true, false); } final int upperBound(long[] a, long key, int ng, int ok) { return BS(a, key, true, true, false, ng, ok); } final int cntBS(long[] a, long key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, true); } final int cntBS(long[] a, long key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, true, ng, ok); } final int BS(long[] a, long key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, false); } final int BS(long[] a, long key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, false, ng, ok); } final int BS(long[] a, long key, boolean asc, boolean gt, boolean eq, boolean cnt) { return BS(a, key, asc, gt, eq, cnt, asc ^ gt ? a.length : -1, asc ^ gt ? -1 : a.length); } final int BS(long[] a, long key, boolean asc, boolean gt, boolean eq, boolean cnt, int ng, int ok) { int index = binarySearch(a, key, gt, eq, ng, ok); return cnt ? (int)abs(ok - index) : index; } final int binarySearch(long[] a, long key, boolean gt, boolean eq, int ng, int ok) { while (abs(ok - ng) > 1) { int mid = (ok + ng) / 2; if(isOKforBS(a, mid, key, gt, eq)) ok = mid; else ng = mid; } return ok; } final boolean isOKforBS(long[] a, int index, long key, boolean gt, boolean eq) { return (a[index] > key && gt) || (a[index] < key && !gt) || (a[index] == key && eq); } final int lowerBound(double[] a, double key) { return BS(a, key, true, true, true); } final int lowerBound(double[] a, double key, int ng, int ok) { return BS(a, key, true, true, true, ng, ok); } final int upperBound(double[] a, double key) { return BS(a, key, true, true, false); } final int upperBound(double[] a, double key, int ng, int ok) { return BS(a, key, true, true, false, ng, ok); } final int cntBS(double[] a, double key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, true); } final int cntBS(double[] a, double key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, true, ng, ok); } final int BS(double[] a, double key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, false); } final int BS(double[] a, double key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, false, ng, ok); } final int BS(double[] a, double key, boolean asc, boolean gt, boolean eq, boolean cnt) { return BS(a, key, asc, gt, eq, cnt, asc ^ gt ? a.length : -1, asc ^ gt ? -1 : a.length); } final int BS(double[] a, double key, boolean asc, boolean gt, boolean eq, boolean cnt, int ng, int ok) { int index = binarySearch(a, key, gt, eq, ng, ok); return cnt ? (int)abs(ok - index) : index; } final int binarySearch(double[] a, double key, boolean gt, boolean eq, int ng, int ok) { while (abs(ok - ng) > 1) { int mid = (ok + ng) / 2; if(isOKforBS(a, mid, key, gt, eq)) ok = mid; else ng = mid; } return ok; } final boolean isOKforBS(double[] a, int index, double key, boolean gt, boolean eq) { return (a[index] > key && gt) || (a[index] < key && !gt) || (a[index] == key && eq); } final <T extends Comparable<? super T>> int lowerBound(T[] a, T key) { return BS(a, key, true, true, true); } final <T extends Comparable<? super T>> int lowerBound(T[] a, T key, int ng, int ok) { return BS(a, key, true, true, true, ng, ok); } final <T extends Comparable<? super T>> int upperBound(T[] a, T key) { return BS(a, key, true, true, false); } final <T extends Comparable<? super T>> int upperBound(T[] a, T key, int ng, int ok) { return BS(a, key, true, true, false, ng, ok); } final <T extends Comparable<? super T>> int cntBS(T[] a, T key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, true); } final <T extends Comparable<? super T>> int cntBS(T[] a, T key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, true, ng, ok); } final <T extends Comparable<? super T>> int BS(T[] a, T key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, false); } final <T extends Comparable<? super T>> int BS(T[] a, T key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, false, ng, ok); } final <T extends Comparable<? super T>> int BS(T[] a, T key, boolean asc, boolean gt, boolean eq, boolean cnt) { return BS(a, key, asc, gt, eq, cnt, asc ^ gt ? a.length : -1, asc ^ gt ? -1 : a.length); } final <T extends Comparable<? super T>> int BS(T[] a, T key, boolean asc, boolean gt, boolean eq, boolean cnt, int ng, int ok) { int index = binarySearch(a, key, gt, eq, ng, ok); return cnt ? (int)abs(ok - index) : index; } final <T extends Comparable<? super T>> int binarySearch(T[] a, T key, boolean gt, boolean eq, int ng, int ok) { while (abs(ok - ng) > 1) { int mid = (ok + ng) / 2; if(isOKforBS(a, mid, key, gt, eq)) ok = mid; else ng = mid; } return ok; } final <T extends Comparable<? super T>> boolean isOKforBS(T[] a, int index, T key, boolean gt, boolean eq) { int compare = a[index].compareTo(key); return (compare > 0 && gt) || (compare < 0 && !gt) || (compare == 0 && eq); } final <T> int lowerBound(T[] a, T key, Comparator<? super T> c) { return BS(a, key, true, true, true, c); } final <T> int lowerBound(T[] a, T key, int ng, int ok, Comparator<? super T> c) { return BS(a, key, true, true, true, ng, ok, c); } final <T> int upperBound(T[] a, T key, Comparator<? super T> c) { return BS(a, key, true, true, false, c); } final <T> int upperBound(T[] a, T key, int ng, int ok, Comparator<? super T> c) { return BS(a, key, true, true, false, ng, ok, c); } final <T> int cntBS(T[] a, T key, boolean asc, boolean gt, boolean eq, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, true, c); } final <T> int cntBS(T[] a, T key, boolean asc, boolean gt, boolean eq, int ng, int ok, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, true, ng, ok, c); } final <T> int BS(T[] a, T key, boolean asc, boolean gt, boolean eq, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, false, c); } final <T> int BS(T[] a, T key, boolean asc, boolean gt, boolean eq, int ng, int ok, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, false, ng, ok, c); } final <T> int BS(T[] a, T key, boolean asc, boolean gt, boolean eq, boolean cnt, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, cnt, asc ^ gt ? a.length : -1, asc ^ gt ? -1 : a.length, c); } final <T> int BS(T[] a, T key, boolean asc, boolean gt, boolean eq, boolean cnt, int ng, int ok, Comparator<? super T> c) { int index = binarySearch(a, key, gt, eq, ng, ok, c); return cnt ? (int)abs(ok - index) : index; } final <T> int binarySearch(T[] a, T key, boolean gt, boolean eq, int ng, int ok, Comparator<? super T> c) { while (abs(ok - ng) > 1) { int mid = (ok + ng) / 2; if(isOKforBS(a, mid, key, gt, eq, c)) ok = mid; else ng = mid; } return ok; } final <T> boolean isOKforBS(T[] a, int index, T key, boolean gt, boolean eq, Comparator<? super T> c) { int compare = c.compare(a[index], key); return (compare > 0 && gt) || (compare < 0 && !gt) || (compare == 0 && eq); } final <T extends Comparable<? super T>> int lowerBound(List<T> a, T key) { return BS(a, key, true, true, true); } final <T extends Comparable<? super T>> int lowerBound(List<T> a, T key, int ng, int ok) { return BS(a, key, true, true, true, ng, ok); } final <T extends Comparable<? super T>> int upperBound(List<T> a, T key) { return BS(a, key, true, true, false); } final <T extends Comparable<? super T>> int upperBound(List<T> a, T key, int ng, int ok) { return BS(a, key, true, true, false, ng, ok); } final <T extends Comparable<? super T>> int cntBS(List<T> a, T key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, true); } final <T extends Comparable<? super T>> int cntBS(List<T> a, T key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, true, ng, ok); } final <T extends Comparable<? super T>> int BS(List<T> a, T key, boolean asc, boolean gt, boolean eq) { return BS(a, key, asc, gt, eq, false); } final <T extends Comparable<? super T>> int BS(List<T> a, T key, boolean asc, boolean gt, boolean eq, int ng, int ok) { return BS(a, key, asc, gt, eq, false, ng, ok); } final <T extends Comparable<? super T>> int BS(List<T> a, T key, boolean asc, boolean gt, boolean eq, boolean cnt) { return BS(a, key, asc, gt, eq, cnt, asc ^ gt ? a.size() : -1, asc ^ gt ? -1 : a.size()); } final <T extends Comparable<? super T>> int BS(List<T> a, T key, boolean asc, boolean gt, boolean eq, boolean cnt, int ng, int ok) { int index = binarySearch(a, key, gt, eq, ng, ok); return cnt ? (int)abs(ok - index) : index; } final <T extends Comparable<? super T>> int binarySearch(List<T> a, T key, boolean gt, boolean eq, int ng, int ok) { while (abs(ok - ng) > 1) { int mid = (ok + ng) / 2; if(isOKforBS(a, mid, key, gt, eq)) ok = mid; else ng = mid; } return ok; } final <T extends Comparable<? super T>> boolean isOKforBS(List<T> a, int index, T key, boolean gt, boolean eq) { int compare = a.get(index).compareTo(key); return (compare > 0 && gt) || (compare < 0 && !gt) || (compare == 0 && eq); } final <T> int lowerBound(List<T> a, T key, Comparator<? super T> c) { return BS(a, key, true, true, true, c); } final <T> int lowerBound(List<T> a, T key, int ng, int ok, Comparator<? super T> c) { return BS(a, key, true, true, true, ng, ok, c); } final <T> int upperBound(List<T> a, T key, Comparator<? super T> c) { return BS(a, key, true, true, false, c); } final <T> int upperBound(List<T> a, T key, int ng, int ok, Comparator<? super T> c) { return BS(a, key, true, true, false, ng, ok, c); } final <T> int cntBS(List<T> a, T key, boolean asc, boolean gt, boolean eq, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, true, c); } final <T> int cntBS(List<T> a, T key, boolean asc, boolean gt, boolean eq, int ng, int ok, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, true, ng, ok, c); } final <T> int BS(List<T> a, T key, boolean asc, boolean gt, boolean eq, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, false, c); } final <T> int BS(List<T> a, T key, boolean asc, boolean gt, boolean eq, int ng, int ok, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, false, ng, ok, c); } final <T> int BS(List<T> a, T key, boolean asc, boolean gt, boolean eq, boolean cnt, Comparator<? super T> c) { return BS(a, key, asc, gt, eq, cnt, asc ^ gt ? a.size() : -1, asc ^ gt ? -1 : a.size(), c); } final <T> int BS(List<T> a, T key, boolean asc, boolean gt, boolean eq, boolean cnt, int ng, int ok, Comparator<? super T> c) { int index = binarySearch(a, key, gt, eq, ng, ok, c); return cnt ? (int)abs(ok - index) : index; } final <T> int binarySearch(List<T> a, T key, boolean gt, boolean eq, int ng, int ok, Comparator<? super T> c) { while (abs(ok - ng) > 1) { int mid = (ok + ng) / 2; if(isOKforBS(a, mid, key, gt, eq, c)) ok = mid; else ng = mid; } return ok; } final <T> boolean isOKforBS(List<T> a, int index, T key, boolean gt, boolean eq, Comparator<? super T> c) { int compare = c.compare(a.get(index), key); return (compare > 0 && gt) || (compare < 0 && !gt) || (compare == 0 && eq); } final PairLL binaryRangeSearch(long left, long right, UnaryOperator<Long> op, boolean minimize) { long ok1 = right, ng1 = left; while(abs(ok1 - ng1) > 1) { long mid = (ok1 + ng1) / 2; boolean isOK = (op.apply(mid + 1) - op.apply(mid)) * (minimize ? 1 : -1) >= 0; if(isOK) ok1 = mid; else ng1 = mid; } long ok2 = left, ng2 = right; while(abs(ok2 - ng2) > 1) { long mid = (ok2 + ng2) / 2; boolean isOK = (op.apply(mid - 1) - op.apply(mid)) * (minimize ? 1 : -1) >= 0; if(isOK) ok2 = mid; else ng2 = mid; } return new PairLL(ok1, ok2); //[l, r] } final double ternarySearch(double left, double right, UnaryOperator<Double> op, boolean minimize, int loop) { for(int cnt = 0; cnt < loop; cnt ++) { double m1 = (left * 2 + right) / 3.0; double m2 = (left + right * 2) / 3.0; if(op.apply(m1) > op.apply(m2) ^ minimize) right = m2; else left = m1; } return (left + right) / 2.0; } // mods Mod md = new Mod(); // class Mod107 extends Mod { Mod107() { super(1_000_000_007); } } Mod107 md = new Mod107(); // class Mod998 extends Mod { Mod998() { super(998244353); } } Mod998 md = new Mod998(); class Mod { final long MOD = 1_000_000_007; Mod() { MH = 0; ML = 0; IS_MOD_CONST = true; } // final long MOD = 998244353; Mod() { MH = 0; ML = 0; IS_MOD_CONST = true; } // final long MOD; Mod(long mod) { MOD = mod; IS_MOD_CONST = false; long a = (1l << 32) / MOD; long b = (1l << 32) % MOD; long m = a * a * MOD + 2 * a * b + (b * b) / MOD; MH = m >>> 32; ML = m & MASK; } static final long MASK = 0xffff_ffffl; final long MH; final long ML; final boolean IS_MOD_CONST; final long reduce(long x) { if(MOD == 1) return 0; if(x < 0) return (x = reduce(- x)) == 0 ? 0 : MOD - x; long z = (x & MASK) * ML; z = (x & MASK) * MH + (x >>> 32) * ML + (z >>> 32); z = (x >>> 32) * MH + (z >>> 32); x -= z * MOD; return x < MOD ? x : x - MOD; } final long mod(long x) { if(0 <= x && x < MOD) return x; if(- MOD <= x && x < 0) return x + MOD; return IS_MOD_CONST ? ((x %= MOD) < 0 ? x + MOD : x) : reduce(x); } final long[] mod(long[] a) { for(int i = 0; i < a.length; i ++) a[i] = mod(a[i]); return a; } final long[][] mod(long[][] a) { for(int i = 0; i < a.length; i ++) mod(a[i]); return a; } final long[][][] mod(long[][][] a) { for(int i = 0; i < a.length; i ++) mod(a[i]); return a; } final long add(long x, long y) { return (x += y) >= MOD * 2 || x < 0 ? mod(x) : x >= MOD ? x - MOD : x; } final long sum(long... x) { long sum = 0; for(long ele : x) sum = add(sum, ele); return sum; } final long sub(long x, long y) { return (x -= y) < - MOD || x >= MOD ? mod(x) : x < 0 ? x + MOD : x; } final long pow(long x, long y) { nonNegativeCheck(y); x = mod(x); long ans = 1; for(; y > 0; y >>= 1) { if((y & 1) != 0) ans = mul(ans, x); x = mul(x, x); } return ans; } final long mul(long x, long y) { if(x >= 0 && x < MOD && y >= 0 && y < MOD) return IS_MOD_CONST ? (x * y) % MOD : reduce(x * y); x = mod(x); y = mod(y); return IS_MOD_CONST ? (x * y) % MOD : reduce(x * y); } final long mul(long... x) { long ans = 1; for(long ele : x) ans = mul(ans, ele); return ans; } final long div(long x, long y) { return mul(x, inv(y)); } final long[] pows(long x, int max) { x = mod(x); long pow[] = new long[max + 1]; pow[0] = 1; for(int i = 0; i < max; i ++) pow[i + 1] = mul(pow[i], x); return pow; } final long fact(int n) { nonNegativeCheck(n); prepareFact(); if(n < MAX_FACT1) return fact[n]; else { long ans = fact[MAX_FACT1 - 1]; for(int i = MAX_FACT1; i <= n; i ++) ans = mul(ans, i); return ans; } } final long invFact(int n) { nonNegativeCheck(n); prepareFact(); if(n < MAX_FACT1) return invFact[n]; else return inv(fact(n)); } static final int MAX_INV_SIZE = 100_100; final Map<Long, Long> invMap = new HashMap<>(); final long inv(long x) { x = mod(x); if(invMap.containsKey(x)) return invMap.get(x); if(invMap.size() >= MAX_INV_SIZE) return calInv(x); invMap.put(x, calInv(x)); return invMap.get(x); } final long calInv(long x) { // O(logM) PairLL s = new PairLL(MOD, 0); PairLL t = new PairLL(mod(x), 1); while(t.a > 0) { long tmp = s.a / t.a; PairLL u = new PairLL(s.a - t.a * tmp, s.b - t.b * tmp); s = t; t = u; } if(s.b < 0) s.b += MOD / s.a; return s.b; } final long[] invs(int n) { // O(N) positiveCheck(n); long inv[] = new long[n + 1]; inv[1] = 1; for(int i = 2; i <= n; i ++) inv[i] = mul(inv[(int)(MOD % i)], (MOD - MOD / i)); return inv; } static final int MAX_FACT1 = 5_000_100; static final int MAX_FACT2 = 500_100; static final int MAX_FACT_MAP_SIZE = 100; long fact[]; long invFact[]; boolean isFactPrepared = false; final Map<Long, long[]> factMap = new HashMap<>(); final void prepareFact() { if(isFactPrepared) return; fact = new long[MAX_FACT1]; invFact = new long[MAX_FACT1]; fill(fact, 0); fill(invFact, 0); fact[0] = 1; int maxIndex = min(MAX_FACT1, (int)MOD); for(int i = 1; i < maxIndex; i ++) fact[i] = mul(fact[i - 1], i); invFact[maxIndex - 1] = inv(fact[maxIndex - 1]); for(int i = maxIndex - 1; i > 0; i --) invFact[i - 1] = mul(invFact[i], i); isFactPrepared = true; } final long P(long n, long r) { if(!isFactPrepared) prepareFact(); if(n < 0 || r < 0 || n < r) return 0; if(n < MAX_FACT1 && n < MOD) return mul(fact[(int)n], invFact[(int)(n - r)]); if(!factMap.containsKey(n)) { long largeFact[] = new long[MAX_FACT2]; factMap.put(n, largeFact); fill(largeFact, -1); largeFact[0] = 1; } long largeFact[] = factMap.get(n); if(r >= MAX_FACT2) { long ans = 1; for(long i = n - r + 1; i <= n; i ++) ans = mul(ans, i); return ans; }else { int i = (int)r; while(largeFact[i] < 0) i --; for(; i < r; i ++) largeFact[i + 1] = mul(largeFact[i], n - i); if(factMap.size() > MAX_FACT_MAP_SIZE) factMap.remove(n); return largeFact[(int)r]; } } final long C(long n, long r) { if(!isFactPrepared) prepareFact(); if(n < 0) return mod(C(- n + r - 1, - n - 1) * ((r & 1) == 0 ? 1 : -1)); if(r < 0 || n < r) return 0; r = min(r, n - r); if(n < MOD) return mul(P(n, r), r < MAX_FACT1 ? invFact[(int)r] : inv(fact((int)r))); long digitN[] = baseConvert(n, MOD); long digitR[] = baseConvert(r, MOD); int len = digitN.length; digitR = resize(digitR, len, 0); long ans = 1; for(int i = 0; i < len; i ++) ans = mul(ans, C(digitN[i], digitR[i])); return ans; } final long H(long n, long r) { return C(n - 1 + r, r); } final long sqrt(long x) { x = mod(x); long p = (MOD - 1) >> 1; if(pow(x, p) != 1) return -1; long q = MOD - 1; int m = 1; while(((q >>= 1) & 1) == 0) m ++; long z = 1; while(pow(z, p) == 1) z = random(1, MOD); long c = pow(z, q); long t = pow(x, q); long r = pow(x, (q + 1) >> 1); if(t == 0) return 0; m -= 2; while(t != 1) { long pows[] = new long[m + 1]; pows[0] = t; for(int i = 0; i < m; i ++) pows[i + 1] = mul(pows[i], pows[i]); while(pows[m --] == 1) c = mul(c, c); r = mul(r, c); c = mul(c, c); t = mul(t, c); } return r; } } final long mod(long x, long mod) { if(0 <= x && x < mod) return x; if(- mod <= x && x < 0) return x + mod; return (x %= mod) < 0 ? x + mod : x; } final long pow(long x, long y, long mod) { nonNegativeCheck(y); x = mod(x, mod); long ans = 1; for(; y > 0; y >>= 1) { if((y & 1) != 0) ans = mod(ans * x, mod); x = mod(x * x, mod); } return ans; } // grid class Grids { int h, w; Grid[][] gs; Grid[] gi; Grids(int h, int w) { nonNegativeCheck(h); nonNegativeCheck(w); this.h = h; this.w = w; gs = new Grid[h][w]; gi = new Grid[h * w]; for(int i = 0; i < h; i ++) { for(int j = 0; j < w; j ++) { gs[i][j] = new Grid(i, j, h, w); gi[gs[i][j].i] = gs[i][j]; } } } void init(boolean[][] b) { for(int i = 0; i < h; i ++) for(int j = 0; j < w; j ++) gs[i][j].b = b[i][j]; } void init(long[][] val) { for(int i = 0; i < h; i ++) for(int j = 0; j < w; j ++) gs[i][j].val = val[i][j]; } Grid get(int x, int y) { return isValid(x, y, h, w) ? gs[x][y] : null; } Grid get(int i) { return get(i / w, i % w); } int dx[] = {0, -1, 1, 0, 0, -1, 1, -1, 1}; int dy[] = {0, 0, 0, -1, 1, -1, -1, 1, 1}; Grid next(int x, int y, int i) { return next(gs[x][y], i); } Grid next(Grid g, int i) { return isValid(g.x + dx[i], g.y + dy[i], g.h, g.w) ? gs[g.x + dx[i]][g.y + dy[i]] : null; } } class Grid implements Comparable<Grid> { int x, y, h, w, i; boolean b; long val; Grid() { } Grid(int x, int y, int h, int w) { init(x, y, h, w, false, 0); } Grid(int x, int y, int h, int w, boolean b) { init(x, y, h, w, b, 0); } Grid(int x, int y, int h, int w, long val) { init(x, y, h, w, false, val); } Grid(int x, int y, int h, int w, boolean b, long val) { init(x, y, h, w, b, val); } void init(int x, int y, int h, int w, boolean b, long val) { this.x = x; this.y = y; this.h = h; this.w = w; this.b = b; this.val = val; this.i = x * w + y; } @Override public String toString() { return "("+x+", "+y+")"+" "+booleanToString(b)+" "+val; } @Override public int hashCode() { return Objects.hash(x, y, h, w, b, val); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; Grid that = (Grid) obj; if(this.x != that.x) return false; if(this.y != that.y) return false; if(this.h != that.h) return false; if(this.w != that.w) return false; if(this.b != that.b) return false; if(this.val != that.val) return false; return true; } @Override public int compareTo(Grid that) { int c = Long.compare(this.val, that.val); if(c == 0) c = Integer.compare(this.x, that.x); if(c == 0) c = Integer.compare(this.y, that.y); return c; } } final boolean isValid(int x, int y, int h, int w) { return x >= 0 && x < h && y >= 0 && y < w; } final boolean isValid(Grid g) { return isValid(g.x, g.y, g.h, g.w); } // graph class Graph { int numNode, numEdge; boolean directed; List<Edge> edges = new ArrayList<>(); Node nodes[]; Node reversedNodes[]; Graph(int numNode, int numEdge, boolean directed) { nonNegativeCheck(numNode); this.numNode = numNode; this.numEdge = numEdge; this.directed = directed; nodes = new Node[numNode]; reversedNodes = new Node[numNode]; for(int i = 0; i < numNode; i ++) { nodes[i] = new Node(i); reversedNodes[i] = new Node(i); } } void init(List<Edge> edges) { this.edges = edges; for(Edge e : edges) add(e); } void add(int source, int target, long cost) { add(new Edge(source, target, cost)); } void add(Edge e) { rangeCheck(e.source, numNode); rangeCheck(e.target, numNode); edges.add(e); nodes[e.source].add(e.target, e.cost); if(directed) reversedNodes[e.target].add(e.source, e.cost); else nodes[e.target].add(e.source, e.cost); numEdge = edges.size(); } void clearNodes() { edges.clear(); numEdge = 0; for(Node n : nodes) n.clear(); for(Node n : reversedNodes) n.clear(); } } class Node extends ArrayList<Edge> { int id; Node(int id) { this.id = id; } void add(int target, long cost) { add(new Edge(id, target, cost)); } } class Edge implements Comparable<Edge> { int source; int target; long cost; Edge(int source, int target, long cost) { this.source = source; this.target = target; this.cost = cost; } @Override public String toString() { return source+" - "+cost+" -> "+target; } @Override public int hashCode() { return Objects.hash(source, target); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; Edge that = (Edge) obj; if(this.source != that.source) return false; if(this.target != that.target) return false; return true; } @Override public int compareTo(Edge that) { int c = Long.compare(this.cost, that.cost); if(c == 0) c = Integer.compare(this.source, that.source); if(c == 0) c = Integer.compare(this.target, that.target); return c; } } // Pair class Pair<T extends Comparable<? super T>, U extends Comparable<? super U>> implements Comparable<Pair<T, U>> { T a; U b; Pair() { } Pair(T a, U b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a.toString()+", "+b.toString()+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; Pair that = (Pair) obj; if(this.a.getClass() != that.a.getClass()) return false; if(this.b.getClass() != that.b.getClass()) return false; if(!this.a.equals(that.a)) return false; if(!this.b.equals(that.b)) return false; return true; } @Override public int compareTo(Pair<T, U> that) { int c = (this.a).compareTo(that.a); if(c == 0) c = (this.b).compareTo(that.b); return c; } } final PairII npii() { return new PairII(ni(), ni()); } final PairII[] npii(int n) { PairII a[] = new PairII[n]; for(int i = 0; i < n; i ++) a[i] = npii(); return a; } final PairII[][] npii(int n, int m) { PairII a[][] = new PairII[n][m]; for(int i = 0; i < n; i ++) a[i] = npii(m); return a; } class PairII implements Comparable<PairII> { int a; int b; PairII() { } PairII(int a, int b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a+", "+b+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; PairII that = (PairII) obj; if(this.a != that.a || this.b != that.b) return false; return true; } @Override public int compareTo(PairII that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); return c; } } final PairIL npil() { return new PairIL(ni(), nl()); } final PairIL[] npil(int n) { PairIL a[] = new PairIL[n]; for(int i = 0; i < n; i ++) a[i] = npil(); return a; } final PairIL[][] npil(int n, int m) { PairIL a[][] = new PairIL[n][m]; for(int i = 0; i < n; i ++) a[i] = npil(m); return a; } class PairIL implements Comparable<PairIL> { int a; long b; PairIL() { } PairIL(int a, long b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a+", "+b+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; PairIL that = (PairIL) obj; if(this.a != that.a || this.b != that.b) return false; return true; } @Override public int compareTo(PairIL that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); return c; } } final PairID npid() { return new PairID(ni(), nd()); } final PairID[] npid(int n) { PairID a[] = new PairID[n]; for(int i = 0; i < n; i ++) a[i] = npid(); return a; } final PairID[][] npid(int n, int m) { PairID a[][] = new PairID[n][m]; for(int i = 0; i < n; i ++) a[i] = npid(m); return a; } class PairID implements Comparable<PairID> { int a; double b; PairID() { } PairID(int a, double b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a+", "+b+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; PairID that = (PairID) obj; if(this.a != that.a || this.b != that.b) return false; return true; } @Override public int compareTo(PairID that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); return c; } } final PairLI npli() { return new PairLI(nl(), ni()); } final PairLI[] npli(int n) { PairLI a[] = new PairLI[n]; for(int i = 0; i < n; i ++) a[i] = npli(); return a; } final PairLI[][] npli(int n, int m) { PairLI a[][] = new PairLI[n][m]; for(int i = 0; i < n; i ++) a[i] = npli(m); return a; } class PairLI implements Comparable<PairLI> { long a; int b; PairLI() { } PairLI(long a, int b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a+", "+b+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; PairLI that = (PairLI) obj; if(this.a != that.a || this.b != that.b) return false; return true; } @Override public int compareTo(PairLI that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); return c; } } final PairLL npll() { return new PairLL(nl(), nl()); } final PairLL[] npll(int n) { PairLL a[] = new PairLL[n]; for(int i = 0; i < n; i ++) a[i] = npll(); return a; } final PairLL[][] npll(int n, int m) { PairLL a[][] = new PairLL[n][m]; for(int i = 0; i < n; i ++) a[i] = npll(m); return a; } class PairLL implements Comparable<PairLL> { long a; long b; PairLL() { } PairLL(long a, long b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a+", "+b+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; PairLL that = (PairLL) obj; if(this.a != that.a || this.b != that.b) return false; return true; } @Override public int compareTo(PairLL that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); return c; } } final PairLD npld() { return new PairLD(nl(), nd()); } final PairLD[] npld(int n) { PairLD a[] = new PairLD[n]; for(int i = 0; i < n; i ++) a[i] = npld(); return a; } final PairLD[][] npld(int n, int m) { PairLD a[][] = new PairLD[n][m]; for(int i = 0; i < n; i ++) a[i] = npld(m); return a; } class PairLD implements Comparable<PairLD> { long a; double b; PairLD() { } PairLD(long a, double b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a+", "+b+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; PairLD that = (PairLD) obj; if(this.a != that.a || this.b != that.b) return false; return true; } @Override public int compareTo(PairLD that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); return c; } } final PairDI npdi() { return new PairDI(nd(), ni()); } final PairDI[] npdi(int n) { PairDI a[] = new PairDI[n]; for(int i = 0; i < n; i ++) a[i] = npdi(); return a; } final PairDI[][] npdi(int n, int m) { PairDI a[][] = new PairDI[n][m]; for(int i = 0; i < n; i ++) a[i] = npdi(m); return a; } class PairDI implements Comparable<PairDI> { double a; int b; PairDI() { } PairDI(double a, int b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a+", "+b+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; PairDI that = (PairDI) obj; if(this.a != that.a || this.b != that.b) return false; return true; } @Override public int compareTo(PairDI that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); return c; } } final PairDL npdl() { return new PairDL(nd(), nl()); } final PairDL[] npdl(int n) { PairDL a[] = new PairDL[n]; for(int i = 0; i < n; i ++) a[i] = npdl(); return a; } final PairDL[][] npdl(int n, int m) { PairDL a[][] = new PairDL[n][m]; for(int i = 0; i < n; i ++) a[i] = npdl(m); return a; } class PairDL implements Comparable<PairDL> { double a; long b; PairDL() { } PairDL(double a, long b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a+", "+b+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; PairDL that = (PairDL) obj; if(this.a != that.a || this.b != that.b) return false; return true; } @Override public int compareTo(PairDL that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); return c; } } final PairDD npdd() { return new PairDD(nd(), nd()); } final PairDD[] npdd(int n) { PairDD a[] = new PairDD[n]; for(int i = 0; i < n; i ++) a[i] = npdd(); return a; } final PairDD[][] npdd(int n, int m) { PairDD a[][] = new PairDD[n][m]; for(int i = 0; i < n; i ++) a[i] = npdd(m); return a; } class PairDD implements Comparable<PairDD> { double a; double b; PairDD() { } PairDD(double a, double b) { this.a = a; this.b = b; } @Override public String toString() { return "("+a+", "+b+")"; } @Override public int hashCode() { return Objects.hash(a, b); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; PairDD that = (PairDD) obj; if(this.a != that.a || this.b != that.b) return false; return true; } @Override public int compareTo(PairDD that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); return c; } } interface ITuple { public StringBuilder toStringBuilder(); @Override public String toString(); @Override public int hashCode(); @Override public boolean equals(Object obj); } class BasicTuple<T extends ITuple & Comparable<? super T>, V extends Comparable<? super V>> implements Comparable<BasicTuple> { T t; V a; BasicTuple() { } StringBuilder sbTuple = new StringBuilder(); public StringBuilder toStringBuilder() { sbTuple.setLength(0); return sbTuple.append(t.toStringBuilder()).append(", ").append(a); } @Override public String toString() { return "("+toStringBuilder().toString()+")"; } @Override public int hashCode() { return Objects.hash(t, a); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; BasicTuple that = (BasicTuple) obj; if(this.t.getClass() != that.t.getClass()) return false; if(this.a.getClass() != that.a.getClass()) return false; if(!this.t.equals(that.t)) return false; if(!this.a.equals(that.a)) return false; return true; } @Override @SuppressWarnings("unchecked") public int compareTo(BasicTuple that) { int c = (this.t).compareTo((T) (Object) that.t); if(c == 0) c = (this.a).compareTo((V) (Object) that.a); return c; } } class UniqueTuple<V extends Comparable<? super V>> implements ITuple, Comparable<UniqueTuple> { V a; UniqueTuple() { } final StringBuilder sbTuple = new StringBuilder(); public StringBuilder toStringBuilder() { sbTuple.setLength(0); return sbTuple.append(a); } @Override public String toString() { return "("+toStringBuilder().toString()+")"; } @Override public int hashCode() { return Objects.hash(a); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(this.getClass() != obj.getClass()) return false; UniqueTuple that = (UniqueTuple) obj; if(this.a.getClass() != that.a.getClass()) return false; if(!this.a.equals(that.a)) return false; return true; } @Override @SuppressWarnings("unchecked") public int compareTo(UniqueTuple that) { return (this.a).compareTo((V) (Object) that.a); } } class Tuple1<T0 extends Comparable<? super T0>> extends UniqueTuple<T0> implements ITuple { Tuple1() { super(); } Tuple1(T0 a0) { super(); this.a = a0; } T0 get0() { return a; } void set0(T0 x) { a = x; } } class Tuple2< T0 extends Comparable<? super T0>, T1 extends Comparable<? super T1>> extends BasicTuple<Tuple1<T0>, T1> implements ITuple { Tuple2() { super(); } @SuppressWarnings("unchecked") Tuple2(T0 a0, T1 a1) { super(); this.t = new Tuple1(a0); this.a = a1; } T0 get0() { return t.get0(); } T1 get1() { return a; } void set0(T0 x) { t.set0(x); } void set1(T1 x) { a = x; } } class Tuple3< T0 extends Comparable<? super T0>, T1 extends Comparable<? super T1>, T2 extends Comparable<? super T2>> extends BasicTuple<Tuple2<T0, T1>, T2> implements ITuple { Tuple3() { super(); } @SuppressWarnings("unchecked") Tuple3(T0 a0, T1 a1, T2 a2) { super(); this.t = new Tuple2(a0, a1); this.a = a2; } T0 get0() { return t.get0(); } T1 get1() { return t.get1(); } T2 get2() { return a; } void set0(T0 x) { t.set0(x); } void set1(T1 x) { t.set1(x); } void set2(T2 x) { a = x; } } class Tuple4< T0 extends Comparable<? super T0>, T1 extends Comparable<? super T1>, T2 extends Comparable<? super T2>, T3 extends Comparable<? super T3>> extends BasicTuple<Tuple3<T0, T1, T2>, T3> implements ITuple { Tuple4() { super(); } @SuppressWarnings("unchecked") Tuple4(T0 a0, T1 a1, T2 a2, T3 a3) { super(); this.t = new Tuple3(a0, a1, a2); this.a = a3; } T0 get0() { return t.get0(); } T1 get1() { return t.get1(); } T2 get2() { return t.get2(); } T3 get3() { return a; } void set0(T0 x) { t.set0(x); } void set1(T1 x) { t.set1(x); } void set2(T2 x) { t.set2(x); } void set3(T3 x) { a = x; } } class Tuple5< T0 extends Comparable<? super T0>, T1 extends Comparable<? super T1>, T2 extends Comparable<? super T2>, T3 extends Comparable<? super T3>, T4 extends Comparable<? super T4>> extends BasicTuple<Tuple4<T0, T1, T2, T3>, T4> implements ITuple { Tuple5() { super(); } @SuppressWarnings("unchecked") Tuple5(T0 a0, T1 a1, T2 a2, T3 a3, T4 a4) { super(); this.t = new Tuple4(a0, a1, a2, a3); this.a = a4; } T0 get0() { return t.get0(); } T1 get1() { return t.get1(); } T2 get2() { return t.get2(); } T3 get3() { return t.get3(); } T4 get4() { return a; } void set0(T0 x) { t.set0(x); } void set1(T1 x) { t.set1(x); } void set2(T2 x) { t.set2(x); } void set3(T3 x) { t.set3(x); } void set4(T4 x) { a = x; } } class Tuple6< T0 extends Comparable<? super T0>, T1 extends Comparable<? super T1>, T2 extends Comparable<? super T2>, T3 extends Comparable<? super T3>, T4 extends Comparable<? super T4>, T5 extends Comparable<? super T5>> extends BasicTuple<Tuple5<T0, T1, T2, T3, T4>, T5> implements ITuple { Tuple6() { super(); } @SuppressWarnings("unchecked") Tuple6(T0 a0, T1 a1, T2 a2, T3 a3, T4 a4, T5 a5) { super(); this.t = new Tuple5(a0, a1, a2, a3, a4); this.a = a5; } T0 get0() { return t.get0(); } T1 get1() { return t.get1(); } T2 get2() { return t.get2(); } T3 get3() { return t.get3(); } T4 get4() { return t.get4(); } T5 get5() { return a; } void set0(T0 x) { t.set0(x); } void set1(T1 x) { t.set1(x); } void set2(T2 x) { t.set2(x); } void set3(T3 x) { t.set3(x); } void set4(T4 x) { t.set4(x); } void set5(T5 x) { a = x; } } class Tuple7< T0 extends Comparable<? super T0>, T1 extends Comparable<? super T1>, T2 extends Comparable<? super T2>, T3 extends Comparable<? super T3>, T4 extends Comparable<? super T4>, T5 extends Comparable<? super T5>, T6 extends Comparable<? super T6>> extends BasicTuple<Tuple6<T0, T1, T2, T3, T4, T5>, T6> implements ITuple { Tuple7() { super(); } @SuppressWarnings("unchecked") Tuple7(T0 a0, T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T6 a6) { super(); this.t = new Tuple6(a0, a1, a2, a3, a4, a5); this.a = a6; } T0 get0() { return t.get0(); } T1 get1() { return t.get1(); } T2 get2() { return t.get2(); } T3 get3() { return t.get3(); } T4 get4() { return t.get4(); } T5 get5() { return t.get5(); } T6 get6() { return a; } void set0(T0 x) { t.set0(x); } void set1(T1 x) { t.set1(x); } void set2(T2 x) { t.set2(x); } void set3(T3 x) { t.set3(x); } void set4(T4 x) { t.set4(x); } void set5(T5 x) { t.set5(x); } void set6(T6 x) { a = x; } } class Tuple8< T0 extends Comparable<? super T0>, T1 extends Comparable<? super T1>, T2 extends Comparable<? super T2>, T3 extends Comparable<? super T3>, T4 extends Comparable<? super T4>, T5 extends Comparable<? super T5>, T6 extends Comparable<? super T6>, T7 extends Comparable<? super T7>> extends BasicTuple<Tuple7<T0, T1, T2, T3, T4, T5, T6>, T7> implements ITuple { Tuple8() { super(); } @SuppressWarnings("unchecked") Tuple8(T0 a0, T1 a1, T2 a2, T3 a3, T4 a4, T5 a5, T6 a6, T7 a7) { super(); this.t = new Tuple7(a0, a1, a2, a3, a4, a5, a6); this.a = a7; } T0 get0() { return t.get0(); } T1 get1() { return t.get1(); } T2 get2() { return t.get2(); } T3 get3() { return t.get3(); } T4 get4() { return t.get4(); } T5 get5() { return t.get5(); } T6 get6() { return t.get6(); } T7 get7() { return a; } void set0(T0 x) { t.set0(x); } void set1(T1 x) { t.set1(x); } void set2(T2 x) { t.set2(x); } void set3(T3 x) { t.set3(x); } void set4(T4 x) { t.set4(x); } void set5(T5 x) { t.set5(x); } void set6(T6 x) { t.set6(x); } void set7(T7 x) { a = x; } } class TupleIII implements Comparable<TupleIII> { int a; int b; int c; TupleIII() { } TupleIII(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleIII that = (TupleIII) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleIII that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); if(c == 0) c = Integer.compare(this.c, that.c); return c; } } class TupleIIL implements Comparable<TupleIIL> { int a; int b; long c; TupleIIL() { } TupleIIL(int a, int b, long c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleIIL that = (TupleIIL) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleIIL that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); if(c == 0) c = Long.compare(this.c, that.c); return c; } } class TupleIID implements Comparable<TupleIID> { int a; int b; double c; TupleIID() { } TupleIID(int a, int b, double c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleIID that = (TupleIID) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleIID that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); if(c == 0) c = Double.compare(this.c, that.c); return c; } } class TupleILI implements Comparable<TupleILI> { int a; long b; int c; TupleILI() { } TupleILI(int a, long b, int c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleILI that = (TupleILI) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleILI that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); if(c == 0) c = Integer.compare(this.c, that.c); return c; } } class TupleILL implements Comparable<TupleILL> { int a; long b; long c; TupleILL() { } TupleILL(int a, long b, long c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleILL that = (TupleILL) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleILL that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); if(c == 0) c = Long.compare(this.c, that.c); return c; } } class TupleILD implements Comparable<TupleILD> { int a; long b; double c; TupleILD() { } TupleILD(int a, long b, double c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleILD that = (TupleILD) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleILD that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); if(c == 0) c = Double.compare(this.c, that.c); return c; } } class TupleIDI implements Comparable<TupleIDI> { int a; double b; int c; TupleIDI() { } TupleIDI(int a, double b, int c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleIDI that = (TupleIDI) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleIDI that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); if(c == 0) c = Integer.compare(this.c, that.c); return c; } } class TupleIDL implements Comparable<TupleIDL> { int a; double b; long c; TupleIDL() { } TupleIDL(int a, double b, long c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleIDL that = (TupleIDL) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleIDL that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); if(c == 0) c = Long.compare(this.c, that.c); return c; } } class TupleIDD implements Comparable<TupleIDD> { int a; double b; double c; TupleIDD() { } TupleIDD(int a, double b, double c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleIDD that = (TupleIDD) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleIDD that) { int c = Integer.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); if(c == 0) c = Double.compare(this.c, that.c); return c; } } class TupleLII implements Comparable<TupleLII> { long a; int b; int c; TupleLII() { } TupleLII(long a, int b, int c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleLII that = (TupleLII) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleLII that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); if(c == 0) c = Integer.compare(this.c, that.c); return c; } } class TupleLIL implements Comparable<TupleLIL> { long a; int b; long c; TupleLIL() { } TupleLIL(long a, int b, long c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleLIL that = (TupleLIL) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleLIL that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); if(c == 0) c = Long.compare(this.c, that.c); return c; } } class TupleLID implements Comparable<TupleLID> { long a; int b; double c; TupleLID() { } TupleLID(long a, int b, double c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleLID that = (TupleLID) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleLID that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); if(c == 0) c = Double.compare(this.c, that.c); return c; } } class TupleLLI implements Comparable<TupleLLI> { long a; long b; int c; TupleLLI() { } TupleLLI(long a, long b, int c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleLLI that = (TupleLLI) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleLLI that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); if(c == 0) c = Integer.compare(this.c, that.c); return c; } } class TupleLLL implements Comparable<TupleLLL> { long a; long b; long c; TupleLLL() { } TupleLLL(long a, long b, long c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleLLL that = (TupleLLL) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleLLL that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); if(c == 0) c = Long.compare(this.c, that.c); return c; } } class TupleLLD implements Comparable<TupleLLD> { long a; long b; double c; TupleLLD() { } TupleLLD(long a, long b, double c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleLLD that = (TupleLLD) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleLLD that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); if(c == 0) c = Double.compare(this.c, that.c); return c; } } class TupleLDI implements Comparable<TupleLDI> { long a; double b; int c; TupleLDI() { } TupleLDI(long a, double b, int c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleLDI that = (TupleLDI) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleLDI that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); if(c == 0) c = Integer.compare(this.c, that.c); return c; } } class TupleLDL implements Comparable<TupleLDL> { long a; double b; long c; TupleLDL() { } TupleLDL(long a, double b, long c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleLDL that = (TupleLDL) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleLDL that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); if(c == 0) c = Long.compare(this.c, that.c); return c; } } class TupleLDD implements Comparable<TupleLDD> { long a; double b; double c; TupleLDD() { } TupleLDD(long a, double b, double c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleLDD that = (TupleLDD) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleLDD that) { int c = Long.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); if(c == 0) c = Double.compare(this.c, that.c); return c; } } class TupleDII implements Comparable<TupleDII> { double a; int b; int c; TupleDII() { } TupleDII(double a, int b, int c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleDII that = (TupleDII) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleDII that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); if(c == 0) c = Integer.compare(this.c, that.c); return c; } } class TupleDIL implements Comparable<TupleDIL> { double a; int b; long c; TupleDIL() { } TupleDIL(double a, int b, long c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleDIL that = (TupleDIL) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleDIL that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); if(c == 0) c = Long.compare(this.c, that.c); return c; } } class TupleDID implements Comparable<TupleDID> { double a; int b; double c; TupleDID() { } TupleDID(double a, int b, double c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleDID that = (TupleDID) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleDID that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Integer.compare(this.b, that.b); if(c == 0) c = Double.compare(this.c, that.c); return c; } } class TupleDLI implements Comparable<TupleDLI> { double a; long b; int c; TupleDLI() { } TupleDLI(double a, long b, int c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleDLI that = (TupleDLI) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleDLI that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); if(c == 0) c = Integer.compare(this.c, that.c); return c; } } class TupleDLL implements Comparable<TupleDLL> { double a; long b; long c; TupleDLL() { } TupleDLL(double a, long b, long c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleDLL that = (TupleDLL) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleDLL that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); if(c == 0) c = Long.compare(this.c, that.c); return c; } } class TupleDLD implements Comparable<TupleDLD> { double a; long b; double c; TupleDLD() { } TupleDLD(double a, long b, double c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleDLD that = (TupleDLD) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleDLD that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Long.compare(this.b, that.b); if(c == 0) c = Double.compare(this.c, that.c); return c; } } class TupleDDI implements Comparable<TupleDDI> { double a; double b; int c; TupleDDI() { } TupleDDI(double a, double b, int c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleDDI that = (TupleDDI) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleDDI that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); if(c == 0) c = Integer.compare(this.c, that.c); return c; } } class TupleDDL implements Comparable<TupleDDL> { double a; double b; long c; TupleDDL() { } TupleDDL(double a, double b, long c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleDDL that = (TupleDDL) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleDDL that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); if(c == 0) c = Long.compare(this.c, that.c); return c; } } class TupleDDD implements Comparable<TupleDDD> { double a; double b; double c; TupleDDD() { } TupleDDD(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } @Override public String toString() { return "("+a+", "+b+", "+c+")"; } @Override public int hashCode() { return Objects.hash(a, b, c); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null || this.getClass() != obj.getClass()) return false; TupleDDD that = (TupleDDD) obj; if(this.a != that.a || this.b != that.b || this.c != that.c) return false; return true; } @Override public int compareTo(TupleDDD that) { int c = Double.compare(this.a, that.a); if(c == 0) c = Double.compare(this.b, that.b); if(c == 0) c = Double.compare(this.c, that.c); return c; } } public void solve() { long n = nl(); int m = ni(); int d = ni(); long r[] = nl(m + 1); r = resize(r, m * 2, m - 1); for(int i = 0; i < m; i ++) r[i] = - r[m * 2 - i - 1]; for(int i = 0; i < m; i ++) r[m + i] ++; long s[] = nl(m); s = resize(s, m * 2 + 1, m); for(int i = 1; i <= m; i ++) s[i] = s[m * 2 - i]; for(int i = m * 2; i > 0; i --) s[i] -= s[i - 1]; for(int i = 0; i <= m * 2; i ++) s[i] *= -1; long sum[] = new long[d + 1]; long x = - divfloor(n * d, 2); for(int i = 0; i < m * 2; i ++) { long r1 = constrain(divceil(r[i] - x, d), 0, n); long r2 = constrain(divceil(r[i] - x - d + 1, d), 0, n); sum[0] += r1 * s[i + 1]; int j = (int)((r[i] - x) % d); if(j < 0) j += d; sum[j] += (r2 - r1) * s[i + 1]; sum[d] -= r2 * s[i + 1]; } for(int i = 0; i < d; i ++) sum[i + 1] += sum[i]; prtln(max(sum)); } } }
ConDefects/ConDefects/Code/arc131_d/Java/30717346
condefects-java_data_700
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.util.function.*; import java.util.stream.IntStream; public class Main implements Runnable{ public static void main(String[] args) { new Thread(null,new Main(),"",16*1024*1024).start(); } public void run(){ Solver.SOLVE(); } } class UnionFind { private int[] roots; public UnionFind(int n){ roots = new int[n]; for (int i = 0; i < n; i++) { roots[i] = i; } } public int root(int x){ if(roots[x] == x){ return x; } return roots[x] = root(roots[x]); } public void unite(int x,int y){ int rx = root(x); int ry = root(y); if(rx == ry){ return; } roots[rx] = ry; } public boolean same(int x,int y){ int rx = root(x); int ry = root(y); return rx == ry; } } class DSU { private int n; private int[] parentOrSize; public DSU(int n) { this.n = n; this.parentOrSize = new int[n]; java.util.Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; return x; } boolean same(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("" + a); return -parentOrSize[leader(a)]; } ArrayList<ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } ArrayList<ArrayList<Integer>> result = new ArrayList<>(n); for (int i = 0; i < n; i++) { result.add(new ArrayList<>(groupSize[i])); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } result.removeIf(ArrayList::isEmpty); return result; } } class PairL implements Comparable<PairL>, Comparator<PairL> { public long x,y; public PairL(long x,long y) { this.x = x; this.y = y; } public void swap(){ long t = x; x = y; y = t; } @Override public int compare(PairL o1, PairL o2) { return o1.compareTo(o2); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairL pairl = (PairL) o; return x == pairl.x && y == pairl.y; } @Override public int hashCode() { return Objects.hash(x, y); } public PairL add(PairL p){ return new PairL(x+p.x,y+p.y); } @Override public int compareTo(PairL o) { return Long.compare(x,o.x); } } class PairI implements Comparable<PairI>, Comparator<PairI> { public int x,y; public PairI(int x,int y) { this.x = x; this.y = y; } public void swap(){ int t = x; x = y; y = t; } @Override public int compare(PairI o1, PairI o2) { if(o1.x == o2.x){ return Integer.compare(o1.y,o2.y); } return Integer.compare(o1.x,o2.x); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairI pairI = (PairI) o; return x == pairI.x && y == pairI.y; } @Override public int hashCode() { return Objects.hash(x, y); } @Override public int compareTo(PairI o) { if(x == o.x){ return Integer.compare(y,o.y); } return Integer.compare(x,o.x); } public PairI add(PairI p){ return new PairI(x+p.x,y+p.y); } public PairI sub(PairI p){ return new PairI(x-p.x,y-p.y); } public PairI addG(PairI p,int h,int w) { int x = this.x + p.x; int y = this.y + p.y; if(0 <= x&&x < w&&0 <= y&&y < h){ return new PairI(x,y); } return null; } } class PairISet{ int x,y; PairISet(int x,int y){ this.x = x; this.y = y; } @Override public int hashCode() { return Objects.hash(x, y); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairI pairI = (PairI) o; return (x == pairI.x && y == pairI.y)||(x == pairI.y && y == pairI.x); } } class Line{ //ax+bx+c=0 long a,b,c; public Line(int x0, int y0, int x1, int y1) { long dx = x1-x0; long dy = y1-y0; long gcd = Solver.gcd(dx,dy); dx/=gcd; dy/=gcd; if(dx < 0){ dx=-dx; dy=-dy; } if(dx == 0 && dy < 0){ dy=-dy; } a = dy; b = -dx; c = dx*y0-dy*x0; } public boolean onLine(int x,int y){ return a*x + b*y + c == 0; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Line line = (Line) o; return a == line.a && b == line.b && c == line.c; } @Override public int hashCode() { return Objects.hash(a, b, c); } } class Dist extends PairI{ int d; public Dist(int x,int y,int d){ super(x,y); this.d = d; } public Dist addG(PairI p,int h,int w) { int x = this.x + p.x; int y = this.y + p.y; if(0 <= x&&x < w&&0 <= y&&y < h){ return new Dist(x,y,d+1); } return null; } } class Tuple implements Comparable<Tuple>{ public int x,y,z; public Tuple(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Tuple three = (Tuple) o; return x == three.x && y == three.y && z == three.z; } @Override public int hashCode() { return Objects.hash(x, y, z); } @Override public int compareTo(Tuple o) { if(x == o.x){ return Integer.compare(y,o.y); } return Integer.compare(x,o.x); } } class Edge implements Comparable<Edge>{ public int from; public int to; public int name; public long d; public Edge(int to){ this.to = to; } public Edge(int to, long d){ this.to = to; this.d = d; } public Edge setName(int name){ this.name = name; return this; } public Edge(int from, int to, long d){ this.to = to; this.from = from; this.d = d; } @Override public int compareTo(Edge o) { return Long.compare(d,o.d); } } class PairC{ char a,b; public PairC(char a, char b){ this.a = a; this.b = b; } } class IB{ int i; boolean b; IB(int i,boolean b){ this.i = i; this.b = b; } } class CI{ char c; int i; CI(char c,int i){ this.c = c; this.i = i; } } class SortedMultiSet extends TreeMap<Long,Integer>{ public void add(long a){ put(a,getOrDefault(a,0)+1); } public void remove(long a){ if(get(a) == 1){ super.remove(a); }else{ put(a,get(a)-1); } } public void lower(long a){ } } class MultiSet extends HashMap<Integer,Integer>{ public void add(int a){ put(a,getOrDefault(a,0)+1); } public void remove(int a){ if(get(a) == 1){ super.remove(a); }else{ put(a,get(a)-1); } } public boolean contains(int a){ return containsKey(a); } } class PP{ PairI s,t; int name; public PP(PairI s, PairI t,int name) { this.s = s; this.t = t; this.name = name; } } class Plane{ ArrayList<PP> up,down; public Plane(){ up = new ArrayList<>(); down = new ArrayList<>(); } } class Matrix{ int row; int column; int[][] nums; public Matrix(int row,int column){ this.row = row; this.column = column; nums = new int[row][column]; } } class SquareMatrix{ int size; long[][] nums; public SquareMatrix(int size){ this.size = size; nums = new long[size][size]; } public SquareMatrix(long[][] nums){ size = nums.length; this.nums = new long[size][size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { this.nums[i][j] = nums[i][j]; } } } public static SquareMatrix identityMatrix(int size){ long[][] mat = new long[size][size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if(i == j){ mat[i][j] = 1; } } } return new SquareMatrix(mat); } public SquareMatrix mul(SquareMatrix m){ if(m.size != size){ throw new IllegalArgumentException(); } SquareMatrix ans = new SquareMatrix(size); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { ans.nums[i][k] += nums[i][j]*m.nums[j][k]; } } } return ans; } public SquareMatrix modMul(SquareMatrix m,long mod){ if(m.size != size){ throw new IllegalArgumentException(); } SquareMatrix ans = new SquareMatrix(size); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { ans.nums[i][k] += nums[i][j]*m.nums[j][k]; ans.nums[i][k]%=mod; } } } return ans; } public long[] mulVec(long[] vec){ if(vec.length != size){ throw new IllegalArgumentException(); } long[] ans = new long[size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { ans[i] += vec[j]*nums[i][j]; } } return ans; } public long[] modMulVec(long[] vec,long mod){ if(vec.length != size){ throw new IllegalArgumentException(); } long[] ans = new long[size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { ans[i] += vec[j]*nums[i][j]; ans[i]%=mod; } } return ans; } public static SquareMatrix pow(SquareMatrix base,long exp){ SquareMatrix ans = identityMatrix(base.size); while (exp > 0){ if ((exp & 1) == 1) { ans = base.mul(ans); } base = base.mul(base); exp >>= 1; } return ans; } public SquareMatrix pow(long exp){ return pow(this,exp); } public static SquareMatrix modPow(SquareMatrix base,long exp,long mod){ SquareMatrix ans = identityMatrix(base.size); while (exp > 0){ if ((exp & 1) == 1) { ans = base.modMul(ans,mod); } base = base.modMul(base,mod); exp >>= 1; } return ans; } public SquareMatrix modPow(long exp,long mod){ return modPow(this,exp,mod); } } class Fraction implements Comparable<Fraction>{ int de,num; int name; public Fraction(int de, int num) { this.de = de; this.num = num; } @Override public int compareTo(Fraction o) { long a = (long) de * o.num; long b = (long) num* o.de; return Long.compare(a,b); } } class Solver { public static final int MOD1 = 1000000007; public static final int MOD9 = 998244353; public static Scanner sc = new Scanner(System.in); public static final int inf = 2000000000; public static final int ninf = -inf; public static final char[] alpha = "abcdefghijklmnopqrstuvwxyz".toCharArray(); public static final char[] ALPHA = "abcdefghijklmnopqrstuvwxyz".toUpperCase().toCharArray(); public static FastScanner fs = new FastScanner(); public static PrintWriter out = new PrintWriter(System.out); public static final PairI[] move = new PairI[]{new PairI(1,0),new PairI(0,1),new PairI(-1,0),new PairI(0,-1)}; public static final PairI[] move8 = new PairI[]{ new PairI(1,0),new PairI(0,1),new PairI(-1,0),new PairI(0,-1), new PairI(1,1),new PairI(-1,1),new PairI(1,-1),new PairI(-1,-1) }; public static void solve() { int n = rI(); int[] c = rIv(9); int min = min(c); int minidx = -1; for (int i = 0; i < 9; i++) { if(c[i] == min){ minidx = i; } } int times = n/min; if(times == 0) { oI(0); return; } int[] ans = new int[times]; Arrays.fill(ans,minidx+1); int left = n%min; int[] nc = new int[9-minidx]; for (int i = 0; i < 9 - minidx; i++) { nc[i] = c[i+minidx] - min; } int idx = 0; out:for (int i = 8-minidx; i >= 0; i--) { if(left == 0) break; int time = left/nc[i]; left = left%nc[i]; while (time-->0){ ans[idx] = i+minidx+1; idx++; if(idx == times){ break out; } } } StringBuilder an = new StringBuilder(); for (int i = 0; i < times; i++) { an.append(ans[i]); } oS(an.toString()); } static char toLower(char a){ return String.valueOf(a).toLowerCase().charAt(0); } static char toUpper(char a){ return String.valueOf(a).toUpperCase().charAt(0); } static int nand(int a,int b){ if(a == 1&&b == 1){ return 0; } return 1; } static int standingBits(long n){ String bits = toBits(n); int ans = 0; for (int i = 0; i < bits.length(); i++) { if(bits.charAt(i) == '1'){ ans++; } } return ans; } static boolean contain(String s,char c){ for (int i = 0; i < s.length(); i++) { if(s.charAt(i) == c){ return true; } } return false; } static String toBits(long n){ StringBuilder ans = new StringBuilder(); while (n > 0){ ans.append(n%2); n/=2; } return ans.reverse().toString(); } static long toLong(String anss){ long ansi = 0; for (int i = 0; i < anss.length(); i++) { if(anss.charAt(i) == '1'){ ansi += (1L<<(anss.length()-1-i)); } } return ansi; } static int perfectPowNum(long n){ int res = 0; double range = Math.log(n)/Math.log(2); range++; for (int i = 2; i < range; i++) { long a = (long) Math.pow(n,1d/i); if(pow(a,i) == n||pow(a+1,i)==n){ res++; } } return res; } static boolean[] eratosthenes(int n){ boolean[] res = new boolean[n+1]; for (int i = 2; i <= n; i++) { res[i] = true; } for (int i = 2; i <= n; i++) { if(res[i]){ int k = i*2; while (k <= n){ res[k] = false; k+=i; } } } return res; } static BitSet and(BitSet set1,BitSet set2){ BitSet ans = (BitSet) set1.clone(); ans.and(set2); return ans; } static BitSet or(BitSet set1,BitSet set2){ BitSet ans = (BitSet) set1.clone(); ans.or(set2); return ans; } static BitSet xor(BitSet set1,BitSet set2){ BitSet ans = (BitSet) set1.clone(); ans.xor(set2); return ans; } static BitSet toBitset(long n){ return BitSet.valueOf(new long[]{n}); } static long toLong(BitSet set){ if(set.length() > 63) { throw new IllegalArgumentException(); } if(set.length() == 0){ return 0; } return set.toLongArray()[0]; } static int deg(long x){ return String.valueOf(x).length(); } static int nthdeg(long x,int d){ x/=pow(10,d); return (int)(x%10); } static boolean isPalindrome(int a,int b,String s){ int dif = b-a; boolean ok = true; for (int i = 0; i < dif; i++) { if (s.charAt(i + a) != s.charAt(b - i)) { ok = false; break; } } return ok; } static int intValue(char c){ return Integer.parseInt(String.valueOf(c)); } public static int toIntC(char c){ for (int i = 0; i < ALPHA.length; i++) { if(c == ALPHA[i]){ return i; } } throw new IllegalArgumentException("not an alphabet"); } public static int toInt(char c){ for (int i = 0; i < alpha.length; i++) { if(c == alpha[i]){ return i; } } throw new IllegalArgumentException("not an alphabet"); } public static void reverse(int[] a){ int[] tmp = a.clone(); for (int i = 0; i < a.length; i++) { a[i] = tmp[a.length - 1 - i]; } } public static int[] compress(int[] a){ int[] ans = new int[a.length]; int[] b = erase(a); Arrays.sort(b); for (int i = 0; i < a.length; i++) { ans[i] = lower(b,a[i]); } return ans; } public static int lower(int[] a,int x){ int low = 0, high = a.length; int mid; while (low < high) { mid = low + (high - low) / 2; if (x <= a[mid]) { high = mid; } else { low = mid + 1; } } if (low < a.length && a[low] < x) { low++; } return low; } public static int lower(long[] a,long x) { int low = 0, high = a.length; int mid; while (low < high) { mid = low + (high - low) / 2; if (x <= a[mid]) { high = mid; } else { low = mid + 1; } } if (low < a.length && a[low] < x) { low++; } return low; } public static <T extends Comparable<? super T>> int lower(T[] a,T x){ int low = 0, high = a.length; int mid; while (low < high) { mid = low + (high - low) / 2; if (x.compareTo(a[mid]) < 1) { high = mid; } else { low = mid + 1; } } if (low < a.length && x.compareTo(a[low]) > 0) { low++; } return low; } public static int upper(int[] a,int x){ int low = 0, high = a.length; int mid; while (low < high && low != a.length) { mid = low + (high - low) / 2; if (x >= a[mid]) { low = mid + 1; } else { high = mid; } } return low; } public static int upper(long[] a,long x){ int low = 0, high = a.length; int mid; while (low < high && low != a.length) { mid = low + (high - low) / 2; if (x >= a[mid]) { low = mid + 1; } else { high = mid; } } return low; } public static <T extends Comparable<? super T>> int upper(T[] a,T x){ int low = 0, high = a.length; int mid; while (low < high && low != a.length) { mid = low + (high - low) / 2; if (x.compareTo(a[mid]) > -1) { low = mid + 1; } else { high = mid; } } return low; } public static int[] erase(int[] a){ HashSet<Integer> used = new HashSet<>(); ArrayList<Integer> ans = new ArrayList<>(); for (int i = 0; i < a.length; i++) { if(!used.contains(a[i])){ used.add(a[i]); ans.add(a[i]); } } return convI(ans); } public static int abs(int a){ return Math.abs(a); } public static long abs(long a){ return Math.abs(a); } public static int max(int a,int b){ return Math.max(a,b); } public static int max(int... a){ int max = Integer.MIN_VALUE; for (int i = 0; i < a.length; i++) { max = max(a[i],max); } return max; } public static long max(long a,long b){ return Math.max(a,b); } public static long max(long... a){ long max = Long.MIN_VALUE; for (int i = 0; i < a.length; i++) { max = max(a[i],max); } return max; } public static int min(int a,int b){ return Math.min(a,b); } public static int min(int... a){ int min = Integer.MAX_VALUE; for (int i = 0; i < a.length; i++) { min = min(a[i],min); } return min; } public static long min(long a,long b){ return Math.min(a, b); } public static long min(long... a){ long min = Long.MAX_VALUE; for (int i = 0; i < a.length; i++) { min = min(a[i],min); } return min; } public static final class MC { private final int mod; public MC(final int mod) { this.mod = mod; } public long mod(long x) { x %= mod; if (x < 0) { x += mod; } return x; } public long add(final long a, final long b) { return mod(mod(a) + mod(b)); } public long add(final long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = add(ans,a[i]); } return mod(ans); } public long mul(final long a, final long b) { return mod(mod(a) * mod(b)); } public long mul(final long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = mul(ans,a[i]); } return mod(ans); } public long div(final long numerator, final long denominator) { return mod(numerator * inverse(denominator)); } public long power(long base, long exp) { long ret = 1; base %= mod; while (exp > 0) { if ((exp & 1) == 1) { ret = mul(ret, base); } base = mul(base, base); exp >>= 1; } return ret; } public long inverse(final long x) { return power(x, mod - 2); } public long fact(final int n) { return product(1, n); } public long permutation(int n,int r){ return product(n-r+1,n); } public long product(final int start, final int end) { long result = 1; for (int i = start; i <= end; i++) { result *= i; result %= mod; } return result; } public long combination(final int n, int r) { if (r > n) { return 0; } r = min(r,n-r); return div(product(n - r + 1, n), fact(r)); } } public static long pow(long x,long n){ long ans = 1L; long tmp = x; while (true){ if(n < 1L){ break; } if(n % 2L == 1L){ ans*=tmp; } tmp *=tmp; n = n >> 1; } return ans; } public static long modPow(long x,long n,long m){ long ans = 1L; long tmp = x%m; while (true){ if(n < 1L){ break; } if(n % 2L == 1L){ ans*=tmp; ans%=m; } tmp *=tmp; tmp%=m; n = n >> 1; } return ans; } public static int gcd(int a,int b){ if(b == 0) return a; else return gcd(b,a%b); } public static long gcd(long a,long b){ if(b == 0) return a; else return gcd(b,a%b); } public static int gcd(int... a){ int ans = a[0]; for (int i = 1; i < a.length; i++) { ans = gcd(ans,a[i]); } return ans; } public static long gcd(long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = gcd(ans,a[i]); } return ans; } public static long lcm(int a,int b){ return (long) a / gcd(a, b) * b; } public static long lcm(long a,long b){ return a / gcd(a,b) * b; } public static boolean isPrime(long x){ if(x < 2) return false; else if(x == 2) return true; if(x%2 == 0) return false; for(long i = 3; i*i <= x; i+= 2){ if(x%i == 0) return false; } return true; } public static int rI() { return fs.nextInt(); } public static int[] rIv(int length) { int[] res = new int[length]; for (int i = 0; i < length; i++) { res[i] = fs.nextInt(); } return res; } public static String rS() { return fs.next(); } public static String[] rSv(int length) { String[] res = new String[length]; for (int i = 0; i < length; i++) res[i] = fs.next(); return res; } public static long rL() { return fs.nextLong(); } public static long[] rLv(int length) { long[] res = new long[length]; for (int i = 0; i < length; i++) res[i] = fs.nextLong(); return res; } public static double rD(){ return fs.nextDouble(); } public static double[] rDv(int length){ double[] res = new double[length]; for (int i = 0; i < length; i++) res[i] = rD(); return res; } public static String aiS(int[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String alS(long[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String adS(double[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String acS(char[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String asS(String[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String liS(ArrayList<Integer> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String liS(ArrayList<Integer> a, IntUnaryOperator o){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(o.applyAsInt(a.get(i))); } return ans.toString(); } public static String llS(ArrayList<Long> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String llS(ArrayList<Long> a, LongUnaryOperator o){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(o.applyAsLong(a.get(i))); } return ans.toString(); } public static String ldS(ArrayList<Double> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String lcS(ArrayList<Character> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String lsS(ArrayList<String> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static void nL(){ out.println(); } public static void oI(int a) { out.println(a); } public static void onI(int a){ out.print(a); } public static void oIv(int... a) { oS(aiS(a)); } public static void oS(String s) { out.println(s); } public static void onS(String s) { out.print(s); } public static void oSv(String[] a) { oS(asS(a)); } public static void oL(long l) { out.println(l); } public static void onL(long l) { out.print(l); } public static void oLv(long... a) { oS(alS(a)); } public static void oD(double d){ out.println(d); } public static void onD(double d){ out.print(d); } public static void oDv(double... d){ oS(adS(d)); } public static void oC(char c){ out.println(c); } public static void onC(char c){ out.print(c); } public static void oCv(char... c){ oS(acS(c)); } public static void fl(){ out.flush(); } public static void yes_no(boolean yes){ if(yes){ oS("Yes"); return; } oS("No"); } public static int fact(int num) { if (num == 0) { return 1; } else if (num == 1) { return 1; } else if (num < 0) { throw new IllegalArgumentException("factorial should be bigger than 0"); } return num * fact(num - 1); } public static int[] convI(ArrayList<Integer> list) { int[] res = new int[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static long[] convL(ArrayList<Long> list) { long[] res = new long[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static String[] convS(ArrayList<String> list) { String[] res = new String[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static ArrayList<Integer> convI(int[] vec) { ArrayList<Integer> list = new ArrayList<>(); for (int i : vec) list.add(i); return list; } public static ArrayList<Long> convL(long[] vec) { ArrayList<Long> list = new ArrayList<>(); for (long i : vec) list.add(i); return list; } public static ArrayList<String> convS(String[] vec) { return new ArrayList<>(Arrays.asList(vec)); } public static ArrayList<ArrayList<Integer>> permutation(int a) { int[] list = new int[a]; for (int i = 0; i < a; i++) { list[i] = i; } return permutation(list); } public static ArrayList<ArrayList<Integer>> permutation1(int a) { int[] list = new int[a]; for (int i = 0; i < a; i++) { list[i] = i+1; } return permutation(list); } public static ArrayList<ArrayList<Integer>> permutation(int[] seed) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); int[] perm = new int[seed.length]; boolean[] used = new boolean[seed.length]; buildPerm(seed, perm, used, 0,res); return res; } private static void buildPerm(int[] seed, int[] perm, boolean[] used, int index,ArrayList<ArrayList<Integer>> res) { if (index == seed.length) { res.add(convI(perm)); return; } for (int i = 0; i < seed.length; i++) { if (used[i]) continue; perm[index] = seed[i]; used[i] = true; buildPerm(seed, perm, used, index + 1,res); used[i] = false; } } public static ArrayList<ArrayList<String>> permutation(String[] seed) { ArrayList<ArrayList<String>> res = new ArrayList<>(); String[] perm = new String[seed.length]; boolean[] used = new boolean[seed.length]; buildPerm(seed, perm, used, 0,res); return res; } private static void buildPerm(String[] seed, String[] perm, boolean[] used, int index,ArrayList<ArrayList<String>> res) { if (index == seed.length) { res.add(convS(perm)); return; } for (int i = 0; i < seed.length; i++) { if (used[i]) continue; perm[index] = seed[i]; used[i] = true; buildPerm(seed, perm, used, index + 1,res); used[i] = false; } } public static void swap(int[] a,int i1,int i2){ int t = a[i1]; a[i1] = a[i2]; a[i2] = t; } public static void swap(char[] a,int i1,int i2){ char t = a[i1]; a[i1] = a[i2]; a[i2] = t; } public static void SOLVE(){ solve(); out.flush(); } } class SegTree<S> { final int MAX; final int N; final java.util.function.BinaryOperator<S> op; final S E; final S[] data; @SuppressWarnings("unchecked") public SegTree(int n, java.util.function.BinaryOperator<S> op, S e) { this.MAX = n; int k = 1; while (k < n) k <<= 1; this.N = k; this.E = e; this.op = op; this.data = (S[]) new Object[N << 1]; java.util.Arrays.fill(data, E); } public SegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e) { this(dat.length, op, e); build(dat); } private void build(S[] dat) { int l = dat.length; System.arraycopy(dat, 0, data, N, l); for (int i = N - 1; i > 0; i--) { data[i] = op.apply(data[i << 1 | 0], data[i << 1 | 1]); } } public void set(int p, S x) { exclusiveRangeCheck(p); data[p += N] = x; p >>= 1; while (p > 0) { data[p] = op.apply(data[p << 1 | 0], data[p << 1 | 1]); p >>= 1; } } public S get(int p) { exclusiveRangeCheck(p); return data[p + N]; } public S prod(int l, int r) { if (l > r) { throw new IllegalArgumentException( String.format("Invalid range: [%d, %d)", l, r) ); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); S sumLeft = E; S sumRight = E; l += N; r += N; while (l < r) { if ((l & 1) == 1) sumLeft = op.apply(sumLeft, data[l++]); if ((r & 1) == 1) sumRight = op.apply(data[--r], sumRight); l >>= 1; r >>= 1; } return op.apply(sumLeft, sumRight); } public S allProd() { return data[1]; } public int maxRight(int l, java.util.function.Predicate<S> f) { inclusiveRangeCheck(l); if (!f.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (l == MAX) return MAX; l += N; S sum = E; do { l >>= Integer.numberOfTrailingZeros(l); if (!f.test(op.apply(sum, data[l]))) { while (l < N) { l = l << 1; if (f.test(op.apply(sum, data[l]))) { sum = op.apply(sum, data[l]); l++; } } return l - N; } sum = op.apply(sum, data[l]); l++; } while ((l & -l) != l); return MAX; } public int minLeft(int r, java.util.function.Predicate<S> f) { inclusiveRangeCheck(r); if (!f.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (r == 0) return 0; r += N; S sum = E; do { r--; while (r > 1 && (r & 1) == 1) r >>= 1; if (!f.test(op.apply(data[r], sum))) { while (r < N) { r = r << 1 | 1; if (f.test(op.apply(data[r], sum))) { sum = op.apply(data[r], sum); r--; } } return r + 1 - N; } sum = op.apply(data[r], sum); } while ((r & -r) != r); return 0; } private void exclusiveRangeCheck(int p) { if (p < 0 || p >= MAX) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for the range [%d, %d).", p, 0, MAX) ); } } private void inclusiveRangeCheck(int p) { if (p < 0 || p > MAX) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for the range [%d, %d].", p, 0, MAX) ); } } // **************** DEBUG **************** // private int indent = 6; public void setIndent(int newIndent) { this.indent = newIndent; } @Override public String toString() { return toSimpleString(); } public String toDetailedString() { return toDetailedString(1, 0); } private String toDetailedString(int k, int sp) { if (k >= N) return indent(sp) + data[k]; String s = ""; s += toDetailedString(k << 1 | 1, sp + indent); s += "\n"; s += indent(sp) + data[k]; s += "\n"; s += toDetailedString(k << 1 | 0, sp + indent); return s; } private static String indent(int n) { StringBuilder sb = new StringBuilder(); while (n --> 0) sb.append(' '); return sb.toString(); } public String toSimpleString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < N; i++) { sb.append(data[i + N]); if (i < N - 1) sb.append(',').append(' '); } sb.append(']'); return sb.toString(); } } /** * @verified * - https://atcoder.jp/contests/practice2/tasks/practice2_e * - http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_6_B */ class MinCostFlow { private static final class InternalWeightedCapEdge { final int to, rev; long cap; final long cost; InternalWeightedCapEdge(int to, int rev, long cap, long cost) { this.to = to; this.rev = rev; this.cap = cap; this.cost = cost; } } public static final class WeightedCapEdge { public final int from, to; public final long cap, flow, cost; WeightedCapEdge(int from, int to, long cap, long flow, long cost) { this.from = from; this.to = to; this.cap = cap; this.flow = flow; this.cost = cost; } @Override public boolean equals(Object o) { if (o instanceof WeightedCapEdge) { WeightedCapEdge e = (WeightedCapEdge) o; return from == e.from && to == e.to && cap == e.cap && flow == e.flow && cost == e.cost; } return false; } } private static final class IntPair { final int first, second; IntPair(int first, int second) { this.first = first; this.second = second; } } public static final class FlowAndCost { public final long flow, cost; FlowAndCost(long flow, long cost) { this.flow = flow; this.cost = cost; } @Override public boolean equals(Object o) { if (o instanceof FlowAndCost) { FlowAndCost c = (FlowAndCost) o; return flow == c.flow && cost == c.cost; } return false; } } static final long INF = Long.MAX_VALUE; private final int n; private final java.util.ArrayList<IntPair> pos; public final java.util.ArrayList<InternalWeightedCapEdge>[] g; @SuppressWarnings("unchecked") public MinCostFlow(int n) { this.n = n; this.pos = new java.util.ArrayList<>(); this.g = new java.util.ArrayList[n]; for (int i = 0; i < n; i++) { this.g[i] = new java.util.ArrayList<>(); } } public int addEdge(int from, int to, long cap, long cost) { rangeCheck(from, 0, n); rangeCheck(to, 0, n); nonNegativeCheck(cap, "Capacity"); nonNegativeCheck(cost, "Cost"); int m = pos.size(); pos.add(new IntPair(from, g[from].size())); int fromId = g[from].size(); int toId = g[to].size(); if (from == to) toId++; g[from].add(new InternalWeightedCapEdge(to, toId, cap, cost)); g[to].add(new InternalWeightedCapEdge(from, fromId, 0L, -cost)); return m; } private InternalWeightedCapEdge getInternalEdge(int i) { return g[pos.get(i).first].get(pos.get(i).second); } private InternalWeightedCapEdge getInternalEdgeReversed(InternalWeightedCapEdge e) { return g[e.to].get(e.rev); } public WeightedCapEdge getEdge(int i) { int m = pos.size(); rangeCheck(i, 0, m); InternalWeightedCapEdge e = getInternalEdge(i); InternalWeightedCapEdge re = getInternalEdgeReversed(e); return new WeightedCapEdge(re.to, e.to, e.cap + re.cap, re.cap, e.cost); } public WeightedCapEdge[] getEdges() { WeightedCapEdge[] res = new WeightedCapEdge[pos.size()]; java.util.Arrays.setAll(res, this::getEdge); return res; } public FlowAndCost minCostMaxFlow(int s, int t) { return minCostFlow(s, t, INF); } public FlowAndCost minCostFlow(int s, int t, long flowLimit) { return minCostSlope(s, t, flowLimit).getLast(); } java.util.LinkedList<FlowAndCost> minCostSlope(int s, int t) { return minCostSlope(s, t, INF); } public java.util.LinkedList<FlowAndCost> minCostSlope(int s, int t, long flowLimit) { rangeCheck(s, 0, n); rangeCheck(t, 0, n); if (s == t) { throw new IllegalArgumentException( String.format("%d and %d is the same vertex.", s, t) ); } long[] dual = new long[n]; long[] dist = new long[n]; int[] pv = new int[n]; int[] pe = new int[n]; boolean[] vis = new boolean[n]; long flow = 0; long cost = 0, prev_cost = -1; java.util.LinkedList<FlowAndCost> result = new java.util.LinkedList<>(); result.addLast(new FlowAndCost(flow, cost)); while (flow < flowLimit) { if (!dualRef(s, t, dual, dist, pv, pe, vis)) break; long c = flowLimit - flow; for (int v = t; v != s; v = pv[v]) { c = Math.min(c, g[pv[v]].get(pe[v]).cap); } for (int v = t; v != s; v = pv[v]) { InternalWeightedCapEdge e = g[pv[v]].get(pe[v]); e.cap -= c; g[v].get(e.rev).cap += c; } long d = -dual[s]; flow += c; cost += c * d; if (prev_cost == d) { result.removeLast(); } result.addLast(new FlowAndCost(flow, cost)); prev_cost = cost; } return result; } private boolean dualRef(int s, int t, long[] dual, long[] dist, int[] pv, int[] pe, boolean[] vis) { java.util.Arrays.fill(dist, INF); java.util.Arrays.fill(pv, -1); java.util.Arrays.fill(pe, -1); java.util.Arrays.fill(vis, false); class State implements Comparable<State> { final long key; final int to; State(long key, int to) { this.key = key; this.to = to; } public int compareTo(State q) { return key > q.key ? 1 : -1; } }; java.util.PriorityQueue<State> pq = new java.util.PriorityQueue<>(); dist[s] = 0; pq.add(new State(0L, s)); while (pq.size() > 0) { int v = pq.poll().to; if (vis[v]) continue; vis[v] = true; if (v == t) break; for (int i = 0, deg = g[v].size(); i < deg; i++) { InternalWeightedCapEdge e = g[v].get(i); if (vis[e.to] || e.cap == 0) continue; long cost = e.cost - dual[e.to] + dual[v]; if (dist[e.to] - dist[v] > cost) { dist[e.to] = dist[v] + cost; pv[e.to] = v; pe[e.to] = i; pq.add(new State(dist[e.to], e.to)); } } } if (!vis[t]) { return false; } for (int v = 0; v < n; v++) { if (!vis[v]) continue; dual[v] -= dist[t] - dist[v]; } return true; } private void rangeCheck(int i, int minInlusive, int maxExclusive) { if (i < 0 || i >= maxExclusive) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for length %d", i, maxExclusive) ); } } private void nonNegativeCheck(long cap, java.lang.String attribute) { if (cap < 0) { throw new IllegalArgumentException( String.format("%s %d is negative.", attribute, cap) ); } } } class LazySegTree<S, F> { final int MAX; final int N; final int Log; final java.util.function.BinaryOperator<S> Op; final S E; final java.util.function.BiFunction<F, S, S> Mapping; final java.util.function.BinaryOperator<F> Composition; final F Id; final S[] Dat; final F[] Laz; @SuppressWarnings("unchecked") public LazySegTree(int n, java.util.function.BinaryOperator<S> op, S e, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BinaryOperator<F> composition, F id) { this.MAX = n; int k = 1; while (k < n) k <<= 1; this.N = k; this.Log = Integer.numberOfTrailingZeros(N); this.Op = op; this.E = e; this.Mapping = mapping; this.Composition = composition; this.Id = id; this.Dat = (S[]) new Object[N << 1]; this.Laz = (F[]) new Object[N]; java.util.Arrays.fill(Dat, E); java.util.Arrays.fill(Laz, Id); } public LazySegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BinaryOperator<F> composition, F id) { this(dat.length, op, e, mapping, composition, id); build(dat); } private void build(S[] dat) { int l = dat.length; System.arraycopy(dat, 0, Dat, N, l); for (int i = N - 1; i > 0; i--) { Dat[i] = Op.apply(Dat[i << 1 | 0], Dat[i << 1 | 1]); } } private void push(int k) { if (Laz[k] == Id) return; int lk = k << 1 | 0, rk = k << 1 | 1; Dat[lk] = Mapping.apply(Laz[k], Dat[lk]); Dat[rk] = Mapping.apply(Laz[k], Dat[rk]); if (lk < N) Laz[lk] = Composition.apply(Laz[k], Laz[lk]); if (rk < N) Laz[rk] = Composition.apply(Laz[k], Laz[rk]); Laz[k] = Id; } private void pushTo(int k) { for (int i = Log; i > 0; i--) push(k >> i); } private void pushTo(int lk, int rk) { for (int i = Log; i > 0; i--) { if (((lk >> i) << i) != lk) push(lk >> i); if (((rk >> i) << i) != rk) push(rk >> i); } } private void updateFrom(int k) { k >>= 1; while (k > 0) { Dat[k] = Op.apply(Dat[k << 1 | 0], Dat[k << 1 | 1]); k >>= 1; } } private void updateFrom(int lk, int rk) { for (int i = 1; i <= Log; i++) { if (((lk >> i) << i) != lk) { int lki = lk >> i; Dat[lki] = Op.apply(Dat[lki << 1 | 0], Dat[lki << 1 | 1]); } if (((rk >> i) << i) != rk) { int rki = (rk - 1) >> i; Dat[rki] = Op.apply(Dat[rki << 1 | 0], Dat[rki << 1 | 1]); } } } public void set(int p, S x) { exclusiveRangeCheck(p); p += N; pushTo(p); Dat[p] = x; updateFrom(p); } public S get(int p) { exclusiveRangeCheck(p); p += N; pushTo(p); return Dat[p]; } public S prod(int l, int r) { if (l > r) { throw new IllegalArgumentException( String.format("Invalid range: [%d, %d)", l, r) ); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); if (l == r) return E; l += N; r += N; pushTo(l, r); S sumLeft = E, sumRight = E; while (l < r) { if ((l & 1) == 1) sumLeft = Op.apply(sumLeft, Dat[l++]); if ((r & 1) == 1) sumRight = Op.apply(Dat[--r], sumRight); l >>= 1; r >>= 1; } return Op.apply(sumLeft, sumRight); } public S allProd() { return Dat[1]; } public void apply(int p, F f) { exclusiveRangeCheck(p); p += N; pushTo(p); Dat[p] = Mapping.apply(f, Dat[p]); updateFrom(p); } public void apply(int l, int r, F f) { if (l > r) { throw new IllegalArgumentException( String.format("Invalid range: [%d, %d)", l, r) ); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); if (l == r) return; l += N; r += N; pushTo(l, r); for (int l2 = l, r2 = r; l2 < r2;) { if ((l2 & 1) == 1) { Dat[l2] = Mapping.apply(f, Dat[l2]); if (l2 < N) Laz[l2] = Composition.apply(f, Laz[l2]); l2++; } if ((r2 & 1) == 1) { r2--; Dat[r2] = Mapping.apply(f, Dat[r2]); if (r2 < N) Laz[r2] = Composition.apply(f, Laz[r2]); } l2 >>= 1; r2 >>= 1; } updateFrom(l, r); } public int maxRight(int l, java.util.function.Predicate<S> g) { inclusiveRangeCheck(l); if (!g.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (l == MAX) return MAX; l += N; pushTo(l); S sum = E; do { l >>= Integer.numberOfTrailingZeros(l); if (!g.test(Op.apply(sum, Dat[l]))) { while (l < N) { push(l); l = l << 1; if (g.test(Op.apply(sum, Dat[l]))) { sum = Op.apply(sum, Dat[l]); l++; } } return l - N; } sum = Op.apply(sum, Dat[l]); l++; } while ((l & -l) != l); return MAX; } public int minLeft(int r, java.util.function.Predicate<S> g) { inclusiveRangeCheck(r); if (!g.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (r == 0) return 0; r += N; pushTo(r - 1); S sum = E; do { r--; while (r > 1 && (r & 1) == 1) r >>= 1; if (!g.test(Op.apply(Dat[r], sum))) { while (r < N) { push(r); r = r << 1 | 1; if (g.test(Op.apply(Dat[r], sum))) { sum = Op.apply(Dat[r], sum); r--; } } return r + 1 - N; } sum = Op.apply(Dat[r], sum); } while ((r & -r) != r); return 0; } private void exclusiveRangeCheck(int p) { if (p < 0 || p >= MAX) { throw new IndexOutOfBoundsException( String.format("Index %d is not in [%d, %d).", p, 0, MAX) ); } } private void inclusiveRangeCheck(int p) { if (p < 0 || p > MAX) { throw new IndexOutOfBoundsException( String.format("Index %d is not in [%d, %d].", p, 0, MAX) ); } } // **************** DEBUG **************** // private int indent = 6; public void setIndent(int newIndent) { this.indent = newIndent; } @Override public String toString() { return toSimpleString(); } private S[] simulatePushAll() { S[] simDat = java.util.Arrays.copyOf(Dat, 2 * N); F[] simLaz = java.util.Arrays.copyOf(Laz, 2 * N); for (int k = 1; k < N; k++) { if (simLaz[k] == Id) continue; int lk = k << 1 | 0, rk = k << 1 | 1; simDat[lk] = Mapping.apply(simLaz[k], simDat[lk]); simDat[rk] = Mapping.apply(simLaz[k], simDat[rk]); if (lk < N) simLaz[lk] = Composition.apply(simLaz[k], simLaz[lk]); if (rk < N) simLaz[rk] = Composition.apply(simLaz[k], simLaz[rk]); simLaz[k] = Id; } return simDat; } public String toDetailedString() { return toDetailedString(1, 0, simulatePushAll()); } private String toDetailedString(int k, int sp, S[] dat) { if (k >= N) return indent(sp) + dat[k]; String s = ""; s += toDetailedString(k << 1 | 1, sp + indent, dat); s += "\n"; s += indent(sp) + dat[k]; s += "\n"; s += toDetailedString(k << 1 | 0, sp + indent, dat); return s; } private static String indent(int n) { StringBuilder sb = new StringBuilder(); while (n --> 0) sb.append(' '); return sb.toString(); } public String toSimpleString() { S[] dat = simulatePushAll(); StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < N; i++) { sb.append(dat[i + N]); if (i < N - 1) sb.append(',').append(' '); } sb.append(']'); return sb.toString(); } } class FenwickTree{ private int _n; private long[] data; public FenwickTree(int n){ this._n = n; data = new long[n]; } /** * @verified https://atcoder.jp/contests/practice2/tasks/practice2_b * @submission https://atcoder.jp/contests/practice2/submissions/16580495 */ public FenwickTree(long[] data) { this(data.length); build(data); } public void set(int p, long x){ add(p, x - get(p)); } public void add(int p, long x){ assert(0<=p && p<_n); p++; while(p<=_n){ data[p-1] += x; p += p&-p; } } public long sum(int l, int r){ assert(0<=l && l<=r && r<=_n); return sum(r)-sum(l); } public long get(int p){ return sum(p, p+1); } private long sum(int r){ long s = 0; while(r>0){ s += data[r-1]; r -= r&-r; } return s; } private void build(long[] dat) { System.arraycopy(dat, 0, data, 0, _n); for (int i=1; i<=_n; i++) { int p = i+(i&-i); if(p<=_n){ data[p-1] += data[i-1]; } } } } class MaxFlow { private static final class InternalCapEdge { final int to; final int rev; long cap; InternalCapEdge(int to, int rev, long cap) { this.to = to; this.rev = rev; this.cap = cap; } } public static final class CapEdge { public final int from, to; public final long cap, flow; CapEdge(int from, int to, long cap, long flow) { this.from = from; this.to = to; this.cap = cap; this.flow = flow; } @Override public boolean equals(Object o) { if (o instanceof CapEdge) { CapEdge e = (CapEdge) o; return from == e.from && to == e.to && cap == e.cap && flow == e.flow; } return false; } } private static final class IntPair { final int first, second; IntPair(int first, int second) { this.first = first; this.second = second; } } static final long INF = Long.MAX_VALUE; private final int n; private final java.util.ArrayList<IntPair> pos; private final java.util.ArrayList<InternalCapEdge>[] g; @SuppressWarnings("unchecked") public MaxFlow(int n) { this.n = n; this.pos = new java.util.ArrayList<>(); this.g = new java.util.ArrayList[n]; for (int i = 0; i < n; i++) { this.g[i] = new java.util.ArrayList<>(); } } public int addEdge(int from, int to, long cap) { rangeCheck(from, 0, n); rangeCheck(to, 0, n); nonNegativeCheck(cap, "Capacity"); int m = pos.size(); pos.add(new IntPair(from, g[from].size())); int fromId = g[from].size(); int toId = g[to].size(); if (from == to) toId++; g[from].add(new InternalCapEdge(to, toId, cap)); g[to].add(new InternalCapEdge(from, fromId, 0L)); return m; } private InternalCapEdge getInternalEdge(int i) { return g[pos.get(i).first].get(pos.get(i).second); } private InternalCapEdge getInternalEdgeReversed(InternalCapEdge e) { return g[e.to].get(e.rev); } public CapEdge getEdge(int i) { int m = pos.size(); rangeCheck(i, 0, m); InternalCapEdge e = getInternalEdge(i); InternalCapEdge re = getInternalEdgeReversed(e); return new CapEdge(re.to, e.to, e.cap + re.cap, re.cap); } public CapEdge[] getEdges() { CapEdge[] res = new CapEdge[pos.size()]; java.util.Arrays.setAll(res, this::getEdge); return res; } public void changeEdge(int i, long newCap, long newFlow) { int m = pos.size(); rangeCheck(i, 0, m); nonNegativeCheck(newCap, "Capacity"); if (newFlow > newCap) { throw new IllegalArgumentException( String.format("Flow %d is greater than the capacity %d.", newCap, newFlow) ); } InternalCapEdge e = getInternalEdge(i); InternalCapEdge re = getInternalEdgeReversed(e); e.cap = newCap - newFlow; re.cap = newFlow; } public long maxFlow(int s, int t) { return flow(s, t, INF); } public long flow(int s, int t, long flowLimit) { rangeCheck(s, 0, n); rangeCheck(t, 0, n); long flow = 0L; int[] level = new int[n]; int[] que = new int[n]; int[] iter = new int[n]; while (flow < flowLimit) { bfs(s, t, level, que); if (level[t] < 0) break; java.util.Arrays.fill(iter, 0); while (flow < flowLimit) { long d = dfs(t, s, flowLimit - flow, iter, level); if (d == 0) break; flow += d; } } return flow; } private void bfs(int s, int t, int[] level, int[] que) { java.util.Arrays.fill(level, -1); int hd = 0, tl = 0; que[tl++] = s; level[s] = 0; while (hd < tl) { int u = que[hd++]; for (InternalCapEdge e : g[u]) { int v = e.to; if (e.cap == 0 || level[v] >= 0) continue; level[v] = level[u] + 1; if (v == t) return; que[tl++] = v; } } } private long dfs(int cur, int s, long flowLimit, int[] iter, int[] level) { if (cur == s) return flowLimit; long res = 0; int curLevel = level[cur]; for (int itMax = g[cur].size(); iter[cur] < itMax; iter[cur]++) { int i = iter[cur]; InternalCapEdge e = g[cur].get(i); InternalCapEdge re = getInternalEdgeReversed(e); if (curLevel <= level[e.to] || re.cap == 0) continue; long d = dfs(e.to, s, Math.min(flowLimit - res, re.cap), iter, level); if (d <= 0) continue; e.cap += d; re.cap -= d; res += d; if (res == flowLimit) break; } return res; } public boolean[] minCut(int s) { rangeCheck(s, 0, n); boolean[] visited = new boolean[n]; int[] stack = new int[n]; int ptr = 0; stack[ptr++] = s; visited[s] = true; while (ptr > 0) { int u = stack[--ptr]; for (InternalCapEdge e : g[u]) { int v = e.to; if (e.cap > 0 && !visited[v]) { visited[v] = true; stack[ptr++] = v; } } } return visited; } private void rangeCheck(int i, int minInclusive, int maxExclusive) { if (i < 0 || i >= maxExclusive) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for length %d", i, maxExclusive) ); } } private void nonNegativeCheck(long cap, String attribute) { if (cap < 0) { throw new IllegalArgumentException( String.format("%s %d is negative.", attribute, cap) ); } } } 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.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.util.function.*; import java.util.stream.IntStream; public class Main implements Runnable{ public static void main(String[] args) { new Thread(null,new Main(),"",16*1024*1024).start(); } public void run(){ Solver.SOLVE(); } } class UnionFind { private int[] roots; public UnionFind(int n){ roots = new int[n]; for (int i = 0; i < n; i++) { roots[i] = i; } } public int root(int x){ if(roots[x] == x){ return x; } return roots[x] = root(roots[x]); } public void unite(int x,int y){ int rx = root(x); int ry = root(y); if(rx == ry){ return; } roots[rx] = ry; } public boolean same(int x,int y){ int rx = root(x); int ry = root(y); return rx == ry; } } class DSU { private int n; private int[] parentOrSize; public DSU(int n) { this.n = n; this.parentOrSize = new int[n]; java.util.Arrays.fill(parentOrSize, -1); } int merge(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); int x = leader(a); int y = leader(b); if (x == y) return x; if (-parentOrSize[x] < -parentOrSize[y]) { int tmp = x; x = y; y = tmp; } parentOrSize[x] += parentOrSize[y]; parentOrSize[y] = x; return x; } boolean same(int a, int b) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("a=" + a); if (!(0 <= b && b < n)) throw new IndexOutOfBoundsException("b=" + b); return leader(a) == leader(b); } int leader(int a) { if (parentOrSize[a] < 0) { return a; } else { parentOrSize[a] = leader(parentOrSize[a]); return parentOrSize[a]; } } int size(int a) { if (!(0 <= a && a < n)) throw new IndexOutOfBoundsException("" + a); return -parentOrSize[leader(a)]; } ArrayList<ArrayList<Integer>> groups() { int[] leaderBuf = new int[n]; int[] groupSize = new int[n]; for (int i = 0; i < n; i++) { leaderBuf[i] = leader(i); groupSize[leaderBuf[i]]++; } ArrayList<ArrayList<Integer>> result = new ArrayList<>(n); for (int i = 0; i < n; i++) { result.add(new ArrayList<>(groupSize[i])); } for (int i = 0; i < n; i++) { result.get(leaderBuf[i]).add(i); } result.removeIf(ArrayList::isEmpty); return result; } } class PairL implements Comparable<PairL>, Comparator<PairL> { public long x,y; public PairL(long x,long y) { this.x = x; this.y = y; } public void swap(){ long t = x; x = y; y = t; } @Override public int compare(PairL o1, PairL o2) { return o1.compareTo(o2); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairL pairl = (PairL) o; return x == pairl.x && y == pairl.y; } @Override public int hashCode() { return Objects.hash(x, y); } public PairL add(PairL p){ return new PairL(x+p.x,y+p.y); } @Override public int compareTo(PairL o) { return Long.compare(x,o.x); } } class PairI implements Comparable<PairI>, Comparator<PairI> { public int x,y; public PairI(int x,int y) { this.x = x; this.y = y; } public void swap(){ int t = x; x = y; y = t; } @Override public int compare(PairI o1, PairI o2) { if(o1.x == o2.x){ return Integer.compare(o1.y,o2.y); } return Integer.compare(o1.x,o2.x); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairI pairI = (PairI) o; return x == pairI.x && y == pairI.y; } @Override public int hashCode() { return Objects.hash(x, y); } @Override public int compareTo(PairI o) { if(x == o.x){ return Integer.compare(y,o.y); } return Integer.compare(x,o.x); } public PairI add(PairI p){ return new PairI(x+p.x,y+p.y); } public PairI sub(PairI p){ return new PairI(x-p.x,y-p.y); } public PairI addG(PairI p,int h,int w) { int x = this.x + p.x; int y = this.y + p.y; if(0 <= x&&x < w&&0 <= y&&y < h){ return new PairI(x,y); } return null; } } class PairISet{ int x,y; PairISet(int x,int y){ this.x = x; this.y = y; } @Override public int hashCode() { return Objects.hash(x, y); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PairI pairI = (PairI) o; return (x == pairI.x && y == pairI.y)||(x == pairI.y && y == pairI.x); } } class Line{ //ax+bx+c=0 long a,b,c; public Line(int x0, int y0, int x1, int y1) { long dx = x1-x0; long dy = y1-y0; long gcd = Solver.gcd(dx,dy); dx/=gcd; dy/=gcd; if(dx < 0){ dx=-dx; dy=-dy; } if(dx == 0 && dy < 0){ dy=-dy; } a = dy; b = -dx; c = dx*y0-dy*x0; } public boolean onLine(int x,int y){ return a*x + b*y + c == 0; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Line line = (Line) o; return a == line.a && b == line.b && c == line.c; } @Override public int hashCode() { return Objects.hash(a, b, c); } } class Dist extends PairI{ int d; public Dist(int x,int y,int d){ super(x,y); this.d = d; } public Dist addG(PairI p,int h,int w) { int x = this.x + p.x; int y = this.y + p.y; if(0 <= x&&x < w&&0 <= y&&y < h){ return new Dist(x,y,d+1); } return null; } } class Tuple implements Comparable<Tuple>{ public int x,y,z; public Tuple(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Tuple three = (Tuple) o; return x == three.x && y == three.y && z == three.z; } @Override public int hashCode() { return Objects.hash(x, y, z); } @Override public int compareTo(Tuple o) { if(x == o.x){ return Integer.compare(y,o.y); } return Integer.compare(x,o.x); } } class Edge implements Comparable<Edge>{ public int from; public int to; public int name; public long d; public Edge(int to){ this.to = to; } public Edge(int to, long d){ this.to = to; this.d = d; } public Edge setName(int name){ this.name = name; return this; } public Edge(int from, int to, long d){ this.to = to; this.from = from; this.d = d; } @Override public int compareTo(Edge o) { return Long.compare(d,o.d); } } class PairC{ char a,b; public PairC(char a, char b){ this.a = a; this.b = b; } } class IB{ int i; boolean b; IB(int i,boolean b){ this.i = i; this.b = b; } } class CI{ char c; int i; CI(char c,int i){ this.c = c; this.i = i; } } class SortedMultiSet extends TreeMap<Long,Integer>{ public void add(long a){ put(a,getOrDefault(a,0)+1); } public void remove(long a){ if(get(a) == 1){ super.remove(a); }else{ put(a,get(a)-1); } } public void lower(long a){ } } class MultiSet extends HashMap<Integer,Integer>{ public void add(int a){ put(a,getOrDefault(a,0)+1); } public void remove(int a){ if(get(a) == 1){ super.remove(a); }else{ put(a,get(a)-1); } } public boolean contains(int a){ return containsKey(a); } } class PP{ PairI s,t; int name; public PP(PairI s, PairI t,int name) { this.s = s; this.t = t; this.name = name; } } class Plane{ ArrayList<PP> up,down; public Plane(){ up = new ArrayList<>(); down = new ArrayList<>(); } } class Matrix{ int row; int column; int[][] nums; public Matrix(int row,int column){ this.row = row; this.column = column; nums = new int[row][column]; } } class SquareMatrix{ int size; long[][] nums; public SquareMatrix(int size){ this.size = size; nums = new long[size][size]; } public SquareMatrix(long[][] nums){ size = nums.length; this.nums = new long[size][size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { this.nums[i][j] = nums[i][j]; } } } public static SquareMatrix identityMatrix(int size){ long[][] mat = new long[size][size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if(i == j){ mat[i][j] = 1; } } } return new SquareMatrix(mat); } public SquareMatrix mul(SquareMatrix m){ if(m.size != size){ throw new IllegalArgumentException(); } SquareMatrix ans = new SquareMatrix(size); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { ans.nums[i][k] += nums[i][j]*m.nums[j][k]; } } } return ans; } public SquareMatrix modMul(SquareMatrix m,long mod){ if(m.size != size){ throw new IllegalArgumentException(); } SquareMatrix ans = new SquareMatrix(size); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { for (int k = 0; k < size; k++) { ans.nums[i][k] += nums[i][j]*m.nums[j][k]; ans.nums[i][k]%=mod; } } } return ans; } public long[] mulVec(long[] vec){ if(vec.length != size){ throw new IllegalArgumentException(); } long[] ans = new long[size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { ans[i] += vec[j]*nums[i][j]; } } return ans; } public long[] modMulVec(long[] vec,long mod){ if(vec.length != size){ throw new IllegalArgumentException(); } long[] ans = new long[size]; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { ans[i] += vec[j]*nums[i][j]; ans[i]%=mod; } } return ans; } public static SquareMatrix pow(SquareMatrix base,long exp){ SquareMatrix ans = identityMatrix(base.size); while (exp > 0){ if ((exp & 1) == 1) { ans = base.mul(ans); } base = base.mul(base); exp >>= 1; } return ans; } public SquareMatrix pow(long exp){ return pow(this,exp); } public static SquareMatrix modPow(SquareMatrix base,long exp,long mod){ SquareMatrix ans = identityMatrix(base.size); while (exp > 0){ if ((exp & 1) == 1) { ans = base.modMul(ans,mod); } base = base.modMul(base,mod); exp >>= 1; } return ans; } public SquareMatrix modPow(long exp,long mod){ return modPow(this,exp,mod); } } class Fraction implements Comparable<Fraction>{ int de,num; int name; public Fraction(int de, int num) { this.de = de; this.num = num; } @Override public int compareTo(Fraction o) { long a = (long) de * o.num; long b = (long) num* o.de; return Long.compare(a,b); } } class Solver { public static final int MOD1 = 1000000007; public static final int MOD9 = 998244353; public static Scanner sc = new Scanner(System.in); public static final int inf = 2000000000; public static final int ninf = -inf; public static final char[] alpha = "abcdefghijklmnopqrstuvwxyz".toCharArray(); public static final char[] ALPHA = "abcdefghijklmnopqrstuvwxyz".toUpperCase().toCharArray(); public static FastScanner fs = new FastScanner(); public static PrintWriter out = new PrintWriter(System.out); public static final PairI[] move = new PairI[]{new PairI(1,0),new PairI(0,1),new PairI(-1,0),new PairI(0,-1)}; public static final PairI[] move8 = new PairI[]{ new PairI(1,0),new PairI(0,1),new PairI(-1,0),new PairI(0,-1), new PairI(1,1),new PairI(-1,1),new PairI(1,-1),new PairI(-1,-1) }; public static void solve() { int n = rI(); int[] c = rIv(9); int min = min(c); int minidx = -1; for (int i = 0; i < 9; i++) { if(c[i] == min){ minidx = i; } } int times = n/min; if(times == 0) { oI(0); return; } int[] ans = new int[times]; Arrays.fill(ans,minidx+1); int left = n%min; int[] nc = new int[9-minidx]; for (int i = 0; i < 9 - minidx; i++) { nc[i] = c[i+minidx] - min; } int idx = 0; out:for (int i = 8-minidx; i > 0; i--) { if(left == 0) break; int time = left/nc[i]; left = left%nc[i]; while (time-->0){ ans[idx] = i+minidx+1; idx++; if(idx == times){ break out; } } } StringBuilder an = new StringBuilder(); for (int i = 0; i < times; i++) { an.append(ans[i]); } oS(an.toString()); } static char toLower(char a){ return String.valueOf(a).toLowerCase().charAt(0); } static char toUpper(char a){ return String.valueOf(a).toUpperCase().charAt(0); } static int nand(int a,int b){ if(a == 1&&b == 1){ return 0; } return 1; } static int standingBits(long n){ String bits = toBits(n); int ans = 0; for (int i = 0; i < bits.length(); i++) { if(bits.charAt(i) == '1'){ ans++; } } return ans; } static boolean contain(String s,char c){ for (int i = 0; i < s.length(); i++) { if(s.charAt(i) == c){ return true; } } return false; } static String toBits(long n){ StringBuilder ans = new StringBuilder(); while (n > 0){ ans.append(n%2); n/=2; } return ans.reverse().toString(); } static long toLong(String anss){ long ansi = 0; for (int i = 0; i < anss.length(); i++) { if(anss.charAt(i) == '1'){ ansi += (1L<<(anss.length()-1-i)); } } return ansi; } static int perfectPowNum(long n){ int res = 0; double range = Math.log(n)/Math.log(2); range++; for (int i = 2; i < range; i++) { long a = (long) Math.pow(n,1d/i); if(pow(a,i) == n||pow(a+1,i)==n){ res++; } } return res; } static boolean[] eratosthenes(int n){ boolean[] res = new boolean[n+1]; for (int i = 2; i <= n; i++) { res[i] = true; } for (int i = 2; i <= n; i++) { if(res[i]){ int k = i*2; while (k <= n){ res[k] = false; k+=i; } } } return res; } static BitSet and(BitSet set1,BitSet set2){ BitSet ans = (BitSet) set1.clone(); ans.and(set2); return ans; } static BitSet or(BitSet set1,BitSet set2){ BitSet ans = (BitSet) set1.clone(); ans.or(set2); return ans; } static BitSet xor(BitSet set1,BitSet set2){ BitSet ans = (BitSet) set1.clone(); ans.xor(set2); return ans; } static BitSet toBitset(long n){ return BitSet.valueOf(new long[]{n}); } static long toLong(BitSet set){ if(set.length() > 63) { throw new IllegalArgumentException(); } if(set.length() == 0){ return 0; } return set.toLongArray()[0]; } static int deg(long x){ return String.valueOf(x).length(); } static int nthdeg(long x,int d){ x/=pow(10,d); return (int)(x%10); } static boolean isPalindrome(int a,int b,String s){ int dif = b-a; boolean ok = true; for (int i = 0; i < dif; i++) { if (s.charAt(i + a) != s.charAt(b - i)) { ok = false; break; } } return ok; } static int intValue(char c){ return Integer.parseInt(String.valueOf(c)); } public static int toIntC(char c){ for (int i = 0; i < ALPHA.length; i++) { if(c == ALPHA[i]){ return i; } } throw new IllegalArgumentException("not an alphabet"); } public static int toInt(char c){ for (int i = 0; i < alpha.length; i++) { if(c == alpha[i]){ return i; } } throw new IllegalArgumentException("not an alphabet"); } public static void reverse(int[] a){ int[] tmp = a.clone(); for (int i = 0; i < a.length; i++) { a[i] = tmp[a.length - 1 - i]; } } public static int[] compress(int[] a){ int[] ans = new int[a.length]; int[] b = erase(a); Arrays.sort(b); for (int i = 0; i < a.length; i++) { ans[i] = lower(b,a[i]); } return ans; } public static int lower(int[] a,int x){ int low = 0, high = a.length; int mid; while (low < high) { mid = low + (high - low) / 2; if (x <= a[mid]) { high = mid; } else { low = mid + 1; } } if (low < a.length && a[low] < x) { low++; } return low; } public static int lower(long[] a,long x) { int low = 0, high = a.length; int mid; while (low < high) { mid = low + (high - low) / 2; if (x <= a[mid]) { high = mid; } else { low = mid + 1; } } if (low < a.length && a[low] < x) { low++; } return low; } public static <T extends Comparable<? super T>> int lower(T[] a,T x){ int low = 0, high = a.length; int mid; while (low < high) { mid = low + (high - low) / 2; if (x.compareTo(a[mid]) < 1) { high = mid; } else { low = mid + 1; } } if (low < a.length && x.compareTo(a[low]) > 0) { low++; } return low; } public static int upper(int[] a,int x){ int low = 0, high = a.length; int mid; while (low < high && low != a.length) { mid = low + (high - low) / 2; if (x >= a[mid]) { low = mid + 1; } else { high = mid; } } return low; } public static int upper(long[] a,long x){ int low = 0, high = a.length; int mid; while (low < high && low != a.length) { mid = low + (high - low) / 2; if (x >= a[mid]) { low = mid + 1; } else { high = mid; } } return low; } public static <T extends Comparable<? super T>> int upper(T[] a,T x){ int low = 0, high = a.length; int mid; while (low < high && low != a.length) { mid = low + (high - low) / 2; if (x.compareTo(a[mid]) > -1) { low = mid + 1; } else { high = mid; } } return low; } public static int[] erase(int[] a){ HashSet<Integer> used = new HashSet<>(); ArrayList<Integer> ans = new ArrayList<>(); for (int i = 0; i < a.length; i++) { if(!used.contains(a[i])){ used.add(a[i]); ans.add(a[i]); } } return convI(ans); } public static int abs(int a){ return Math.abs(a); } public static long abs(long a){ return Math.abs(a); } public static int max(int a,int b){ return Math.max(a,b); } public static int max(int... a){ int max = Integer.MIN_VALUE; for (int i = 0; i < a.length; i++) { max = max(a[i],max); } return max; } public static long max(long a,long b){ return Math.max(a,b); } public static long max(long... a){ long max = Long.MIN_VALUE; for (int i = 0; i < a.length; i++) { max = max(a[i],max); } return max; } public static int min(int a,int b){ return Math.min(a,b); } public static int min(int... a){ int min = Integer.MAX_VALUE; for (int i = 0; i < a.length; i++) { min = min(a[i],min); } return min; } public static long min(long a,long b){ return Math.min(a, b); } public static long min(long... a){ long min = Long.MAX_VALUE; for (int i = 0; i < a.length; i++) { min = min(a[i],min); } return min; } public static final class MC { private final int mod; public MC(final int mod) { this.mod = mod; } public long mod(long x) { x %= mod; if (x < 0) { x += mod; } return x; } public long add(final long a, final long b) { return mod(mod(a) + mod(b)); } public long add(final long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = add(ans,a[i]); } return mod(ans); } public long mul(final long a, final long b) { return mod(mod(a) * mod(b)); } public long mul(final long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = mul(ans,a[i]); } return mod(ans); } public long div(final long numerator, final long denominator) { return mod(numerator * inverse(denominator)); } public long power(long base, long exp) { long ret = 1; base %= mod; while (exp > 0) { if ((exp & 1) == 1) { ret = mul(ret, base); } base = mul(base, base); exp >>= 1; } return ret; } public long inverse(final long x) { return power(x, mod - 2); } public long fact(final int n) { return product(1, n); } public long permutation(int n,int r){ return product(n-r+1,n); } public long product(final int start, final int end) { long result = 1; for (int i = start; i <= end; i++) { result *= i; result %= mod; } return result; } public long combination(final int n, int r) { if (r > n) { return 0; } r = min(r,n-r); return div(product(n - r + 1, n), fact(r)); } } public static long pow(long x,long n){ long ans = 1L; long tmp = x; while (true){ if(n < 1L){ break; } if(n % 2L == 1L){ ans*=tmp; } tmp *=tmp; n = n >> 1; } return ans; } public static long modPow(long x,long n,long m){ long ans = 1L; long tmp = x%m; while (true){ if(n < 1L){ break; } if(n % 2L == 1L){ ans*=tmp; ans%=m; } tmp *=tmp; tmp%=m; n = n >> 1; } return ans; } public static int gcd(int a,int b){ if(b == 0) return a; else return gcd(b,a%b); } public static long gcd(long a,long b){ if(b == 0) return a; else return gcd(b,a%b); } public static int gcd(int... a){ int ans = a[0]; for (int i = 1; i < a.length; i++) { ans = gcd(ans,a[i]); } return ans; } public static long gcd(long... a){ long ans = a[0]; for (int i = 1; i < a.length; i++) { ans = gcd(ans,a[i]); } return ans; } public static long lcm(int a,int b){ return (long) a / gcd(a, b) * b; } public static long lcm(long a,long b){ return a / gcd(a,b) * b; } public static boolean isPrime(long x){ if(x < 2) return false; else if(x == 2) return true; if(x%2 == 0) return false; for(long i = 3; i*i <= x; i+= 2){ if(x%i == 0) return false; } return true; } public static int rI() { return fs.nextInt(); } public static int[] rIv(int length) { int[] res = new int[length]; for (int i = 0; i < length; i++) { res[i] = fs.nextInt(); } return res; } public static String rS() { return fs.next(); } public static String[] rSv(int length) { String[] res = new String[length]; for (int i = 0; i < length; i++) res[i] = fs.next(); return res; } public static long rL() { return fs.nextLong(); } public static long[] rLv(int length) { long[] res = new long[length]; for (int i = 0; i < length; i++) res[i] = fs.nextLong(); return res; } public static double rD(){ return fs.nextDouble(); } public static double[] rDv(int length){ double[] res = new double[length]; for (int i = 0; i < length; i++) res[i] = rD(); return res; } public static String aiS(int[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String alS(long[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String adS(double[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String acS(char[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String asS(String[] a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.length; i++) { if(i != 0){ ans.append(' '); } ans.append(a[i]); } return ans.toString(); } public static String liS(ArrayList<Integer> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String liS(ArrayList<Integer> a, IntUnaryOperator o){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(o.applyAsInt(a.get(i))); } return ans.toString(); } public static String llS(ArrayList<Long> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String llS(ArrayList<Long> a, LongUnaryOperator o){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(o.applyAsLong(a.get(i))); } return ans.toString(); } public static String ldS(ArrayList<Double> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String lcS(ArrayList<Character> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static String lsS(ArrayList<String> a){ StringBuilder ans = new StringBuilder(); for (int i = 0; i < a.size(); i++) { if(i != 0){ ans.append(' '); } ans.append(a.get(i)); } return ans.toString(); } public static void nL(){ out.println(); } public static void oI(int a) { out.println(a); } public static void onI(int a){ out.print(a); } public static void oIv(int... a) { oS(aiS(a)); } public static void oS(String s) { out.println(s); } public static void onS(String s) { out.print(s); } public static void oSv(String[] a) { oS(asS(a)); } public static void oL(long l) { out.println(l); } public static void onL(long l) { out.print(l); } public static void oLv(long... a) { oS(alS(a)); } public static void oD(double d){ out.println(d); } public static void onD(double d){ out.print(d); } public static void oDv(double... d){ oS(adS(d)); } public static void oC(char c){ out.println(c); } public static void onC(char c){ out.print(c); } public static void oCv(char... c){ oS(acS(c)); } public static void fl(){ out.flush(); } public static void yes_no(boolean yes){ if(yes){ oS("Yes"); return; } oS("No"); } public static int fact(int num) { if (num == 0) { return 1; } else if (num == 1) { return 1; } else if (num < 0) { throw new IllegalArgumentException("factorial should be bigger than 0"); } return num * fact(num - 1); } public static int[] convI(ArrayList<Integer> list) { int[] res = new int[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static long[] convL(ArrayList<Long> list) { long[] res = new long[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static String[] convS(ArrayList<String> list) { String[] res = new String[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public static ArrayList<Integer> convI(int[] vec) { ArrayList<Integer> list = new ArrayList<>(); for (int i : vec) list.add(i); return list; } public static ArrayList<Long> convL(long[] vec) { ArrayList<Long> list = new ArrayList<>(); for (long i : vec) list.add(i); return list; } public static ArrayList<String> convS(String[] vec) { return new ArrayList<>(Arrays.asList(vec)); } public static ArrayList<ArrayList<Integer>> permutation(int a) { int[] list = new int[a]; for (int i = 0; i < a; i++) { list[i] = i; } return permutation(list); } public static ArrayList<ArrayList<Integer>> permutation1(int a) { int[] list = new int[a]; for (int i = 0; i < a; i++) { list[i] = i+1; } return permutation(list); } public static ArrayList<ArrayList<Integer>> permutation(int[] seed) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); int[] perm = new int[seed.length]; boolean[] used = new boolean[seed.length]; buildPerm(seed, perm, used, 0,res); return res; } private static void buildPerm(int[] seed, int[] perm, boolean[] used, int index,ArrayList<ArrayList<Integer>> res) { if (index == seed.length) { res.add(convI(perm)); return; } for (int i = 0; i < seed.length; i++) { if (used[i]) continue; perm[index] = seed[i]; used[i] = true; buildPerm(seed, perm, used, index + 1,res); used[i] = false; } } public static ArrayList<ArrayList<String>> permutation(String[] seed) { ArrayList<ArrayList<String>> res = new ArrayList<>(); String[] perm = new String[seed.length]; boolean[] used = new boolean[seed.length]; buildPerm(seed, perm, used, 0,res); return res; } private static void buildPerm(String[] seed, String[] perm, boolean[] used, int index,ArrayList<ArrayList<String>> res) { if (index == seed.length) { res.add(convS(perm)); return; } for (int i = 0; i < seed.length; i++) { if (used[i]) continue; perm[index] = seed[i]; used[i] = true; buildPerm(seed, perm, used, index + 1,res); used[i] = false; } } public static void swap(int[] a,int i1,int i2){ int t = a[i1]; a[i1] = a[i2]; a[i2] = t; } public static void swap(char[] a,int i1,int i2){ char t = a[i1]; a[i1] = a[i2]; a[i2] = t; } public static void SOLVE(){ solve(); out.flush(); } } class SegTree<S> { final int MAX; final int N; final java.util.function.BinaryOperator<S> op; final S E; final S[] data; @SuppressWarnings("unchecked") public SegTree(int n, java.util.function.BinaryOperator<S> op, S e) { this.MAX = n; int k = 1; while (k < n) k <<= 1; this.N = k; this.E = e; this.op = op; this.data = (S[]) new Object[N << 1]; java.util.Arrays.fill(data, E); } public SegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e) { this(dat.length, op, e); build(dat); } private void build(S[] dat) { int l = dat.length; System.arraycopy(dat, 0, data, N, l); for (int i = N - 1; i > 0; i--) { data[i] = op.apply(data[i << 1 | 0], data[i << 1 | 1]); } } public void set(int p, S x) { exclusiveRangeCheck(p); data[p += N] = x; p >>= 1; while (p > 0) { data[p] = op.apply(data[p << 1 | 0], data[p << 1 | 1]); p >>= 1; } } public S get(int p) { exclusiveRangeCheck(p); return data[p + N]; } public S prod(int l, int r) { if (l > r) { throw new IllegalArgumentException( String.format("Invalid range: [%d, %d)", l, r) ); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); S sumLeft = E; S sumRight = E; l += N; r += N; while (l < r) { if ((l & 1) == 1) sumLeft = op.apply(sumLeft, data[l++]); if ((r & 1) == 1) sumRight = op.apply(data[--r], sumRight); l >>= 1; r >>= 1; } return op.apply(sumLeft, sumRight); } public S allProd() { return data[1]; } public int maxRight(int l, java.util.function.Predicate<S> f) { inclusiveRangeCheck(l); if (!f.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (l == MAX) return MAX; l += N; S sum = E; do { l >>= Integer.numberOfTrailingZeros(l); if (!f.test(op.apply(sum, data[l]))) { while (l < N) { l = l << 1; if (f.test(op.apply(sum, data[l]))) { sum = op.apply(sum, data[l]); l++; } } return l - N; } sum = op.apply(sum, data[l]); l++; } while ((l & -l) != l); return MAX; } public int minLeft(int r, java.util.function.Predicate<S> f) { inclusiveRangeCheck(r); if (!f.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (r == 0) return 0; r += N; S sum = E; do { r--; while (r > 1 && (r & 1) == 1) r >>= 1; if (!f.test(op.apply(data[r], sum))) { while (r < N) { r = r << 1 | 1; if (f.test(op.apply(data[r], sum))) { sum = op.apply(data[r], sum); r--; } } return r + 1 - N; } sum = op.apply(data[r], sum); } while ((r & -r) != r); return 0; } private void exclusiveRangeCheck(int p) { if (p < 0 || p >= MAX) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for the range [%d, %d).", p, 0, MAX) ); } } private void inclusiveRangeCheck(int p) { if (p < 0 || p > MAX) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for the range [%d, %d].", p, 0, MAX) ); } } // **************** DEBUG **************** // private int indent = 6; public void setIndent(int newIndent) { this.indent = newIndent; } @Override public String toString() { return toSimpleString(); } public String toDetailedString() { return toDetailedString(1, 0); } private String toDetailedString(int k, int sp) { if (k >= N) return indent(sp) + data[k]; String s = ""; s += toDetailedString(k << 1 | 1, sp + indent); s += "\n"; s += indent(sp) + data[k]; s += "\n"; s += toDetailedString(k << 1 | 0, sp + indent); return s; } private static String indent(int n) { StringBuilder sb = new StringBuilder(); while (n --> 0) sb.append(' '); return sb.toString(); } public String toSimpleString() { StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < N; i++) { sb.append(data[i + N]); if (i < N - 1) sb.append(',').append(' '); } sb.append(']'); return sb.toString(); } } /** * @verified * - https://atcoder.jp/contests/practice2/tasks/practice2_e * - http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_6_B */ class MinCostFlow { private static final class InternalWeightedCapEdge { final int to, rev; long cap; final long cost; InternalWeightedCapEdge(int to, int rev, long cap, long cost) { this.to = to; this.rev = rev; this.cap = cap; this.cost = cost; } } public static final class WeightedCapEdge { public final int from, to; public final long cap, flow, cost; WeightedCapEdge(int from, int to, long cap, long flow, long cost) { this.from = from; this.to = to; this.cap = cap; this.flow = flow; this.cost = cost; } @Override public boolean equals(Object o) { if (o instanceof WeightedCapEdge) { WeightedCapEdge e = (WeightedCapEdge) o; return from == e.from && to == e.to && cap == e.cap && flow == e.flow && cost == e.cost; } return false; } } private static final class IntPair { final int first, second; IntPair(int first, int second) { this.first = first; this.second = second; } } public static final class FlowAndCost { public final long flow, cost; FlowAndCost(long flow, long cost) { this.flow = flow; this.cost = cost; } @Override public boolean equals(Object o) { if (o instanceof FlowAndCost) { FlowAndCost c = (FlowAndCost) o; return flow == c.flow && cost == c.cost; } return false; } } static final long INF = Long.MAX_VALUE; private final int n; private final java.util.ArrayList<IntPair> pos; public final java.util.ArrayList<InternalWeightedCapEdge>[] g; @SuppressWarnings("unchecked") public MinCostFlow(int n) { this.n = n; this.pos = new java.util.ArrayList<>(); this.g = new java.util.ArrayList[n]; for (int i = 0; i < n; i++) { this.g[i] = new java.util.ArrayList<>(); } } public int addEdge(int from, int to, long cap, long cost) { rangeCheck(from, 0, n); rangeCheck(to, 0, n); nonNegativeCheck(cap, "Capacity"); nonNegativeCheck(cost, "Cost"); int m = pos.size(); pos.add(new IntPair(from, g[from].size())); int fromId = g[from].size(); int toId = g[to].size(); if (from == to) toId++; g[from].add(new InternalWeightedCapEdge(to, toId, cap, cost)); g[to].add(new InternalWeightedCapEdge(from, fromId, 0L, -cost)); return m; } private InternalWeightedCapEdge getInternalEdge(int i) { return g[pos.get(i).first].get(pos.get(i).second); } private InternalWeightedCapEdge getInternalEdgeReversed(InternalWeightedCapEdge e) { return g[e.to].get(e.rev); } public WeightedCapEdge getEdge(int i) { int m = pos.size(); rangeCheck(i, 0, m); InternalWeightedCapEdge e = getInternalEdge(i); InternalWeightedCapEdge re = getInternalEdgeReversed(e); return new WeightedCapEdge(re.to, e.to, e.cap + re.cap, re.cap, e.cost); } public WeightedCapEdge[] getEdges() { WeightedCapEdge[] res = new WeightedCapEdge[pos.size()]; java.util.Arrays.setAll(res, this::getEdge); return res; } public FlowAndCost minCostMaxFlow(int s, int t) { return minCostFlow(s, t, INF); } public FlowAndCost minCostFlow(int s, int t, long flowLimit) { return minCostSlope(s, t, flowLimit).getLast(); } java.util.LinkedList<FlowAndCost> minCostSlope(int s, int t) { return minCostSlope(s, t, INF); } public java.util.LinkedList<FlowAndCost> minCostSlope(int s, int t, long flowLimit) { rangeCheck(s, 0, n); rangeCheck(t, 0, n); if (s == t) { throw new IllegalArgumentException( String.format("%d and %d is the same vertex.", s, t) ); } long[] dual = new long[n]; long[] dist = new long[n]; int[] pv = new int[n]; int[] pe = new int[n]; boolean[] vis = new boolean[n]; long flow = 0; long cost = 0, prev_cost = -1; java.util.LinkedList<FlowAndCost> result = new java.util.LinkedList<>(); result.addLast(new FlowAndCost(flow, cost)); while (flow < flowLimit) { if (!dualRef(s, t, dual, dist, pv, pe, vis)) break; long c = flowLimit - flow; for (int v = t; v != s; v = pv[v]) { c = Math.min(c, g[pv[v]].get(pe[v]).cap); } for (int v = t; v != s; v = pv[v]) { InternalWeightedCapEdge e = g[pv[v]].get(pe[v]); e.cap -= c; g[v].get(e.rev).cap += c; } long d = -dual[s]; flow += c; cost += c * d; if (prev_cost == d) { result.removeLast(); } result.addLast(new FlowAndCost(flow, cost)); prev_cost = cost; } return result; } private boolean dualRef(int s, int t, long[] dual, long[] dist, int[] pv, int[] pe, boolean[] vis) { java.util.Arrays.fill(dist, INF); java.util.Arrays.fill(pv, -1); java.util.Arrays.fill(pe, -1); java.util.Arrays.fill(vis, false); class State implements Comparable<State> { final long key; final int to; State(long key, int to) { this.key = key; this.to = to; } public int compareTo(State q) { return key > q.key ? 1 : -1; } }; java.util.PriorityQueue<State> pq = new java.util.PriorityQueue<>(); dist[s] = 0; pq.add(new State(0L, s)); while (pq.size() > 0) { int v = pq.poll().to; if (vis[v]) continue; vis[v] = true; if (v == t) break; for (int i = 0, deg = g[v].size(); i < deg; i++) { InternalWeightedCapEdge e = g[v].get(i); if (vis[e.to] || e.cap == 0) continue; long cost = e.cost - dual[e.to] + dual[v]; if (dist[e.to] - dist[v] > cost) { dist[e.to] = dist[v] + cost; pv[e.to] = v; pe[e.to] = i; pq.add(new State(dist[e.to], e.to)); } } } if (!vis[t]) { return false; } for (int v = 0; v < n; v++) { if (!vis[v]) continue; dual[v] -= dist[t] - dist[v]; } return true; } private void rangeCheck(int i, int minInlusive, int maxExclusive) { if (i < 0 || i >= maxExclusive) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for length %d", i, maxExclusive) ); } } private void nonNegativeCheck(long cap, java.lang.String attribute) { if (cap < 0) { throw new IllegalArgumentException( String.format("%s %d is negative.", attribute, cap) ); } } } class LazySegTree<S, F> { final int MAX; final int N; final int Log; final java.util.function.BinaryOperator<S> Op; final S E; final java.util.function.BiFunction<F, S, S> Mapping; final java.util.function.BinaryOperator<F> Composition; final F Id; final S[] Dat; final F[] Laz; @SuppressWarnings("unchecked") public LazySegTree(int n, java.util.function.BinaryOperator<S> op, S e, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BinaryOperator<F> composition, F id) { this.MAX = n; int k = 1; while (k < n) k <<= 1; this.N = k; this.Log = Integer.numberOfTrailingZeros(N); this.Op = op; this.E = e; this.Mapping = mapping; this.Composition = composition; this.Id = id; this.Dat = (S[]) new Object[N << 1]; this.Laz = (F[]) new Object[N]; java.util.Arrays.fill(Dat, E); java.util.Arrays.fill(Laz, Id); } public LazySegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BinaryOperator<F> composition, F id) { this(dat.length, op, e, mapping, composition, id); build(dat); } private void build(S[] dat) { int l = dat.length; System.arraycopy(dat, 0, Dat, N, l); for (int i = N - 1; i > 0; i--) { Dat[i] = Op.apply(Dat[i << 1 | 0], Dat[i << 1 | 1]); } } private void push(int k) { if (Laz[k] == Id) return; int lk = k << 1 | 0, rk = k << 1 | 1; Dat[lk] = Mapping.apply(Laz[k], Dat[lk]); Dat[rk] = Mapping.apply(Laz[k], Dat[rk]); if (lk < N) Laz[lk] = Composition.apply(Laz[k], Laz[lk]); if (rk < N) Laz[rk] = Composition.apply(Laz[k], Laz[rk]); Laz[k] = Id; } private void pushTo(int k) { for (int i = Log; i > 0; i--) push(k >> i); } private void pushTo(int lk, int rk) { for (int i = Log; i > 0; i--) { if (((lk >> i) << i) != lk) push(lk >> i); if (((rk >> i) << i) != rk) push(rk >> i); } } private void updateFrom(int k) { k >>= 1; while (k > 0) { Dat[k] = Op.apply(Dat[k << 1 | 0], Dat[k << 1 | 1]); k >>= 1; } } private void updateFrom(int lk, int rk) { for (int i = 1; i <= Log; i++) { if (((lk >> i) << i) != lk) { int lki = lk >> i; Dat[lki] = Op.apply(Dat[lki << 1 | 0], Dat[lki << 1 | 1]); } if (((rk >> i) << i) != rk) { int rki = (rk - 1) >> i; Dat[rki] = Op.apply(Dat[rki << 1 | 0], Dat[rki << 1 | 1]); } } } public void set(int p, S x) { exclusiveRangeCheck(p); p += N; pushTo(p); Dat[p] = x; updateFrom(p); } public S get(int p) { exclusiveRangeCheck(p); p += N; pushTo(p); return Dat[p]; } public S prod(int l, int r) { if (l > r) { throw new IllegalArgumentException( String.format("Invalid range: [%d, %d)", l, r) ); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); if (l == r) return E; l += N; r += N; pushTo(l, r); S sumLeft = E, sumRight = E; while (l < r) { if ((l & 1) == 1) sumLeft = Op.apply(sumLeft, Dat[l++]); if ((r & 1) == 1) sumRight = Op.apply(Dat[--r], sumRight); l >>= 1; r >>= 1; } return Op.apply(sumLeft, sumRight); } public S allProd() { return Dat[1]; } public void apply(int p, F f) { exclusiveRangeCheck(p); p += N; pushTo(p); Dat[p] = Mapping.apply(f, Dat[p]); updateFrom(p); } public void apply(int l, int r, F f) { if (l > r) { throw new IllegalArgumentException( String.format("Invalid range: [%d, %d)", l, r) ); } inclusiveRangeCheck(l); inclusiveRangeCheck(r); if (l == r) return; l += N; r += N; pushTo(l, r); for (int l2 = l, r2 = r; l2 < r2;) { if ((l2 & 1) == 1) { Dat[l2] = Mapping.apply(f, Dat[l2]); if (l2 < N) Laz[l2] = Composition.apply(f, Laz[l2]); l2++; } if ((r2 & 1) == 1) { r2--; Dat[r2] = Mapping.apply(f, Dat[r2]); if (r2 < N) Laz[r2] = Composition.apply(f, Laz[r2]); } l2 >>= 1; r2 >>= 1; } updateFrom(l, r); } public int maxRight(int l, java.util.function.Predicate<S> g) { inclusiveRangeCheck(l); if (!g.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (l == MAX) return MAX; l += N; pushTo(l); S sum = E; do { l >>= Integer.numberOfTrailingZeros(l); if (!g.test(Op.apply(sum, Dat[l]))) { while (l < N) { push(l); l = l << 1; if (g.test(Op.apply(sum, Dat[l]))) { sum = Op.apply(sum, Dat[l]); l++; } } return l - N; } sum = Op.apply(sum, Dat[l]); l++; } while ((l & -l) != l); return MAX; } public int minLeft(int r, java.util.function.Predicate<S> g) { inclusiveRangeCheck(r); if (!g.test(E)) { throw new IllegalArgumentException("Identity element must satisfy the condition."); } if (r == 0) return 0; r += N; pushTo(r - 1); S sum = E; do { r--; while (r > 1 && (r & 1) == 1) r >>= 1; if (!g.test(Op.apply(Dat[r], sum))) { while (r < N) { push(r); r = r << 1 | 1; if (g.test(Op.apply(Dat[r], sum))) { sum = Op.apply(Dat[r], sum); r--; } } return r + 1 - N; } sum = Op.apply(Dat[r], sum); } while ((r & -r) != r); return 0; } private void exclusiveRangeCheck(int p) { if (p < 0 || p >= MAX) { throw new IndexOutOfBoundsException( String.format("Index %d is not in [%d, %d).", p, 0, MAX) ); } } private void inclusiveRangeCheck(int p) { if (p < 0 || p > MAX) { throw new IndexOutOfBoundsException( String.format("Index %d is not in [%d, %d].", p, 0, MAX) ); } } // **************** DEBUG **************** // private int indent = 6; public void setIndent(int newIndent) { this.indent = newIndent; } @Override public String toString() { return toSimpleString(); } private S[] simulatePushAll() { S[] simDat = java.util.Arrays.copyOf(Dat, 2 * N); F[] simLaz = java.util.Arrays.copyOf(Laz, 2 * N); for (int k = 1; k < N; k++) { if (simLaz[k] == Id) continue; int lk = k << 1 | 0, rk = k << 1 | 1; simDat[lk] = Mapping.apply(simLaz[k], simDat[lk]); simDat[rk] = Mapping.apply(simLaz[k], simDat[rk]); if (lk < N) simLaz[lk] = Composition.apply(simLaz[k], simLaz[lk]); if (rk < N) simLaz[rk] = Composition.apply(simLaz[k], simLaz[rk]); simLaz[k] = Id; } return simDat; } public String toDetailedString() { return toDetailedString(1, 0, simulatePushAll()); } private String toDetailedString(int k, int sp, S[] dat) { if (k >= N) return indent(sp) + dat[k]; String s = ""; s += toDetailedString(k << 1 | 1, sp + indent, dat); s += "\n"; s += indent(sp) + dat[k]; s += "\n"; s += toDetailedString(k << 1 | 0, sp + indent, dat); return s; } private static String indent(int n) { StringBuilder sb = new StringBuilder(); while (n --> 0) sb.append(' '); return sb.toString(); } public String toSimpleString() { S[] dat = simulatePushAll(); StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 0; i < N; i++) { sb.append(dat[i + N]); if (i < N - 1) sb.append(',').append(' '); } sb.append(']'); return sb.toString(); } } class FenwickTree{ private int _n; private long[] data; public FenwickTree(int n){ this._n = n; data = new long[n]; } /** * @verified https://atcoder.jp/contests/practice2/tasks/practice2_b * @submission https://atcoder.jp/contests/practice2/submissions/16580495 */ public FenwickTree(long[] data) { this(data.length); build(data); } public void set(int p, long x){ add(p, x - get(p)); } public void add(int p, long x){ assert(0<=p && p<_n); p++; while(p<=_n){ data[p-1] += x; p += p&-p; } } public long sum(int l, int r){ assert(0<=l && l<=r && r<=_n); return sum(r)-sum(l); } public long get(int p){ return sum(p, p+1); } private long sum(int r){ long s = 0; while(r>0){ s += data[r-1]; r -= r&-r; } return s; } private void build(long[] dat) { System.arraycopy(dat, 0, data, 0, _n); for (int i=1; i<=_n; i++) { int p = i+(i&-i); if(p<=_n){ data[p-1] += data[i-1]; } } } } class MaxFlow { private static final class InternalCapEdge { final int to; final int rev; long cap; InternalCapEdge(int to, int rev, long cap) { this.to = to; this.rev = rev; this.cap = cap; } } public static final class CapEdge { public final int from, to; public final long cap, flow; CapEdge(int from, int to, long cap, long flow) { this.from = from; this.to = to; this.cap = cap; this.flow = flow; } @Override public boolean equals(Object o) { if (o instanceof CapEdge) { CapEdge e = (CapEdge) o; return from == e.from && to == e.to && cap == e.cap && flow == e.flow; } return false; } } private static final class IntPair { final int first, second; IntPair(int first, int second) { this.first = first; this.second = second; } } static final long INF = Long.MAX_VALUE; private final int n; private final java.util.ArrayList<IntPair> pos; private final java.util.ArrayList<InternalCapEdge>[] g; @SuppressWarnings("unchecked") public MaxFlow(int n) { this.n = n; this.pos = new java.util.ArrayList<>(); this.g = new java.util.ArrayList[n]; for (int i = 0; i < n; i++) { this.g[i] = new java.util.ArrayList<>(); } } public int addEdge(int from, int to, long cap) { rangeCheck(from, 0, n); rangeCheck(to, 0, n); nonNegativeCheck(cap, "Capacity"); int m = pos.size(); pos.add(new IntPair(from, g[from].size())); int fromId = g[from].size(); int toId = g[to].size(); if (from == to) toId++; g[from].add(new InternalCapEdge(to, toId, cap)); g[to].add(new InternalCapEdge(from, fromId, 0L)); return m; } private InternalCapEdge getInternalEdge(int i) { return g[pos.get(i).first].get(pos.get(i).second); } private InternalCapEdge getInternalEdgeReversed(InternalCapEdge e) { return g[e.to].get(e.rev); } public CapEdge getEdge(int i) { int m = pos.size(); rangeCheck(i, 0, m); InternalCapEdge e = getInternalEdge(i); InternalCapEdge re = getInternalEdgeReversed(e); return new CapEdge(re.to, e.to, e.cap + re.cap, re.cap); } public CapEdge[] getEdges() { CapEdge[] res = new CapEdge[pos.size()]; java.util.Arrays.setAll(res, this::getEdge); return res; } public void changeEdge(int i, long newCap, long newFlow) { int m = pos.size(); rangeCheck(i, 0, m); nonNegativeCheck(newCap, "Capacity"); if (newFlow > newCap) { throw new IllegalArgumentException( String.format("Flow %d is greater than the capacity %d.", newCap, newFlow) ); } InternalCapEdge e = getInternalEdge(i); InternalCapEdge re = getInternalEdgeReversed(e); e.cap = newCap - newFlow; re.cap = newFlow; } public long maxFlow(int s, int t) { return flow(s, t, INF); } public long flow(int s, int t, long flowLimit) { rangeCheck(s, 0, n); rangeCheck(t, 0, n); long flow = 0L; int[] level = new int[n]; int[] que = new int[n]; int[] iter = new int[n]; while (flow < flowLimit) { bfs(s, t, level, que); if (level[t] < 0) break; java.util.Arrays.fill(iter, 0); while (flow < flowLimit) { long d = dfs(t, s, flowLimit - flow, iter, level); if (d == 0) break; flow += d; } } return flow; } private void bfs(int s, int t, int[] level, int[] que) { java.util.Arrays.fill(level, -1); int hd = 0, tl = 0; que[tl++] = s; level[s] = 0; while (hd < tl) { int u = que[hd++]; for (InternalCapEdge e : g[u]) { int v = e.to; if (e.cap == 0 || level[v] >= 0) continue; level[v] = level[u] + 1; if (v == t) return; que[tl++] = v; } } } private long dfs(int cur, int s, long flowLimit, int[] iter, int[] level) { if (cur == s) return flowLimit; long res = 0; int curLevel = level[cur]; for (int itMax = g[cur].size(); iter[cur] < itMax; iter[cur]++) { int i = iter[cur]; InternalCapEdge e = g[cur].get(i); InternalCapEdge re = getInternalEdgeReversed(e); if (curLevel <= level[e.to] || re.cap == 0) continue; long d = dfs(e.to, s, Math.min(flowLimit - res, re.cap), iter, level); if (d <= 0) continue; e.cap += d; re.cap -= d; res += d; if (res == flowLimit) break; } return res; } public boolean[] minCut(int s) { rangeCheck(s, 0, n); boolean[] visited = new boolean[n]; int[] stack = new int[n]; int ptr = 0; stack[ptr++] = s; visited[s] = true; while (ptr > 0) { int u = stack[--ptr]; for (InternalCapEdge e : g[u]) { int v = e.to; if (e.cap > 0 && !visited[v]) { visited[v] = true; stack[ptr++] = v; } } } return visited; } private void rangeCheck(int i, int minInclusive, int maxExclusive) { if (i < 0 || i >= maxExclusive) { throw new IndexOutOfBoundsException( String.format("Index %d out of bounds for length %d", i, maxExclusive) ); } } private void nonNegativeCheck(long cap, String attribute) { if (cap < 0) { throw new IllegalArgumentException( String.format("%s %d is negative.", attribute, cap) ); } } } 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());} }
ConDefects/ConDefects/Code/abc257_e/Java/45958719