exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
179a1b4685067e74d497d4562366c805
train_004.jsonl
1422376200
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { String s=in.nextString();int n=s.length(); StringBuilder s1=new StringBuilder(""); char ch[]=s.toCharArray(); boolean st=false; for(int i=0;i<(n-1);i++){ if(ch[i]<ch[n-1]&&((int)(ch[i]-'0'))%2==0){ char tmp=ch[i]; ch[i]=ch[n-1]; ch[n-1]=tmp; st=true; break; } } if(st){ for(int i=0;i<n;i++){ s1.append(ch[i]); } out.printLine(s1.toString()); } else { for(int i=n-2;i>=0;i--){ if(((int)(ch[i]-'0'))%2==0){ char tmp=ch[i]; ch[i]=ch[n-1]; ch[n-1]=tmp; st=true; break; } } if(st){ for(int i=0;i<n;i++){ s1.append(ch[i]); } out.printLine(s1.toString()); } else out.printLine("-1"); } } } class InputReader { BufferedReader in; public InputReader(InputStream inputStream) { in=new BufferedReader(new InputStreamReader(inputStream)); } public String nextString() { try { return in.readLine(); } catch (Exception e) { return null; } } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
Java
["527", "4573", "1357997531"]
0.5 seconds
["572", "3574", "-1"]
null
Java 7
standard input
[ "greedy", "math", "strings" ]
bc375e27bd52f413216aaecc674366f8
The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.
1,300
If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.
standard output
PASSED
1d5a0b6b7e052ea99c415ce0851593c7
train_004.jsonl
1422376200
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String n = br.readLine(); int length = n.length(); char[] arr = n.toCharArray(); char lastChar = arr[length-1]; int index = -1; boolean maxEvenPossible = false; for (int i = 0; i < length-1 && !maxEvenPossible; ++i) { char temp = arr[i]; if (((temp-'0')&1) == 0) { if (index < i) index = i; if (temp < lastChar) { maxEvenPossible = true; arr[length-1] = arr[i]; arr[i] = lastChar; out.println(new String(arr)); break; } } } if (!maxEvenPossible){ if (index == -1) { out.println(-1); } else { char temp = arr[index]; arr[index] = lastChar; arr[length-1] = temp; out.println(new String(arr)); } } out.flush(); out.close(); System.exit(0); } }
Java
["527", "4573", "1357997531"]
0.5 seconds
["572", "3574", "-1"]
null
Java 7
standard input
[ "greedy", "math", "strings" ]
bc375e27bd52f413216aaecc674366f8
The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.
1,300
If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.
standard output
PASSED
963c0a26b5dd170f921d175f5d6a3026
train_004.jsonl
1422376200
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Solution { public static int MOD = 1000000007; public static int MAX = 1000002; public static void main(String[] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out,true); int index = 0; String s = br.readLine(); int n = s.length(); int counteven=0; for(int i =0;i<n;i++){ if((int)s.charAt(i)%2==0 ){ counteven++; if(Integer.parseInt(s.charAt(i)+"")>Integer.parseInt(s.charAt(n-1)+"")){ index = i; } else{ index = i; break; } } } if(counteven == 0){ out.println(-1); } else{ String ans = ""; ans+=s.substring(0,index); ans+=s.substring(n-1,n); ans+=s.substring(index+1,n-1); ans+=s.charAt(index); out.println(ans); } } }
Java
["527", "4573", "1357997531"]
0.5 seconds
["572", "3574", "-1"]
null
Java 7
standard input
[ "greedy", "math", "strings" ]
bc375e27bd52f413216aaecc674366f8
The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.
1,300
If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.
standard output
PASSED
457646fe66b8ea34fc30373cea4f5919
train_004.jsonl
1422376200
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!
256 megabytes
import java.util.*; import java.io.*; public class B { public static PrintStream out = System.out; public static void main(String args[]) { Scanner sc = new Scanner(System.in); String S = sc.next(); int last = (int) (S.charAt(S.length() - 1) - '0'); for (int i = 0; i < S.length(); i++) { int cur = (int) (S.charAt(i) - '0'); if (cur % 2 == 1) continue; if (cur < last) { out.println(ns(S, i)); System.exit(0); } } for (int i = 0; i < S.length(); i++) { int cur = (int) (S.charAt(i) - '0'); if (cur % 2 == 1) continue; if (cur == last) { out.println(ns(S, i)); System.exit(0); } } for (int i = S.length() - 1; i >= 0; i--) { int cur = (int) (S.charAt(i) - '0'); if (cur % 2 == 1) continue; if (cur > last) { out.println(ns(S, i)); System.exit(0); } } out.println(-1); } static String ns(String S, int i) { // out.println(S + " " + i); String ret = S; ret = ns(ret, S.length() - 1, S.charAt(i)); ret = ns(ret, i, S.charAt(S.length() - 1)); return ret; } static String ns(String S, int i, char nc) { // out.println(S + " " + i + " " + nc); String left = i == 0 ? "" : S.substring(0, i); String right = i == S.length() - 1 ? "" : S.substring(i + 1, S.length()); return left + nc + right; } }
Java
["527", "4573", "1357997531"]
0.5 seconds
["572", "3574", "-1"]
null
Java 7
standard input
[ "greedy", "math", "strings" ]
bc375e27bd52f413216aaecc674366f8
The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.
1,300
If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.
standard output
PASSED
6700a4d60ecb98a4e986e293d274a366
train_004.jsonl
1422376200
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!
256 megabytes
import java.io.*; import java.util.*; public class Con288_b { FastScanner in; PrintWriter out; void solver(){ StringBuilder a = new StringBuilder(in.next()); int max = -1, imax = -1; int last = Character.getNumericValue(a.charAt(a.length() - 1)); //значение последнего int cur; for (int i = 0; i < a.length(); i++){ cur = Character.getNumericValue(a.charAt(i)); if (cur % 2 == 0) if (last > cur){ //если можно поменять цифры и увеличить число a.deleteCharAt(i); a.insert(i, last); a.deleteCharAt(a.length() - 1); a.append(cur); out.println(a); return; }else { //запомнить самое последнее четное max = cur; imax = i; } } if(max != -1){ a.deleteCharAt(imax); a.insert(imax, last); a.deleteCharAt(a.length() - 1); a.append(max); out.println(a); } else out.println(-1); } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solver(); out.close(); } void run() { try { in = new FastScanner(new File("oddoreven.in")); out = new PrintWriter(new File("oddoreven.out")); solver(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } class FastScanner{ BufferedReader br; StringTokenizer st; public FastScanner(File f){ try{ br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e){ e.printStackTrace(); } } public FastScanner(InputStream f){ br = new BufferedReader(new InputStreamReader(f)); } String next(){ while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } } public static void main(String[] args) { new Con288_b().runIO(); } }
Java
["527", "4573", "1357997531"]
0.5 seconds
["572", "3574", "-1"]
null
Java 7
standard input
[ "greedy", "math", "strings" ]
bc375e27bd52f413216aaecc674366f8
The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.
1,300
If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.
standard output
PASSED
56d7fda3c768ebdb07a9544bbff96830
train_004.jsonl
1422376200
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!
256 megabytes
import java.util.Scanner; public class B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); char[] ar = s.toCharArray(); int idx = -1; int last = ar[ar.length-1]-'0'; for (int i = ar.length-2; i>=0; i--) { int d = Integer.parseInt(ar[i]+""); if(d%2==0 && d < last){ idx = i; }else if(d%2==0 && idx==-1){ idx=i; } } if (idx != -1) { char temp = ar[ar.length - 1]; ar[ar.length - 1] = ar[idx]; ar[idx] = temp; StringBuffer sb = new StringBuffer(""); for (int i = 0; i < ar.length; i++) { sb.append(ar[i]); } System.out.println(sb.toString()); } else{ System.out.println(-1); } } }
Java
["527", "4573", "1357997531"]
0.5 seconds
["572", "3574", "-1"]
null
Java 7
standard input
[ "greedy", "math", "strings" ]
bc375e27bd52f413216aaecc674366f8
The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.
1,300
If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.
standard output
PASSED
6a0d4d40282ebb8ceeb8def88b7e9685
train_004.jsonl
1422376200
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!
256 megabytes
import java.io.InputStream; import java.io.PrintStream; import java.util.Scanner; public class CFS508B { public final static String IN_FILE = "test/CFS508B.in"; public final static String OUT_FILE = "test/CFS508B.out"; public static void main(String[] args) throws Exception { // InputStream in = new FileInputStream(IN_FILE); // // @SuppressWarnings("resource") // PrintStream out = new PrintStream(OUT_FILE); InputStream in = System.in; PrintStream out = System.out; Scanner IN = new Scanner(in); String s = IN.next(); IN.close(); int iMax = -1; char[] current = s.toCharArray(); for (int i = 0; i < current.length; i++) { if ((current[i] - '0') % 2 == 0) { if (iMax == -1) { iMax = i; } else if (compare(current, iMax) > 0) { iMax = i; } } } if (iMax == -1) { out.println(-1); } else { char[] m = s.toCharArray(); m[m.length - 1] = current[iMax]; m[iMax] = current[current.length - 1]; out.println(new String(m)); } } // 13579975311357997531135799753121357997531135799753113579975314135799753113579975318135799753113579975311357997531 private static int compare(char[] current, int iMax) { return current[iMax] - current[current.length - 1]; } }
Java
["527", "4573", "1357997531"]
0.5 seconds
["572", "3574", "-1"]
null
Java 7
standard input
[ "greedy", "math", "strings" ]
bc375e27bd52f413216aaecc674366f8
The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.
1,300
If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.
standard output
PASSED
918a75a9b07d4fa70ea665c4be015fd0
train_004.jsonl
1422376200
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.util.InputMismatchException; /** * * @author Abhishek Tiwari (abhishekt183@gmail.com) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); // int t = in.readInt();F qwqe solver = new qwqe(); // for (int i = 0; i < t; i++) solver.solve(1, in, out); out.close(); } } class qwqe { public void solve(int testNumber, InputReader in, OutputWriter out) { char[] ch = in.next().toCharArray(); int[] a = new int[ch.length]; for (int i = 0; i < ch.length; i++) { if (ch[i] % 2 == 0) { a[i]++; } } boolean flag = true; int lastIndex = -1; for (int i = 0; i < ch.length - 1; i++) { if (a[i] > 0 && ch[ch.length - 1] > ch[i]) { flag = false; swap(ch, i); break; } else if (a[i] > 0) { lastIndex = Math.max(lastIndex, i); } } if (flag && lastIndex != -1) { flag = false; swap(ch, lastIndex); } out.printLine(flag ? -1 : new String(ch)); } private void swap(char[] ch, int minIndex) { char temp = ch[ch.length - 1]; ch[ch.length - 1] = ch[minIndex]; ch[minIndex] = temp; } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter( outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } public static int[][] readIntTable(InputReader in, int rowCount, int columnCount) { int[][] table = new int[rowCount][]; for (int i = 0; i < rowCount; i++) table[i] = readIntArray(in, columnCount); return table; } }
Java
["527", "4573", "1357997531"]
0.5 seconds
["572", "3574", "-1"]
null
Java 7
standard input
[ "greedy", "math", "strings" ]
bc375e27bd52f413216aaecc674366f8
The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.
1,300
If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.
standard output
PASSED
e565533090cca662d4daae2eb996913f
train_004.jsonl
1422376200
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution{ public void solve(String number){ char[] numbers = number.toCharArray(); int lastValue = (int)(numbers[numbers.length - 1] - '0'); int changeIndex = -1; for(int i = 0; i < numbers.length - 1; i++){ int value = (int)(numbers[i] - '0'); if(value % 2 > 0) continue; if(lastValue > value){ changeIndex = i; break; } else{ changeIndex = i; } } if(changeIndex == -1){ System.out.println(-1); } else{ char tempChar = numbers[changeIndex]; numbers[changeIndex] = numbers[numbers.length - 1]; numbers[numbers.length - 1] = tempChar; System.out.println(String.valueOf(numbers)); } return; } public static void main(String[] args){ Solution tool = new Solution(); Scanner scan = new Scanner(System.in); String number = scan.next(); tool.solve(number); scan.close(); return; } }
Java
["527", "4573", "1357997531"]
0.5 seconds
["572", "3574", "-1"]
null
Java 7
standard input
[ "greedy", "math", "strings" ]
bc375e27bd52f413216aaecc674366f8
The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.
1,300
If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.
standard output
PASSED
4e61a7daf2851d7d1897f21637065e57
train_004.jsonl
1422376200
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!
256 megabytes
import java.util.ArrayList; import java.util.Scanner; /** * * @author Diva.shivi */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { String n; Scanner s = new Scanner(System.in); n = s.next(); int i,j; String ans = ""; int t = -1; int m = n.length(); for(i = 0;i < m - 1;i++){ int k = n.charAt(i) - '0'; if(k % 2 == 0){ if( n.charAt(m - 1) > n.charAt(i)){ char st[] = n.toCharArray(); char temp = st[i]; st[i] = st[m - 1]; st[m - 1] = temp; ans = new String(st); break; } t = i; } } if(ans != ""){ System.out.println(ans); }else{ if(t == -1){ System.out.println("-1"); }else{ char st[] = n.toCharArray(); char temp = st[t]; st[t] = st[n.length() - 1]; st[n.length() - 1] = temp; ans = new String(st); System.out.println(ans); } } } }
Java
["527", "4573", "1357997531"]
0.5 seconds
["572", "3574", "-1"]
null
Java 7
standard input
[ "greedy", "math", "strings" ]
bc375e27bd52f413216aaecc674366f8
The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.
1,300
If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.
standard output
PASSED
042e3dae39ba698dd08a3353796badd8
train_004.jsonl
1422376200
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!
256 megabytes
import java.util.Scanner; public class B508 { /** * @param args */ public static void main(String[] args) { Scanner scan = new Scanner(System.in); char[] n = scan.next().toCharArray(); int len = n.length; int l = n[len - 1] - '0'; int idx = -1; for (int i = 0; i < len; i++) { int x = n[i] - '0'; if (x % 2 == 1) continue; idx = i; if (x < l) break; } if (idx == -1) { System.out.println(-1); return; } swap(n, idx, len - 1); for (int i = 0; i < n.length; i++) { System.out.print(n[i]); } System.out.println(); } static char[] swap(char[] s, int i1, int i2) { char temp = s[i1]; s[i1] = s[i2]; s[i2] = temp; return s; } }
Java
["527", "4573", "1357997531"]
0.5 seconds
["572", "3574", "-1"]
null
Java 7
standard input
[ "greedy", "math", "strings" ]
bc375e27bd52f413216aaecc674366f8
The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.
1,300
If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.
standard output
PASSED
be3ad9d4564f4930e5ccbecff4018b0a
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
//package tprob; import java.io.*; import java.util.*; public class BerryJars { public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader((new InputStreamReader(System.in))); //BufferedReader bf = new BufferedReader((new FileReader("C:\\Users\\s-aichen\\Downloads\\BerryJam.txt"))); int tests = Integer.parseInt(bf.readLine()); for (int test=0; test<tests; test++) { int n = Integer.parseInt(bf.readLine()); StringTokenizer st = new StringTokenizer(bf.readLine()); int[] totalJams = new int[2]; int[] leftJars = new int[n]; int[] rightJars = new int[n]; // fills leftJars from right to left so jam at index 0 can be eaten right away for (int i=n-1; i>=0; i--) { int jam = Integer.parseInt(st.nextToken()); leftJars[i] = jam; totalJams[jam-1]++; } //fills rightJars from left to right so jam at index 0 can be eaten right away for (int i=0; i<n; i++) { int jam = Integer.parseInt(st.nextToken()); rightJars[i] = jam; totalJams[jam-1]++; } int eatType = more(totalJams); int profitNeeded = Math.abs(totalJams[0] - totalJams[1]); ArrayList<Integer> leftProfits = findProfits(leftJars, eatType); ArrayList<Integer> rightProfits = findProfits(rightJars, eatType); int leftMax = Math.min(leftProfits.size()-1, profitNeeded); int rightMax = Math.min(rightProfits.size()-1, profitNeeded); int leftMin = profitNeeded - rightMax; int minCost = Integer.MAX_VALUE; for (int i=leftMin; i<=leftMax; i++) { int rightProfit = profitNeeded - i; int cost = leftProfits.get(i) + rightProfits.get(rightProfit); if (cost < minCost) { minCost = cost; } } System.out.println(minCost); } } public static ArrayList<Integer> findProfits(int[] jars, int type){ ArrayList<Integer> profits = new ArrayList<>(); profits.add(0); int good = 0; int bad = 0; for (int i=0; i<jars.length; i++) { int next = profits.size(); if (jars[i] == type) { good++; } else { bad++; } if (good - bad == next) { profits.add(i+1); } } return profits; } public static int more(int[] a) { if (a[0] > a[1]) { return 1; } else { return 2; } } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
d70d2c116d16326a94829bbc9c94665a
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class p1278C { public void realMain() throws Exception { BufferedReader fin = new BufferedReader(new InputStreamReader(System.in), 1000000); String in = fin.readLine(); String[] ar = in.split(" "); int T = Integer.parseInt(ar[0]); for(int t = 0; t < T; t++) { int ret2 = 0; boolean dig2 = false; for (int ch = 0; (ch = fin.read()) != -1; ) { if (ch >= '0' && ch <= '9') { dig2 = true; ret2 = ret2 * 10 + ch - '0'; } else if (dig2) break; } int n = ret2; int[] left = new int[n + 1]; left[0] = 0; for(int i = 0; i < n; i++) { int ret = 0; boolean dig = false; for (int ch = 0; (ch = fin.read()) != -1; ) { if (ch >= '0' && ch <= '9') { dig = true; ret = ret * 10 + ch - '0'; } else if (dig) break; } if(ret == 1) { left[i + 1] = left[i] + 1; } else { left[i + 1] = left[i] - 1; } } int[] right = new int[n + 1]; right[n] = 0; int[] tmpright = new int[n]; for(int i = 0; i < n; i++) { int ret = 0; boolean dig = false; for (int ch = 0; (ch = fin.read()) != -1; ) { if (ch >= '0' && ch <= '9') { dig = true; ret = ret * 10 + ch - '0'; } else if (dig) break; } tmpright[i] = ret; } for(int i = n - 1; i >= 0; i--) { if(tmpright[i] == 1) { right[i] = right[i + 1] + 1; } else { right[i] = right[i + 1] - 1; } } //System.out.println(Arrays.toString(left)); //System.out.println(Arrays.toString(right)); int[] minleft = new int[n + n + 2]; int[] minright = new int[n + n + 2]; for(int i = 0; i < n + n + 2; i++) { minleft[i] = -1; minright[i] = -1; } int min = Integer.MAX_VALUE; for(int i = n; i >= 0; i--) { if(minleft[ left[i] + n + 1 ] == -1) { minleft[ left[i] + n + 1 ] = n - i; } } for(int i = 0; i < n + 1; i++) { if(minright[ right[i] + n + 1 ] == -1) { minright[ right[i] + n + 1 ] = i; } } //System.out.println(Arrays.toString(minleft)); //System.out.println(Arrays.toString(minright)); for(int i = 0; i < n + 2; i++) { int neg = i - (n + 1); neg *= -1; if(minleft[i] != -1 && minright[ neg + n + 1 ] != -1) { min = Math.min(min, minleft[i] + minright[ neg + n + 1 ]); } } for(int i = n + 2; i < n + n + 2; i++) { int neg = i - (n + 1); neg *= -1; if(minleft[i] != -1 && minright[ neg + n + 1 ] != -1) { min = Math.min(min, minleft[i] + minright[neg + n + 1]); } } System.out.println(min); } } public static void main(String[] args) throws Exception { p1278C a = new p1278C(); a.realMain(); } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
4ce24a7aed64454c36eddbab22417421
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Code2112 { public static void main(String args[]){ Reader s = new Reader(); int t = s.nextInt(); StringBuilder sb = new StringBuilder(); while(t-- > 0){ int n = s.nextInt(); int a[] = new int[2*n]; for(int i=0;i<a.length;i++){ a[i] = s.nextInt(); } int min = 2*n; int left = n - 1; int right = n; Map<Integer,Integer> map = new HashMap<>(); map.put(0,2*n); int pre[][] = new int[n][2]; int red = 0; int blue = 0; for(int i=2*n-1;i>=right;i--){ if(a[i] == 1){ red++; } else{ blue++; } map.put(red-blue,i); } for(int i=0;i<=left;i++){ if(i==0){ if(a[i] == 1){ pre[i][0]++; } else{ pre[i][1]++; } } else{ if(a[i] == 1){ pre[i][0] = 1 + pre[i-1][0]; pre[i][1] = pre[i-1][1]; } else{ pre[i][1] = 1 + pre[i-1][1]; pre[i][0] = pre[i-1][0]; } } } if(pre[n-1][0] == pre[n-1][1]){ min = n; } if(map.containsKey(0)){ min = Math.min(min,n + map.get(0) - n); } red = 0; blue = 0; //System.out.println(min); for(int i=left;i>=0;i--){ red = pre[i][0]; blue = pre[i][1]; if(map.containsKey(blue-red)){ int index = map.get(blue-red); min = Math.min(min,index - n + left - i); } } sb.append(min).append("\n"); } System.out.println(sb); } static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
57a4f067081d21efaee960bffdde0d72
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int T=sc.nextInt(); while(T>=1){ --T; int n=sc.nextInt(); int a[]=new int[2*n+1]; int sum[]=new int[2*n+1];sum[0]=0; for(int i=1;i<=2*n;i++){ a[i]=sc.nextInt(); sum[i]+=sum[i-1]; if(a[i]==1)sum[i]+=1; else sum[i]-=1; } HashMap<Integer,Integer>mp=new HashMap<>(); for(int i=0;i<=n;i++){ if(mp.containsKey(sum[i])){ mp.replace(sum[i],n-i); } else{ mp.put(sum[i],n-i); } } //System.out.println(mp.toString()); Integer ans=2*n; for(int i=n;i<=2*n;i++){//右侧吃的 int now=sum[2*n]-sum[i]; if(mp.containsKey(-now)){ //System.out.println("now:"+now+" i:"+i+" ?;"+mp.get(-now)); ans=Math.min(ans,mp.get(-now)+i-n); } } System.out.println(ans); } } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
c0373f6f3d58a8d8b98dc5e959842efc
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.net.PortUnreachableException; import java.util.*; // written by luchy0120 public class Main { public static void main(String[] args) throws Exception { new Main().run(); } static int groups = 0; static int[] fa; static int[] sz; static void init(int n) { groups = n; fa = new int[n]; for (int i = 1; i < n; ++i) { fa[i] = i; } sz = new int[n]; Arrays.fill(sz, 1); } static int root(int p) { while (p != fa[p]) { fa[p] = fa[fa[p]]; p = fa[p]; } return p; } static void combine(int p, int q) { int i = root(p); int j = root(q); if (i == j) { return; } if (sz[i] < sz[j]) { fa[i] = j; sz[j] += sz[i]; } else { fa[j] = i; sz[i] += sz[j]; } groups--; } int color[],dfn[],low[],stack[],cnt[]; boolean vis[]; boolean iscut[]; int deep,top,n,m,sum,ans; List<Integer> g[]; void tarjan(int u,int fa) { int child = 0; dfn[u]=++deep; low[u]=deep; vis[u]=true; stack[++top]=u; int sz=g[u].size(); for(int i=0;i<sz;i++) { int v =g[u].get(i); if(v==fa) continue; if(dfn[v]==0) { child++; tarjan(v,u); low[u]=Math.min(low[u],low[v]); } else { if(vis[v]) { low[u]=Math.min(low[u],low[v]); } } } if(fa<0&&child==1){ iscut[u] =true; } if(dfn[u]==low[u]) { iscut[u] = true; color[u]=++sum; vis[u]=false; while(stack[top]!=u) { color[stack[top]]=sum; vis[stack[top--]]=false; } top--; } } // void solve() { // // } // int get_room(int i,int j){ // return i/3*3 + j/3; // } // int a[][] = new int[9][9]; // int space = 0; // // boolean vis_row[][] = new boolean[9][10]; // boolean vis_col[][] = new boolean[9][10]; // boolean vis_room[][] = new boolean[9][10]; // int val[][][] =new int[9][9][]; // int prepare[][]; // // void dfs(int rt){ // // } int h[],to[],ne[];int ct =0; void add(int u,int v){ u--;v--; to[ct] = v; ne[ct] = h[u]; h[u] = ct++; } void solve(){ int t =ni(); for(int i=0;i<t;++i){ int n = ni(); int a[] = na(2*n); Map<Integer,Integer> mp = new HashMap<>();int s =0; mp.put(0,-1); for(int j=0;j<n;++j){ if(a[j]==1){ s++; }else{ s--; } mp.put(s,j); } int s1 = 0; int r = 2*n; if(mp.containsKey(0)){ int le = mp.get(0); r = Math.min(r,2*n-le-1); } for(int j=2*n-1;j>=n;--j){ if(a[j]==1){ s1++; }else{ s1--; } int ck = -s1; if(mp.containsKey(ck)){ int le = mp.get(ck); r = Math.min(r,j-le-1); } } println(r); } } List<Integer> go[]; int par[][]; int w[][]; int gg[][]; void dfs(int rt,int fa){ vis[rt] = true; if(fa!=-1) { par[rt][0] = fa; } for(int to:go[rt]){ if(to==fa) continue; w[to][0] = gg[rt][to]; dfs(to,rt); } } void solve1() { int n = ni(); int m = ni(); int e[][] = new int[m][3]; for (int i = 0; i < m; ++i) { int u = ni(); int v = ni(); int z = ni(); e[i][0] = u; e[i][1] = v; e[i][2] = z; } Arrays.sort(e, (xx, yy) -> { return yy[2] - xx[2]; }); init(n + 1); gg = new int[n + 1][n + 1]; go = new ArrayList[n + 1]; for (int i = 0; i <= n; ++i) { go[i] = new ArrayList<>(); } for (int i = 0; i < m; ++i) { int p1 = e[i][0]; int p2 = e[i][1]; if (root(p1) != root(p2)) { combine(p1, p2); gg[p1][p2] = e[i][2]; gg[p2][p1] = e[i][2]; go[p1].add(p2); go[p2].add(p1); } } boolean vis[] = new boolean[n + 1]; par = new int[n + 1][21]; w = new int[n + 1][21]; for (int j = 0; j < 21; ++j) { for (int i = 0; i <= n; ++i) { w[i][j] = 100000000; } } for (int i = 0; i <= n; ++i) { if (!vis[i]) { dfs(i, -1); } } for (int j = 1; j < 20; ++j) { for (int i = 1; i <= n; ++i) { w[i][j] = Math.min(w[i][j - 1], w[par[i][j - 1]][j - 1]); par[i][j] = par[par[i][j - 1]][j - 1]; } } int q = ni(); for (int i = 0; i < q; ++i) { int xx = ni(); int yy = ni(); if (root(xx) != root(yy)) { println(-1); continue; } int res = Integer.MAX_VALUE; for (int p = 20; p >= 0; --p) { if (par[xx][p] != par[yy][p]) { res = Math.min(res, w[xx][p]); res = Math.min(res, w[yy][p]); xx = par[xx][p]; yy = par[yy][p]; } } res = Math.min(res, w[xx][0]); res = Math.min(res, w[yy][0]); println(res); } } // // // // // // // // // // // // // // // // // // // // // // } static long mul(long a, long b, long p) { long res=0,base=a; while(b>0) { if((b&1L)>0) res=(res+base)%p; base=(base+base)%p; b>>=1; } return res; } static long mod_pow(long k,long n,long p){ long res = 1L; long temp = (k%p+p)%p; while(n!=0L){ if((n&1L)==1L){ res = ((res*temp)%p+p)%p; } temp = ((temp * temp)%p+p)%p; n = n>>1L; } return res%p; } public static String roundS(double result, int scale){ String fmt = String.format("%%.%df", scale); return String.format(fmt, result); } // void solve() { // // for(int i=0;i<9;++i) { // for (int j = 0; j < 9; ++j) { // int v = ni(); // a[i][j] = v; // if(v>0) { // vis_row[i][v] = true; // vis_col[j][v] = true; // vis_room[get_room(i, j)][v] = true; // }else{ // space++; // } // } // } // // // prepare = new int[space][2]; // // int p = 0; // // for(int i=0;i<9;++i) { // for (int j = 0; j < 9; ++j) { // if(a[i][j]==0){ // prepare[p][0] = i; // prepare[p][1]= j;p++; // List<Integer> temp =new ArrayList<>(); // for(int k=1;k<=9;++k){ // if(!vis_col[j][k]&&!vis_row[i][k]&&!vis_room[get_room(i,j)][k]){ // temp.add(k); // } // } // int sz = temp.size(); // val[i][j] = new int[sz]; // for(int k=0;k<sz;++k){ // val[i][j][k] = temp.get(k); // } // } // } // } // Arrays.sort(prepare,(x,y)->{ // return Integer.compare(val[x[0]][x[1]].length,val[y[0]][y[1]].length); // }); // dfs(0); // // // // // // // // // // // } InputStream is; PrintWriter out; void run() throws Exception { is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private char ncc() { int b = readByte(); return (char) b; } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private String nline() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b) || b == ' ') { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[][] nm(int n, int m) { char[][] a = new char[n][]; for (int i = 0; i < n; i++) a[i] = ns(m); return a; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private long[] nal(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) { } ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') num = (num << 3) + (num << 1) + (b - '0'); else return minus ? -num : num; b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) { } ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') num = num * 10 + (b - '0'); else return minus ? -num : num; b = readByte(); } } void print(Object obj) { out.print(obj); } void println(Object obj) { out.println(obj); } void println() { out.println(); } void printArray(int a[],int from){ int l = a.length; for(int i=from;i<l;++i){ print(a[i]); if(i!=l-1){ print(" "); } } println(); } void printArray(long a[],int from){ int l = a.length; for(int i=from;i<l;++i){ print(a[i]); if(i!=l-1){ print(" "); } } println(); } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
4e4da418d93f727efa569641d8414cc9
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public class Solution{ public static Integer INT(String s) { return Integer.parseInt(s); } public static Long LONG(String s) { return Long.parseLong(s); } static int mod=(int)1e9+7, oo=Integer.MAX_VALUE, _oo=Integer.MIN_VALUE; static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static Scanner in=new Scanner(System.in); static StringBuilder out=new StringBuilder(); //================================================================================================================================================== public static void main(String args[]) throws IOException { int t=in.nextInt(); while(t--!=0) { int n=in.nextInt(), sum, min=(n<<1), diff=0; int a[]=new int[n*2]; for(int i=0; i<(n<<1); i++) { a[i]=in.nextInt()==1?+1:-1; diff+=a[i]; } HashMap<Integer, Integer> map=new HashMap<>(); map.put(0, -1); sum=0; for(int i=0; i<n; i++) { sum+=a[i]; map.put(sum, i); if(sum==0) min=(n<<1)-(i+1); } sum=0; for(int i=(n<<1)-1; i>=n; i--) { sum+=a[i]; if(map.containsKey(-sum)) min=Math.min(min, i-map.get(-sum)-1); if(sum==0) min=Math.min(min, i); } out.append(min+"\n"); } System.out.print(out); } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
50fd2b9a76b60f61f5703a4616602d2b
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class berryjam { public static void main(String[] args) throws IOException { FastScanner scan = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = scan.nextInt(); for (int cases = 0; cases < t; cases++) { int n = scan.nextInt(); int[] jams = new int[2*n]; int total = 0; for (int i = 0; i < 2*n; i++) { int aaa = scan.nextInt(); if (aaa == 2) { jams[i] = -1; total--; } else { jams[i] = 1; total++; } } int[] sum = new int[2*n]; sum[n-1] = jams[n-1]; sum[n] = jams[n]; for (int i = n-1-1; i >= 0; i--) { sum[i] = sum[i+1]+jams[i]; } for (int i = n+1; i < 2*n; i++) { sum[i] = sum[i-1]+jams[i]; } int[] index = new int[4*n+1]; Arrays.fill(index, -1); for (int i = 0; i < n; i++) { index[sum[i]+2*n] = n-i; } index[2*n] = 0; long ans = 2*n; //System.out.println(ans); if (index[total+2*n] != -1) ans = Math.min(ans, index[total+2*n]); //for (int i : sum) System.out.print(i + " "); System.out.println(""); //for (int i : index) System.out.print(i + " "); System.out.println(""); for (int i = n; i < 2*n; i++) { //System.out.println(i-n + " " + index[total-sum[i]+2*n]); if (index[total-sum[i]+2*n] != -1) ans = Math.min(ans, index[total-sum[i]+2*n] + i-n+1); } //if (total == 0) ans = 0; out.println(ans); } out.close(); } public static void shuffle(int[] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int rPos = rgen.nextInt(arr.length); int temp = arr[i]; arr[i] = arr[rPos]; arr[rPos]=temp; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
2ee7e289f1d3ad42bcd4954c9136a725
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class berryJar { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int t=scn.nextInt(); while(t-- !=0) { int n=scn.nextInt(); int[]arr=new int[2*n]; int diff=0; for(int i=0;i<2*n;i++) { arr[i]=scn.nextInt(); if(arr[i]==1) diff++; else diff--; } if(diff==0) { System.out.println("0"); continue; } HashMap<Integer,Integer>map=new HashMap(); map.put(0,0); int curr=0; for(int i=n;i<2*n;i++) { if(arr[i]==1) curr++; else curr--; if(!map.containsKey(curr)) map.put(curr,i-n+1); } curr=0; int ans=2*n; if(map.containsKey(diff)) { ans=Math.min(ans,map.get(diff)); } for(int i=n-1;i>=0;i--) { if(arr[i]==1) curr++; else curr--; if(map.containsKey(diff-curr)) { ans=Math.min(ans,n-i+map.get(diff-curr)); } } System.out.println(ans); } } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
082cc4c3512acbea86d745a7f9e8e191
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.awt.image.BandedSampleModel; import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); StringTokenizer st=new StringTokenizer(br.readLine()); int test=Integer.parseInt(st.nextToken()); while(test-->0){ st=new StringTokenizer(br.readLine()); int n=Integer.parseInt(st.nextToken()); int[] arr=new int[2*n]; int gap=0; st=new StringTokenizer(br.readLine()); for(int i=0;i<2*n;i++) { arr[i] = Integer.parseInt(st.nextToken()); if (arr[i] == 1) { gap++; } else { gap--; } } if(gap==0){ pw.println("0"); continue; } HashMap<Integer,Integer> map=new HashMap<>(); int intial=gap; gap=0; int ans=Integer.MAX_VALUE; for(int i=n;i<2*n;i++){ if(arr[i]==1){ gap++; }else { gap--; } if(intial==gap){ if(i-n+1<ans){ ans=i-n+1; } } if(gap!=0){ if(!map.containsKey(gap)){ map.put(gap,i-n+1); } } } gap=0; for(int i=n-1;i>=0;i--){ if(arr[i]==1){ gap++; }else { gap--; } if(intial==gap){ if(n-i<ans){ ans=n-i; } } if(gap!=0){ if(map.containsKey(intial-gap)){ if((map.get(intial-gap)+n-i)<ans){ ans=(map.get(intial-gap)+n-i); } } } } pw.println(ans); } pw.close(); } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
13c3bc0bbcad1f990bff2f651090b4d2
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class SOlution { public static void main(String ag[]) { Scanner sc=new Scanner(System.in); int i,j,k; int T=sc.nextInt(); while(T-->0) { int N=sc.nextInt(); int A[]=new int[2*N+1]; for(i=1;i<=2*N;i++) A[i]=sc.nextInt(); int diff[]=new int[2*N+1]; int one=0; int two=0; for(i=1;i<=N;i++) { if(A[i]==1) one++; else two++; diff[i]=one-two; } one=two=0; for(i=2*N;i>N;i--) { if(A[i]==1) one++; else two++; diff[i]=one-two; } HashMap<Integer,Integer> hm=new HashMap<>(); int max=0;; for(i=1;i<=N;i++) { hm.put(diff[i],i); if(diff[i]==0) max=i; } for(i=2*N;i>N;i--) { if(diff[i]==0) max=Math.max(max,2*N-i+1); if(hm.get(diff[i]*-1)!=null) max=Math.max(max,(2*N-i+1)+hm.get(diff[i]*-1)); } System.out.println(2*N-max); } } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
d2ff88f06098555d6194b1623fb8cfdd
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
/** * Alipay.com Inc. Copyright (c) 2004-2019 All Rights Reserved. */ import java.util.HashMap; import java.util.Map; import java.util.Scanner; /** * * @author linwanying * @version $Id: BerryJam.java, v 0.1 2019年12月28日 5:18 PM linwanying Exp $ */ public class BerryJam { public static void main(String[] args) { new BerryJam().run(); } private void run() { Scanner scanner = new Scanner(System.in); int number = scanner.nextInt(); while (number-->0){ int n = scanner.nextInt(); Map<Integer, Integer> a = new HashMap<>(n); int a1 = 0; int a2 = 0; int res = 2*n; for (int i = 0; i < n; ++i) { int cur = scanner.nextInt(); if (cur == 1) a1++; if (cur == 2) a2++; a.put(a1-a2, i); if (a1-a2 == 0) { res = 2*n-1-i; } } int[] b = new int[n]; for (int i = 0; i < n; ++i) { b[i] = scanner.nextInt(); } int b1 = 0; int b2 = 0; for (int i = n-1; i >= 0; --i) { if (b[i] == 1) b1++; if (b[i] == 2) b2++; if (a.containsKey(b2-b1)) { int ai = a.get(b2-b1); res = Math.min(res, n-1-ai+i); } if (b2-b1 == 0) { res = Math.min(res, n+i); } } System.out.println(res); } } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
82e7cf12ee2c684ba6d206b88868b4c3
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) throws Exception{ MScanner sc=new MScanner(System.in); PrintWriter pw=new PrintWriter(System.out); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int[]in=new int[2*n]; for(int i=0;i<2*n;i++) { in[i]=sc.nextInt(); if(in[i]==2) { in[i]=-1; } } TreeSet<Integer>suff[]=new TreeSet[4*n+7]; for(int i=0;i<suff.length;i++) { suff[i]=new TreeSet<Integer>(); } int shift=2*n; int suffix=shift; for(int i=2*n;i>=n;i--) { suffix+=i==2*n?0:in[i]; suff[suffix].add(i); } int prefix=shift; int ans=2*n; for(int i=-1;i<n;i++) { prefix+=((i==-1)?0:in[i]); int z=prefix-shift; z*=-1; z+=shift; //System.out.println(shift+" "+prefix+" "+z); if(suff[z].isEmpty())continue; Integer idx=suff[z].first(); if(idx!=null) { //System.out.println(i+" "+(idx-i-1)); //System.out.println(prefix-shift+" "+i+" "+(z-shift)); //System.out.println(suff[z]); ans=Math.min(ans, idx-i-1); } } pw.println(ans); } pw.flush(); } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] takearr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] takearrl(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public Integer[] takearrobj(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] takearrlobj(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
1228fff27de2cac0c910304e3c4fdf0f
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int[] arr=new int[2*n]; int a=0,b=0,c=0,d=0; HashMap<Integer,Integer> map1=new HashMap(); HashMap<Integer,Integer> map2=new HashMap(); for(int i=0;i<2*n;i++) { arr[i]=sc.nextInt(); if(arr[i]==1) a++; else b++; if(i>=n) { if(arr[i]==1) c++; else d++; if(c>d) { if(!map1.containsKey(c-d)) map1.put(c-d,i); } if(d>c) { if(!map2.containsKey(d-c)) map2.put(d-c,i); } } } int x=Math.max(a,b)-Math.min(a,b); int m= x==0?0:2*n; map1.put(0,n-1); map2.put(0,n-1); if(x>0) { if(a>b) { if(map1.containsKey(x)) m=Math.min(m,map1.get(x)-n+1); for(int i=n-1;i>=0;i--) { if(arr[i]==1) x--; else x++; if(map1.containsKey(x)) m=Math.min(m,map1.get(x)-i+1); } } else { if(map2.containsKey(x)) m=Math.min(m,map2.get(x)-n+1); for(int i=n-1;i>=0;i--) { if(arr[i]==2) x--; else x++; if(map2.containsKey(x)) m=Math.min(m,map2.get(x)-i+1); } } } System.out.println(m); } } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
746405b394e75d6f892f5841a342ff97
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
/* Rajkin Hossain */ import java.io.*; import java.util.*; import static java.lang.Math.*; public class C{ FastInput k = new FastInput(System.in); //FastInput k = new FastInput("/home/rajkin/Desktop/input.txt"); FastOutput z = new FastOutput(); HashMap<Integer, Integer> right; int [] y, yy; int [] data; int one, two; void startProgram() { int t = k.nextInt(); while(t-->0) { int n = k.nextInt(); y = new int[n]; yy = new int[n*2]; data = new int[n]; one = two = 0; int sum = 0; right = new HashMap<Integer, Integer>(); int min = Integer.MAX_VALUE; for(int i = 0; i<n; i++) { data[i] = k.nextInt(); if(data[i] == 1) { sum--; one++; } else { sum++; two++; } y[i] = sum; if(sum == 0) { min = Math.min(min, (((2*n) - 1) - (i+1)) + 1); } } for(int i = n; i<(n*2); i++) { yy[i] = k.nextInt(); if(yy[i] == 1) { one++; } else { two++; } } int oneS = one; int twoS = two; sum = 0; for(int i = (2*n-1); i>=n; i--) { if(yy[i] == 1) { sum--; } else { sum++; } if(sum == 0) { min = Math.min(min, i); } right.put(sum, i); } for(int i = n-1; i>=0; i--) { if(right.containsKey(-y[i])) { int index = right.get(-y[i]); min = Math.min(min, index - i - 1); } } int count = 0; for(int i = n-1; i>=0; i--) { if(data[i] == 1) { one--; } else { two--; } count++; if(one == two) { min = Math.min(min, count); } } count = 0; one = oneS; two = twoS; for(int i = n; i<(2*n); i++) { if(yy[i] == 1) { one--; } else { two--; } count++; if(one == two) { min = Math.min(min, count); } } z.println(min == Integer.MAX_VALUE ? (n*2) : min); } z.flush(); System.exit(0); } class Pair implements Comparable<Pair>{ int value; int index; public Pair(int value, int index) { this.value = value; this.index = index; } @Override public int compareTo(Pair p) { return this.value - p.value; } } public static void main(String [] args) throws IOException { new Thread(null, new Runnable(){ public void run(){ try{ new C().startProgram(); } catch(Exception e){ e.printStackTrace(); } } },"Main",1<<28).start(); } /* MARK: FastInput and FastOutput */ class FastInput { BufferedReader reader; StringTokenizer tokenizer; FastInput(InputStream stream){ reader = new BufferedReader(new InputStreamReader(stream)); } FastInput(String path){ try { reader = new BufferedReader(new FileReader(path)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } tokenizer = null; } String next() { return nextToken(); } String nextLine() { try { return reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } boolean hasNext(){ try { return reader.ready(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } String nextToken() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String line = null; try { line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } tokenizer = new StringTokenizer(line); } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.valueOf(nextToken()); } int [] getInputIntArray(int n) { int [] input = new int[n]; for(int i = 0; i<n; i++) { input[i] = nextInt(); } return input; } long [] getInputLongArray(int n) { long [] input = new long[n]; for(int i = 0; i<n; i++) { input[i] = nextLong(); } return input; } int [] getInputIntArrayOneBasedIndex(int n) { int [] input = new int[n+1]; for(int i = 1; i<=n; i++) { input[i] = nextInt(); } return input; } long [] getInputLongArrayOneBasedIndex(int n) { long [] input = new long[n+1]; for(int i = 1; i<=n; i++) { input[i] = nextLong(); } return input; } void fill2DIntArray(int [][] array, int value) { for(int i = 0; i<array.length; i++) { for(int j = 0; j<array[0].length; j++) { array[i][j] = value; } } } void fill2DLongArray(long [][] array, long value) { for(int i = 0; i<array.length; i++) { for(int j = 0; j<array[0].length; j++) { array[i][j] = value; } } } void fill3DIntArray(int [][][] array, int value) { for(int i = 0; i<array.length; i++) { for(int j = 0; j<array[0].length; j++) { for(int k = 0; k<array[0][0].length; k++) { array[i][j][k] = value; } } } } void fill3DLongArray(long [][][] array, long value) { for(int i = 0; i<array.length; i++) { for(int j = 0; j<array[0].length; j++) { for(int k = 0; k<array[0][0].length; k++) { array[i][j][k] = value; } } } } } class FastOutput extends PrintWriter { FastOutput() { super(new BufferedOutputStream(System.out)); } public void debug(Object...obj) { System.err.println(Arrays.deepToString(obj)); } } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
c3fb1ac975bbe07b7ce4103a7a870b8c
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
// package Education78; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; public class ProblemC { public static void print(int a[]){ for(int i=0;i<a.length;i++){ System.out.print(a[i]+" "); } System.out.println(); } public static void main(String[] args)throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int test=Integer.parseInt(br.readLine()); StringBuilder print=new StringBuilder(); while(test--!=0){ int n=Integer.parseInt(br.readLine()); int a[]=new int[2*n+1]; String line[]=br.readLine().split(" "); int red[]=new int[2*n+2]; int white[]=new int[2*n+2]; for(int i=1;i<=2*n;i++){ a[i]=Integer.parseInt(line[i-1]); } int psleft[]=new int[n+1]; int psright[]=new int[n+1]; for(int i=1;i<=n;i++){ if(a[i]==1){ white[i]=white[i-1]+1; red[i]=red[i-1]; } else{ white[i]=white[i-1]; red[i]=red[i-1]+1; } } for(int i=2*n;i>n;i--){ if(a[i]==1){ white[i]=white[i+1]+1; red[i]=red[i+1]; } else{ white[i]=white[i+1]; red[i]=red[i+1]+1; } } HashMap<Integer,Integer> left=new HashMap<>(); HashMap<Integer,Integer> right=new HashMap<>(); for(int i=0;i<=n;i++){ psleft[i]=white[i]-red[i]; psright[i]=red[i+n+1]-white[i+n+1]; left.put(psleft[i],i); } for(int i=n;i>=0;i--){ right.put(psright[i],i); } int ans=2*n; for(int i=1;i<=n;i++){ int l=psleft[i]; // System.out.println(l); if(right.containsKey(l)){ // System.out.println(l); int j=right.get(l); ans=Math.min(ans,n-i+j); } // System.out.println(ans); } // System.out.println(left.toString()); // System.out.println(right.toString()); // print(white); // print(red); // print(psleft); // print(psright); for(int i=0;i<n;i++){ int r=psright[i]; if(left.containsKey(r)){ int j=left.get(r); ans=Math.min(ans,i+n-j); } } print.append(ans+"\n"); } System.out.println(print.toString()); } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
ece4d50c3ef56df2ee5ec98093b95f23
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.StringTokenizer; public class C_Berry_Jam { public static void main(String[] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int T = sc.nextInt(); while(T-- > 0) { int N = sc.nextInt(); //# of 2s - # of 1s int delta = 0; int[] left = new int[N]; for (int i = 0; i < left.length; i++) { left[i] = sc.nextInt(); delta += left[i] == 2 ? +1 : -1; } int[] right = new int[N]; for (int i = 0; i < right.length; i++) { right[i] = sc.nextInt(); delta += right[i] == 2 ? +1 : -1; } int runningTotal; //Value, min jars removed HashMap<Integer, Integer> possibleLeft = new HashMap<>(); possibleLeft.put(0, 0); runningTotal = 0; for(int i = N - 1; i >= 0; i--) { runningTotal += left[i] == 2 ? -1 : +1; if(possibleLeft.get(runningTotal) == null) { possibleLeft.put(runningTotal, N - i); } } //Value, min jars removed HashMap<Integer, Integer> possibleRight = new HashMap<>(); possibleRight.put(0, 0); runningTotal = 0; for(int i = 0; i < N; i++) { runningTotal += right[i] == 2 ? -1 : +1; if(possibleRight.get(runningTotal) == null) { possibleRight.put(runningTotal, i + 1); } } int ans = Integer.MAX_VALUE; for(int l_val : possibleLeft.keySet()) { int r_val = -delta - l_val; if(possibleRight.get(r_val) != null) { ans = Math.min(ans, possibleLeft.get(l_val) + possibleRight.get(r_val)); } } out.println(ans); } out.close(); } 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; } } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
e1e2c6e895bf18fece392186e32f69cd
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main{ public static class FastReader { BufferedReader br; StringTokenizer root; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (root == null || !root.hasMoreTokens()) { try { root = new StringTokenizer(br.readLine()); } catch (Exception r) { r.printStackTrace(); } } return root.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception r) { r.printStackTrace(); } return str; } } public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); static long mod = (long) (1e9+7); static long cf = 998244353; static final long MAX = (long) 1e8; public static List<Integer>[] edges; public static int[][] parent; public static long[] fac; public static int N = (int) 1e5; public static void main(String[] args) { FastReader sc = new FastReader(); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int b = 0,r = 0; Map<Integer,Integer> map = new HashMap<>(); int[] a = new int[2*n+1]; for(int i=1;i<=2*n;++i) { a[i] = sc.nextInt(); } map.put(0, 2*n+1); for(int i=2*n;i>n;--i) { if(a[i] == 1) ++r; else ++b; map.put(r-b, i); } r = 0; b= 0; int ans = 2*n; ans = Math.min(ans,map.get(0)-1); for(int i=1;i<=n;++i) { if(a[i] == 1) ++r; else ++b; if(map.containsKey(b-r)) ans = Math.min(ans,map.get(b-r)-i-1); } out.println(ans); } out.close(); } static class Pair{ int x; int y; Pair(int x,int y){ this.x=x; this.y=y; } @Override public int hashCode() { final int prime = 31; int result = prime * x + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (x != other.x && y != other.y) return false; return true; } @Override public String toString() { return "{"+String.valueOf(x)+","+String.valueOf(y)+"}"; } } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
e60597834a92d705aa7fbd46d955a344
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main{ public static class FastReader { BufferedReader br; StringTokenizer root; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (root == null || !root.hasMoreTokens()) { try { root = new StringTokenizer(br.readLine()); } catch (Exception r) { r.printStackTrace(); } } return root.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception r) { r.printStackTrace(); } return str; } } public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); static long mod = (long) (1e9+7); static long cf = 998244353; static final long MAX = (long) 1e8; public static List<Integer>[] edges; public static int[][] parent; public static long[] fac; public static int N = (int) 1e5; public static void main(String[] args) { FastReader sc = new FastReader(); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int b = 0,r = 0; Map<Integer,TreeSet<Integer>> map = new HashMap<>(); int[] a = new int[2*n+1]; for(int i=1;i<=2*n;++i) { a[i] = sc.nextInt(); } add(map,0,2*n+1); for(int i=2*n;i>n;--i) { if(a[i] == 1) ++r; else ++b; add(map,r-b,i); } r = 0; b= 0; int ans = 2*n; ans = Math.min(ans,map.get(0).first()-1); for(int i=1;i<=n;++i) { if(a[i] == 1) ++r; else ++b; if(map.containsKey(b-r)) { ans = Math.min(ans,map.get(b-r).first()-i-1); } } out.println(ans); } out.close(); } private static void add(Map<Integer, TreeSet<Integer>> map, int j, int i) { // TODO Auto-generated method stub if(map.containsKey(j)) map.get(j).add(i); else { TreeSet<Integer> set = new TreeSet<Integer>(); set.add(i); map.put(j, set); } } static class Pair{ int x; int y; Pair(int x,int y){ this.x=x; this.y=y; } @Override public int hashCode() { final int prime = 31; int result = prime * x + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (x != other.x && y != other.y) return false; return true; } @Override public String toString() { return "{"+String.valueOf(x)+","+String.valueOf(y)+"}"; } } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
0657cee9c4c37b79ee1f236ccea12115
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Collections; import java.util.HashMap; import java.util.PriorityQueue; import java.util.Scanner; import java.util.StringTokenizer; public class gef { public static void main(String[] args) { Scanner sc = new Scanner(System.in); StringTokenizer st = new StringTokenizer(sc.nextLine()); int T = Integer.parseInt(st.nextToken()); StringBuilder sb = new StringBuilder(); for(int qw=0; qw < T; qw++) { int N = Integer.parseInt(sc.nextLine()); int[] arr = new int[N << 1]; st = new StringTokenizer(sc.nextLine()); for(int i=0; i < N << 1; i++) arr[i] = Integer.parseInt(st.nextToken())-1; int red = 0; int blue = 0; for(int x: arr) blue += x; red = 2*N-blue; int diff = red-blue; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); map.put(0, 0); int curr = 0; for(int i=N-1; i >= 0; i--) { curr--; if(arr[i] == 0) curr+=2; if(!map.containsKey(curr)) map.put(curr, N-i); } curr = 0; int res = 2*N; if(map.containsKey(diff)) res = Math.min(res, map.get(diff)); for(int i=N; i < 2*N; i++) { curr--; if(arr[i] == 0) curr+=2; if(map.containsKey(diff-curr)) res = Math.min(res, i+1-N+map.get(diff-curr)); } sb.append(res+"\n"); } System.out.print(sb); } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
60ddf34e5da958d1ab6910132497b7bd
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class berryJar { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int t=scn.nextInt(); while(t-- !=0) { int n=scn.nextInt(); int[]arr=new int[2*n]; int diff=0; for(int i=0;i<2*n;i++) { arr[i]=scn.nextInt(); if(arr[i]==1) diff++; else diff--; } if(diff==0) { System.out.println("0"); continue; } HashMap<Integer,Integer>map=new HashMap(); map.put(0,0); int curr=0; for(int i=n;i<2*n;i++) { if(arr[i]==1) curr++; else curr--; if(!map.containsKey(curr)) map.put(curr,i-n+1); } curr=0; int ans=2*n; if(map.containsKey(diff)) { ans=Math.min(ans,map.get(diff)); } for(int i=n-1;i>=0;i--) { if(arr[i]==1) curr++; else curr--; if(map.containsKey(diff-curr)) { ans=Math.min(ans,n-i+map.get(diff-curr)); } } System.out.println(ans); } } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
ed5b8e4d4a58aca2df1c3526382645c2
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.StringTokenizer; public class CTask { private static final String QUICK_ANSWER = "NO"; private final Input in; private final StringBuilder out; public CTask(Input in, StringBuilder out) { this.in = in; this.out = out; } public void solve() throws QuickAnswer { int n = nextInt(); int[] a = nextInts(2 * n); int cnt1 = 0; for (int i : a) { if (i == 1) ++cnt1; } if (cnt1 == n) { print(0); return; } cnt1 -= n; cnt1 *= 2; int curr = 0; for (int i = 0; i < n; i++) { if (a[i] == 1) ++curr; else --curr; } int[] pos = new int[2 * n + 1]; Arrays.fill(pos, -1_000_000); pos[n + curr] = -1; for (int i = 0; i < n; i++) { if (a[i] == 1) --curr; else ++curr; pos[n + curr] = i; } int min = n + cnt1 < 0 || n + cnt1 > 2 * n ? 1_000_000 : n -1 - pos[n + cnt1]; curr = 0; for (int i = 0; i < n; i++) { if (a[n + i] == 1) ++curr; else --curr; if (n + cnt1 - curr < 0 || n + cnt1 - curr > 2 * n) continue; if (pos[n + cnt1 - curr] == -1_000_000) continue; min = Math.min(min, n + i - pos[n + cnt1 - curr]); } print(min); } // Common functions private static class Input { private final BufferedReader in; private StringTokenizer tokenizer = null; public Input(BufferedReader in) { this.in = in; } String nextToken() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(in.readLine()); } catch (Exception e) { throw new RuntimeException(e); } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } String nextLine() { try { return in.readLine(); } catch (IOException e) { return ""; } } } void quickAnswer(String answer) throws QuickAnswer { throw new QuickAnswer(answer); } void quickAnswer() throws QuickAnswer { quickAnswer(QUICK_ANSWER); } static class QuickAnswer extends Exception { private String answer; public QuickAnswer(String answer) { this.answer = answer; } } void print(Object... args) { String prefix = ""; for (Object arg : args) { out.append(prefix); out.append(arg); prefix = " "; } } void println(Object... args) { print(args); out.append("\n"); } void printsp(Object... args) { print(args); out.append(" "); } int nextInt() { return in.nextInt(); } long nextLong() { return in.nextLong(); } String nextString() { return in.nextLine(); } int[] nextInts(int count) { int[] res = new int[count]; for (int i = 0; i < count; ++i) { res[i] = nextInt(); } return res; } int[][] nextInts(int count, int n) { int[][] res = new int[n][count]; for (int i = 0; i < count; ++i) { for (int j = 0; j < n; j++) { res[j][i] = nextInt(); } } return res; } long[] nextLongs(int count) { long[] res = new long[count]; for (int i = 0; i < count; ++i) { res[i] = nextLong(); } return res; } long[][] nextLongs(int count, int n) { long[][] res = new long[n][count]; for (int i = 0; i < count; ++i) { for (int j = 0; j < n; j++) { res[j][i] = nextLong(); } } return res; } public static void main(String[] args) { doMain(System.in, System.out); } static void doMain(InputStream inStream, PrintStream outStream) { Input in = new Input(new BufferedReader(new InputStreamReader(inStream))); StringBuilder totalOut = new StringBuilder(); int count = 1; count = in.nextInt(); while (count-- > 0) { try { StringBuilder out = new StringBuilder(); new CTask(in, out).solve(); totalOut.append(out.toString()); } catch (QuickAnswer e) { totalOut.append(e.answer); } if (count > 0) { totalOut.append("\n"); } } outStream.print(totalOut.toString()); } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
49d993a9336346310a9966008866d6a1
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class QC { private static int findVal(int[] ar, int n) { int cntA = 0; int cntB = 0; for (int i = 0; i < n; i++) { if (ar[i] == 1) { cntA++; } else if (ar[i] == 2) { cntB++; } } if (cntA == cntB) return 0; List<Integer> l1 = new ArrayList<>(); List<Integer> l2 = new ArrayList<>(); for (int i = n / 2 - 1; i >= 0; i--) { l1.add(ar[i]); } for (int i = n / 2; i < n; i++) { l2.add(ar[i]); } // System.out.println("l1=" + l1 + " l2=" + l2); HashMap<Integer, Integer> map = new HashMap<>(); int myCntA = 0; int myCntB = 0; map.put(0,-1); int min =Integer.MAX_VALUE; for (int i = 0; i < l1.size(); i++) { if (l1.get(i) == 1) { myCntA++; } else { myCntB++; } int diff = myCntA-myCntB; if(cntA-myCntA==cntB-myCntB){ min=Math.min(i+1, min); } if(map.get(diff)==null) { map.put(diff, i); } } // System.out.println(map); for (int i = 0; i < l2.size(); i++) { if (l2.get(i) == 1) { cntA--; } else { cntB--; } int diff = cntA-cntB; // System.out.println("cntA="+cntA+" cntB="+cntB); if (map.get(diff) != null) { int val = map.get(diff) + 1; int res = i + 1 +val; // System.out.println("i="+i+" val="+val+" res="+res); min=Math.min(min, res); } } return min; } public static void main(String[] args) { // File file = new File("/Users/chihohar/IdeaProjects/CodeForce/input/input_a.txt"); // Scanner scan = null; // try { // scan = new Scanner(file); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } Scanner scan = new Scanner(System.in); int t = scan.nextInt(); for (int i = 0; i < t; i++) { int n = scan.nextInt(); n *= 2; int[] ar = new int[n]; for (int j = 0; j < n; j++) { ar[j] = scan.nextInt(); } System.out.println(findVal(ar, n)); } } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
ca3cebc8c387eaf4a75160a8284724b7
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int q = scan.nextInt(); scan.nextLine(); for (int i = 0; i < q; i++) { handleQ(scan); } } private static void handleQ(Scanner scan) { int n = scan.nextInt(); int[] l = new int[n]; int[] r = new int[n]; for (int i = n - 1; i >= 0; i--) { l[i] = scan.nextInt(); } for (int i = 0; i < n; i++) { r[i] = scan.nextInt(); } l[0] = l[0] == 1 ? 1 : -1; r[0] = r[0] == 1 ? 1 : -1; for (int i = 1; i < n; i++) { l[i] = l[i] == 1 ? l[i - 1] + 1 : l[i - 1] - 1; r[i] = r[i] == 1 ? r[i - 1] + 1 : r[i - 1] - 1; } int dif = l[n - 1] + r[n - 1]; if (dif == 0) { System.out.println(0); return; } if (dif < 0) { dif = -dif; for (int i = 0; i < n; i++) { l[i] = -l[i]; r[i] = -r[i]; } } int[] indL = new int[dif + 1]; int[] indR = new int[dif + 1]; for (int i = 0; i < n; i++) { if (l[i] > 0) { if (l[i] > dif) { break; } if (indL[l[i]] == 0) { indL[l[i]] = i + 1; } } } for (int i = 0; i < n; i++) { if (r[i] > 0) { if (r[i] > dif) { break; } if (indR[r[i]] == 0) { indR[r[i]] = i + 1; } } } int min = 2 * n; if (indL[dif] > 0) { min = Math.min(min, indL[dif]); } if (indR[dif] > 0) { min = Math.min(min, indR[dif]); } for (int a = 1; a < dif; a++) { int b = dif - a; if (indL[a] > 0 && indR[b] > 0) { min = Math.min(min, indL[a] + indR[b]); } } System.out.println(min); } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
c397a5d02de104661a9a0ad9990af9ab
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.StringTokenizer; import java.io.PrintWriter; import java.io.*; import java.util.stream.Collectors.*; import java.lang.*; import static java.util.stream.Collectors.*; import static java.util.Map.Entry.*; public class Ideo { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class aksh { int x; int y; int moves; public aksh(int a,int b,int c) { x = a; y = b; moves=c; } } static int power(int x,int y) { int res = 1; // Initialize result // Update x if it is more than or // equal to p while (y > 0) { // If y is odd, multiply x with result if (y%2==1) res = (res*x); // y must be even now y = y>>1; // y = y/2 x = (x*x); } return res; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static boolean compareSeq(char[] S, int x, int y, int n) { for (int i = 0; i < n; i++) { if (S[x] < S[y]) return true; else if (S[x] > S[y]) return false; x = (x + 1) % n; y = (y + 1) % n; } return true; } static void build(long[] sum,int[] arr,int n) { for(int i=0;i<(1<<n);i++) { long total=0; for(int j=0;j<n;j++) { if((i & (1 << j)) > 0) total+=arr[j]; } sum[i]=total; } } static int count(long arr[], long x, int n) { int l=0; int h=n-1; int res=-1; int mid=-1; while(l<=h) { mid=l+(h-l)/2; if(x==arr[mid]) { res=mid; h=mid-1; } else if(x<arr[mid]) h=mid-1; else l=mid+1; } if(res==-1) return 0; //res is first index and res1 is last index of an element in a sorted array total number of occurences is (res1-res+1) int res1=-1; l=0; h=n-1; while(l<=h) { mid=l+(h-l)/2; if(x==arr[mid]) { res1=mid; l=mid+1; } else if(x<arr[mid]) h=mid-1; else l=mid+1; } if(res1==-1) return 0; if(res!=-1 && res1!=-1) return (res1-res+1); return 0; } static int parity(int a) { a^=a>>16; a^=a>>8; a^=a>>4; a^=a>>2; a^=a>>1; return a&1; } /* PriorityQueue<aksh> pq = new PriorityQueue<>((o1, o2) -> { if (o1.p < o2.p) return 1; else if (o1.p > o2.p) return -1; else return 0; });//decreasing order acc to p*/ static int power(int x, int y, int m) { if (y == 0) return 1; int p = power(x, y / 2, m) % m; p = (p * p) % m; if (y % 2 == 0) return p; else return (x * p) % m; } static int modinv(int a, int m) { int g = gcd(a, m); if (g != 1) return 0; else { return power(a, m - 2, m); } //return 0; } static int[] product(int[] nums) { int[] result = new int[nums.length]; int[] t1 = new int[nums.length]; int[] t2 = new int[nums.length]; t1[0]=1; t2[nums.length-1]=1; //scan from left to right for(int i=0; i<nums.length-1; i++){ t1[i+1] = nums[i] * t1[i]; } //scan from right to left for(int i=nums.length-1; i>0; i--){ t2[i-1] = t2[i] * nums[i]; } for(int i=0;i<nums.length;i++) { System.out.print(t1[i]+" "+t2[i]); System.out.println(); } //multiply for(int i=0; i<nums.length; i++){ result[i] = t1[i] * t2[i]; } return result; } static int getsum(int[] bit,int ind) { int sum=0; while(ind>0) { sum+=bit[ind]; ind-= ind & (-ind); } return sum; } static void update(int[] bit,int max,int ind,int val) { while(ind<=max) { bit[ind]+=val; ind+= ind & (-ind); } } static ArrayList<Integer>[] adj; static int[] bfs(ArrayList<Integer>[] adj,int n,ArrayList<Integer> arr) { int[] vis=new int[n]; int[] dis=new int[n]; int[] par=new int[n]; Queue<Integer> q=new LinkedList<>(); Arrays.fill(dis,-1); for(int i=0;i<arr.size();i++) { vis[arr.get(i)]=1; dis[arr.get(i)]=0; par[arr.get(i)]=-1; q.add(arr.get(i)); } while(!q.isEmpty()) { int x=q.remove(); for(int u:adj[x]) { if(vis[u]==0) { vis[u]=1; dis[u]=dis[x]+1; par[u]=x; q.add(u); } } } return dis; } static boolean check(long mid,long a,long b) { long count=1; while(count<=mid) { count++; if(a<b) a+=count; else b+=count; if(a==b) return true; } return false; } static class a1 implements Comparable<a1> { int p; int q; public a1(int p,int q) { this.p=p; this.q=q; } public int compareTo(a1 o) { return p-o.p; } } static int get(int arr[], int n) { int result = 0; int x, sum; // Iterate through every bit for(int i=0; i<32; i++) { // Find sum of set bits at ith position in all // array elements sum = 0; x = (1 << i); for(int j=0; j<n; j++) { if((arr[j] & x)!=0) sum++; } // The bits with sum not multiple of 3, are the // bits of element with single occurrence. if ((sum % 3)!=0) result |= x; } return result; } /* Collections.sort(orders, new Comparator<Point>() { @Override public int compare(Point o1, Point o2) { if (o1.diff < o2.diff) { return -1; } else if (o1.diff > o2.diff) { return 1; } else { return 0; } } }); */ static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static int nextPrime(int N) { // Base case if (N <= 1) return (2-N); int prime = N; boolean found = false; // Loop continuously until isPrime returns // true for a number greater than n while (!found) { if (isPrime(prime)) { found = true; break; } prime++; } return (prime-N); } static long product(long x) { long prod = 1; while (x > 0) { prod *= (x % 10); x /= 10; } return prod; } // This function returns the number having // maximum product of the digits static long findNumber(long l, long r) { // Converting both integers to strings //string a = l.ToString(); String b = Long.toString(r); // Let the current answer be r long ans = r; for (int i = 0; i < b.length(); i++) { if (b.charAt(i) == '0') continue; // Stores the current number having // current digit one less than current // digit in b char[] curr = b.toCharArray(); curr[i] = (char)(((int)(curr[i] - (int)'0') - 1) + (int)('0')); // Replace all following digits with 9 // to maximise the product for (int j = i + 1; j < curr.length; j++) curr[j] = '9'; // Convert string to number int num = 0; for (int j = 0; j < curr.length; j++) num = num * 10 + (curr[j] - '0'); // Check if it lies in range and its product // is greater than max product if (num >= l && product(ans) < product(num)) ans = num; } return product(ans); } static final long INF = Long.MAX_VALUE/5; public static void main(String args[] ) throws Exception { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ FastReader sc=new FastReader(); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int[] a=new int[n+1]; int currl=0; int currr=0; HashMap<Integer,Integer> h=new HashMap<>(); h.put(0,0); for(int i=1;i<=n;i++) { int x=sc.nextInt(); if(x==1) currl+=1; else currl-=1; a[i]=currl; } for(int i=1;i<=n;i++) { int x=sc.nextInt(); if(x==1) currr+=1; else currr-=1; if(!h.containsKey(currr)) h.put(currr,i); } int tot=currl+currr; int best=Integer.MAX_VALUE; for(int i=0;i<=n;i++) { int temp=tot - (a[n]-a[i]); //eat from left (last i jars) if(h.containsKey(temp)) best=Math.min(best,(n-i)+h.get(temp)); } System.out.println(best); } } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
61e7ae21f5fac13a6079a55d15783169
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); CBerryJam solver = new CBerryJam(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } } static class CBerryJam { public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); int[] a = new int[n]; int[] b = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.readInt() == 1 ? 1 : -1; } for (int i = 0; i < n; i++) { b[i] = in.readInt() == 1 ? 1 : -1; } IntHashMap map = new IntHashMap(n, false); PreSum psOfA = new PreSum(a); PreSum psOfB = new PreSum(b); int inf = (int) 1e8; for (int i = 0; i < n; i++) { map.put((int) psOfB.post(i), Math.min(i, map.getOrDefault((int) psOfB.post(i), inf))); } map.put(0, Math.min(n, map.getOrDefault(0, inf))); int ans = n * 2; for (int i = 0; i < n; i++) { int diff = (int) psOfA.prefix(i); ans = Math.min(ans, n - 1 - i + map.getOrDefault(-diff, inf)); } ans = Math.min(ans, n + map.getOrDefault(0, inf)); out.println(ans); } } static class FastInput { private final InputStream is; private StringBuilder defaultStringBuf = new StringBuilder(1 << 13); private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public String next() { return readString(); } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } } static interface IntEntryIterator { boolean hasNext(); void next(); int getEntryKey(); int getEntryValue(); } static class IntHashMap { private int[] slot; private int[] next; private int[] keys; private int[] values; private int alloc; private boolean[] removed; private int mask; private int size; private boolean rehash; public IntHashMap(int cap, boolean rehash) { this.mask = (1 << (32 - Integer.numberOfLeadingZeros(cap - 1))) - 1; slot = new int[mask + 1]; next = new int[cap + 1]; keys = new int[cap + 1]; values = new int[cap + 1]; removed = new boolean[cap + 1]; this.rehash = rehash; } private void doubleCapacity() { int newSize = Math.max(next.length + 10, next.length * 2); next = Arrays.copyOf(next, newSize); keys = Arrays.copyOf(keys, newSize); values = Arrays.copyOf(values, newSize); removed = Arrays.copyOf(removed, newSize); } public void alloc() { alloc++; if (alloc >= next.length) { doubleCapacity(); } next[alloc] = 0; removed[alloc] = false; size++; } private void rehash() { int[] newSlots = new int[Math.max(16, slot.length * 2)]; int newMask = newSlots.length - 1; for (int i = 0; i < slot.length; i++) { if (slot[i] == 0) { continue; } int head = slot[i]; while (head != 0) { int n = next[head]; int s = hash(keys[head]) & newMask; next[head] = newSlots[s]; newSlots[s] = head; head = n; } } this.slot = newSlots; this.mask = newMask; } private int hash(int x) { return x ^ (x >>> 16); } public void put(int x, int y) { put(x, y, true); } public void put(int x, int y, boolean cover) { int h = hash(x); int s = h & mask; if (slot[s] == 0) { alloc(); slot[s] = alloc; keys[alloc] = x; values[alloc] = y; } else { int index = findIndexOrLastEntry(s, x); if (keys[index] != x) { alloc(); next[index] = alloc; keys[alloc] = x; values[alloc] = y; } else if (cover) { values[index] = y; } } if (rehash && size >= slot.length) { rehash(); } } public int getOrDefault(int x, int def) { int h = hash(x); int s = h & mask; if (slot[s] == 0) { return def; } int index = findIndexOrLastEntry(s, x); return keys[index] == x ? values[index] : def; } private int findIndexOrLastEntry(int s, int x) { int iter = slot[s]; while (keys[iter] != x) { if (next[iter] != 0) { iter = next[iter]; } else { return iter; } } return iter; } public IntEntryIterator iterator() { return new IntEntryIterator() { int index = 1; int readIndex = -1; public boolean hasNext() { while (index <= alloc && removed[index]) { index++; } return index <= alloc; } public int getEntryKey() { return keys[readIndex]; } public int getEntryValue() { return values[readIndex]; } public void next() { if (!hasNext()) { throw new IllegalStateException(); } readIndex = index; index++; } }; } public String toString() { IntEntryIterator iterator = iterator(); StringBuilder builder = new StringBuilder("{"); while (iterator.hasNext()) { iterator.next(); builder.append(iterator.getEntryKey()).append("->").append(iterator.getEntryValue()).append(','); } if (builder.charAt(builder.length() - 1) == ',') { builder.setLength(builder.length() - 1); } builder.append('}'); return builder.toString(); } } static class PreSum { private long[] pre; public PreSum(int n) { pre = new long[n]; } public void populate(long[] a) { int n = a.length; pre[0] = a[0]; for (int i = 1; i < n; i++) { pre[i] = pre[i - 1] + a[i]; } } public void populate(int[] a) { int n = a.length; pre[0] = a[0]; for (int i = 1; i < n; i++) { pre[i] = pre[i - 1] + a[i]; } } public PreSum(long[] a) { this(a.length); populate(a); } public PreSum(int[] a) { this(a.length); populate(a); } public long prefix(int i) { return pre[i]; } public long post(int i) { if (i == 0) { return pre[pre.length - 1]; } return pre[pre.length - 1] - pre[i - 1]; } } static class FastOutput implements AutoCloseable, Closeable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput println(int c) { cache.append(c).append('\n'); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
8e501cc1672af1c23e6c0e04a4808a9b
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
//package com.company; import java.util.HashMap; import java.util.Scanner; public class Main { public static void main(String[] args) { // write your code here StringBuilder sb = new StringBuilder(); Scanner s=new Scanner(System.in); int t=s.nextInt(); while(t-->00){ int n=s.nextInt();int[] a=new int[2*n];int c1=0;int c2=0; for(int i=0;i<2*n;i++){ a[i]=s.nextInt(); if(a[i]==1) c1++; else c2++; } int min=Integer.MAX_VALUE; if(c1>c2){int x=c1-c2;HashMap<Integer,Integer> h=new HashMap<Integer, Integer>(); int[] c=new int[2*n];h.put(0,n-1); for(int i=n;i<2*n;i++){ if(a[i]==1) c[i]=c[i-1]+1; else c[i]=c[i-1]-1; if(!h.containsKey(c[i])&&c[i]>=0){ h.put(c[i],i); } }//int min=0; if(h.containsKey(x)) min=h.get(x)-n+1; int[] c11=new int[n+1]; for(int i=n-1;i>=0;i--){ if(a[i]==1) c11[i]=c11[i+1]+1; else c11[i]=c11[i+1]-1; if(c11[i]>0&&x-c11[i]>=0&&h.containsKey(x-c11[i])) min=Math.min(min,n-i+h.get(x-c11[i])-n+1); } }else if(c1<c2){ int x=c2-c1;HashMap<Integer,Integer> h=new HashMap<Integer, Integer>(); int[] c=new int[2*n];h.put(0,n-1); for(int i=n;i<2*n;i++){ if(a[i]==2) c[i]=c[i-1]+1; else c[i]=c[i-1]-1; if(!h.containsKey(c[i])&&c[i]>=0){ h.put(c[i],i); } } if(h.containsKey(x)) min=Math.min(h.get(x)-n+1,min); int[] c11=new int[n+1]; for(int i=n-1;i>=0;i--){ if(a[i]==2) c11[i]=c11[i+1]+1; else c11[i]=c11[i+1]-1; if(c11[i]>0&&x-c11[i]>=0&&h.containsKey(x-c11[i])) min=Math.min(min,n-i+h.get(x-c11[i])-n+1); } } if(min==Integer.MAX_VALUE) min=0; sb.append(min+"\n"); } System.out.println(sb.toString()); } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
56ced0213e354bebebb670b01d108bcc
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class CF_HB_C { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); int arr[]=new int[2*n]; HashMap<Integer,Integer> hm=new HashMap<>(); int diff=0; for(int i=0;i<arr.length;++i) { arr[i]=sc.nextInt(); if(arr[i]==1) diff++; else diff--; } if(diff==0) { System.out.println(diff); continue; } int c=0; hm.put(0,0); for(int i=n;i<arr.length;++i) { if(arr[i]==1) c++; else c--; if(!hm.containsKey(c)) hm.put(c,i-n+1); } c=0; int min=2*n+1; ArrayList<Integer> arrayList=new ArrayList<>(); for(int i=n-1;i>=0;--i) { if(arr[i]==1) c++; else c--; if(hm.containsKey(diff-c)) min=Math.min(min,n-i+hm.get(diff-c)); } if(hm.containsKey(diff)) { min=Math.min(min,hm.get(diff)); } System.out.println(min); // int ac=0,bc=0; // for(int i=0;i<arr.length;++i) { // arr[i]= sc.nextInt(); // if(arr[i]==1) // ac++; // else // bc++; // } // if(ac==bc) { // System.out.println("0"); // continue; // } // int acount[]=new int[arr.length+1]; // int bcount[]=new int[arr.length+1]; // for(int i=1;i<acount.length;++i) // acount[i]=acount[i-1]+(arr[i-1]==1?1:0); // for(int i=1;i<bcount.length;++i) // bcount[i]=bcount[i-1]+(arr[i-1]==2?1:0); // int min=2*n+1; // for(int i=n-1;i>=0;--i) { // for(int j=n;j<arr.length;++j) { // int sac=acount[j+1]-acount[i]; // int sbc=bcount[j+1]-bcount[i]; // if(ac-sac==bc-sbc) { // min=Math.min(min,j-i+1); // } // int saca=acount[j+1]-acount[n]; // int sacb=bcount[j+1]-bcount[n]; // if(ac-saca==bc-sacb) { // min=Math.min(min,j-n+1); // } // } // int isaca=acount[n]-acount[i]; // int isacb=bcount[n]-bcount[i]; // if(ac-isaca==bc-isacb) { // min=Math.min(min,n-i); // } // } //System.out.println(min); } } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
f0cb1e5c13f370ee24e88e33719e590c
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public class Solution{ static PrintWriter out=new PrintWriter(System.out); public static void main (String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String[] input=br.readLine().trim().split(" "); int numTestCases=Integer.parseInt(input[0]); while(numTestCases-->0) { input=br.readLine().trim().split(" "); int n=Integer.parseInt(input[0]); int[] arr=new int[2*n]; input=br.readLine().trim().split(" "); for(int i=0;i<2*n;i++) { arr[i]=Integer.parseInt(input[i]); } out.println(minJars(arr)); } out.flush(); out.close(); } public static int minJars(int[] arr) { int n=arr.length; int half=n/2; HashMap<Integer,Integer> hash=new HashMap<>(); int net=0; // 1=increase // 2=decrease hash.put(0,n); for(int i=n-1;i>=half;i--){ if(arr[i]==1){ net++; } else{ net--; } hash.put(net,i); } int ans=n; net=0; if(hash.containsKey(0)){ int index=hash.get(0); int eaten=n-(n-1-index+1); ans=Math.min(ans,eaten); } for(int i=0;i<half;i++){ if(arr[i]==1){ net++; } else{ net--; } if(hash.containsKey(-net)){ int index=hash.get(-net); int eaten=n-(i+1+n-1-index+1); ans=Math.min(ans,eaten); } } return ans; } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
199c1b17f7f1b38b5020e68332301c0b
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class qc{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int a[]=new int[2*n]; int ans=2*n; int beg=0,end=2*n; int pref[]=new int[2*n]; int one=0,two=0; for(int i=0;i<2*n;i++){ a[i]=sc.nextInt(); if(a[i]==1)one++; else two++; } if(one==two){ System.out.println(0); continue; } if(a[0]==2) pref[0]=1; else pref[0]=-1; for(int i=1;i<2*n;i++){ if(a[i]==1)pref[i]=pref[i-1]-1; else pref[i]=pref[i-1]+1; } int suf[]=new int[2*n]; if(a[2*n-1]==2) suf[2*n-1]=1; else suf[2*n-1]=-1; for(int i=2*n-2;i>=0;i--){ if(a[i]==1)suf[i]=suf[i+1]-1; else suf[i]=suf[i+1]+1; } HashMap<Integer,Integer> hm=new HashMap<>(); int diff=two-one; //System.out.println(diff); if(diff==1){ if(a[n/2]==1 || a[n/2-1]==1){ System.out.println(1); continue; } } if(diff==-1){ if(a[n/2]==2 || a[n/2-1]==2){ System.out.println(1); continue; } } for(int i=a.length/2-2;i>=0;i--){ if(!hm.containsKey(pref[i]))hm.put(pref[i], i); } if(!hm.containsKey(0))hm.put(0, -1); //System.out.println(pref[5]); for(int i=a.length/2-1;i<a.length;i++){ if(hm.containsKey(pref[i]-diff)) ans=Math.min(i-hm.get(pref[i]-diff),ans); // System.out.println(ans+" ans "); } hm=new HashMap<>(); for(int i=a.length/2+1;i<a.length;i++){ if(!hm.containsKey(suf[i]))hm.put(suf[i], i); } if(!hm.containsKey(0))hm.put(0, 2*n); for(int i=a.length/2;i>=0;i--){ if(hm.containsKey(suf[i]-diff)) ans=Math.min(hm.get(suf[i]-diff)-i,ans); } System.out.println(ans); } } public static boolean check(int mid,int[] a){ int one=0,two=0; for(int i=0;i<a.length;i++){ if(a[i]==1)one++; else two++; } //int len=Math.max(a.length,a.length/2+mid); //System.out.println(mid+" mid"); //System.out.println("onet "+one+" "+two); for(int i=Math.max(a.length/2-mid,0),j=0;j<mid;i++,j++){ if(a[i]==1)one--; else two--; } //System.out.println("one "+one+" "+two); if(one==two )return true; for(int i=Math.max(a.length/2-mid,0);i<a.length/2;i++){ if( i+mid>=a.length) break; if(a[i]==1)one++; else two++; if(a[i+mid]==1)one--; else two--; if(one==two) return true; } return false; } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
b65f8c68ab65a4e81988a4eecf689e36
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public class Problem1278C { public static void main(String[] args) { Problem1278C instance = new Problem1278C(); BufferedReader bfr = null; try { bfr = new BufferedReader(new InputStreamReader(System.in)); String line = ""; int t = 0; if ((line = bfr.readLine()) != null) { t = Integer.parseInt(line); } int count = 0; while ((line = bfr.readLine()) != null) { int n = 0; n = Integer.parseInt(line); int[] l = new int[n]; int[] r = new int[n]; if ((line = bfr.readLine()) != null) { String[] tokens = line.split(" "); int oneCount = 0; int twoCount = 0; int eff = 0; Map<Integer, Integer> leftMap = new HashMap<Integer, Integer>(); for (int i = n - 1; i >= 0; i--) { int index = n - 1 - i; if (tokens[i].equalsIgnoreCase("1")) { oneCount++; eff--; } else { twoCount++; eff++; } l[index] = eff; if (!leftMap.containsKey(eff)) { leftMap.put(eff, index); } } eff = 0; Map<Integer, Integer> rightMap = new HashMap<Integer, Integer>(); for (int i = n; i < 2 * n; i++) { int index = i - n; if (tokens[i].equalsIgnoreCase("1")) { oneCount++; eff--; } else { twoCount++; eff++; } r[index] = eff; if (!rightMap.containsKey(eff)) { rightMap.put(eff, index); } } instance.process(leftMap, rightMap, oneCount, twoCount); } count++; if (count == t) break; } } catch (Throwable t) { System.err.println(t); } finally { if (bfr != null) { try { bfr.close(); } catch (IOException e) { e.printStackTrace(); } } } } private void process(Map<Integer, Integer> leftMap, Map<Integer, Integer> rightMap, int oneCount, int twoCount) { int diff = twoCount - oneCount; if (diff == 0) { System.out.println(0); return; } int min = Integer.MAX_VALUE; int leftIndex = -1; int rightIndex = -1; if (leftMap.containsKey(diff)) { int leftValue = leftMap.get(diff); leftIndex = leftValue; min = leftValue; } if (rightMap.containsKey(diff)) { int rightValue = rightMap.get(diff); if (rightValue < min) { leftIndex = -1; rightIndex = rightValue; min = rightValue; } } if (leftMap.size() < rightMap.size()) { for (Integer leftKey : leftMap.keySet()) { int leftValue = leftMap.get(leftKey); int rightKey = diff - leftKey; if (rightMap.containsKey(rightKey)) { int rightValue = rightMap.get(rightKey); if (leftValue + rightValue < min) { min = leftValue + rightValue; leftIndex = leftValue; rightIndex = rightValue; } } } } else { for (Integer rightKey : rightMap.keySet()) { int rightValue = rightMap.get(rightKey); int leftKey = diff - rightKey; if (leftMap.containsKey(leftKey)) { int leftValue = leftMap.get(leftKey); if (leftValue + rightValue < min) { min = leftValue + rightValue; leftIndex = leftValue; rightIndex = rightValue; } } } } System.out.println((2 + leftIndex + rightIndex)); } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
e0e74abbfab2e8e6cb8e728dea8d060d
train_004.jsonl
1576766100
Karlsson has recently discovered a huge stock of berry jam jars in the basement of the house. More specifically, there were $$$2n$$$ jars of strawberry and blueberry jam.All the $$$2n$$$ jars are arranged in a row. The stairs to the basement are exactly in the middle of that row. So when Karlsson enters the basement, he sees exactly $$$n$$$ jars to his left and $$$n$$$ jars to his right.For example, the basement might look like this: Being the starightforward man he is, he immediately starts eating the jam. In one minute he chooses to empty either the first non-empty jar to his left or the first non-empty jar to his right.Finally, Karlsson decided that at the end the amount of full strawberry and blueberry jam jars should become the same.For example, this might be the result: He has eaten $$$1$$$ jar to his left and then $$$5$$$ jars to his right. There remained exactly $$$3$$$ full jars of both strawberry and blueberry jam. Jars are numbered from $$$1$$$ to $$$2n$$$ from left to right, so Karlsson initially stands between jars $$$n$$$ and $$$n+1$$$.What is the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left?Your program should answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class Hello { public static TreeSet<Long> primeFactors(long n) { TreeSet<Long> res = new TreeSet<Long>(); // Print the number of 2s that divide n while (n % 2 == 0) { n /= 2; res.add((long) 2); } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (long i = 3; i <= Math.sqrt(n); i += 2) { // While i divides n, print i and divide n while (n % i == 0) { res.add((long)i); n /= i; } } // This condition is to handle the case whien // n is a prime number greater than 2 if (n > 2) res.add(n); return res; } static long power(long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more // than or equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if((y & 1)==1) res = (res * x) % p; // y must be even now // y = y / 2 y = y >> 1; x = (x * x) % p; } return res; } static PrintWriter pw = new PrintWriter(System.out); // static long A = 1000000000+7; // static int[][][] dp; // public static int f(String s,int n,char a,char b) { // if(n==s.length()) { // return 0; // } // if(dp[a-'a'][b-'a'][n]!=-1)return dp[a-'a'][b-'a'][n]; // String v = ""+a+b+s.charAt(n); // if(v.contains("one") || v.contains("two")) { // return dp[a-'a'][b-'a'][n]=1+f(s,n+1,a,b); // }else if(!v.contains("t")&&!v.contains("w")&&!v.contains("o")&&!v.contains("e")&&!v.contains("n")) // return dp[a-'a'][b-'a'][n]=f(s,n+1,b,s.charAt(n)); // return dp[a-'a'][b-'a'][n] = Math.min(1+f(s,n+1,a,b), f(s,n+1,b,s.charAt(n))); // } // public static void trace(String s,int n,char a,char b) { // if(n==s.length()) { // return ; // } // //System.out.println(">>"+a+" " + b); // String v = ""+a+b+s.charAt(n); // if(v.contains("one") || v.contains("two")) { // pw.print((1+n)+" "); // trace(s,n+1,a,b); // return; // }else if(!v.contains("t")&&!v.contains("w")&&!v.contains("o")&&!v.contains("e")&&!v.contains("n")) // f(s,n+1,b,s.charAt(n)); // if(1+dp[a-'a'][b-'a'][n+1]<dp[b-'a'][s.charAt(n)-'a'][n+1]) { // pw.print((n+1)+" "); // trace(s,n+1,a,b); // }else { // //System.out.print(n+" "); // trace(s,n+1,b,s.charAt(n)); // } // } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int q = sc.nextInt(); while(q-->0) { int n = sc.nextInt(); int[] a = new int[n]; int[] b= new int[n]; for(int i=0;i<a.length;i++)a[i] = sc.nextInt(); for(int i = b.length-1;i>=0;i--)b[i] = sc.nextInt(); TreeMap<Integer,Integer> tr = new TreeMap<>(); int jam = 0;int berry = 0; tr.put(0,0); for(int i=0;i<a.length;i++) { if(a[i]==1)jam++; else berry++; tr.put(jam-berry, i+1); } //System.out.println(Arrays.toString(a)); //System.out.println(tr); jam = 0; berry = 0; int max = 0; if(tr.containsKey(berry-jam)) { max = Math.max(max, (tr.get(berry-jam)+berry+jam)); } for(int i=0;i<b.length;i++) { if(b[i]==1)jam++; else berry++; if(tr.containsKey(berry-jam)) { max = Math.max(max, (tr.get(berry-jam)+berry+jam)); } } pw.println(2*n-max); } pw.flush(); pw.close(); } } class Antenna implements Comparable<Antenna>{ int l;int r; public Antenna(int x,int y) { l = x;r = y; } @Override public int compareTo(Antenna o) { // TODO Auto-generated method stub if(this.l<o.l) return -1; else if(this.l>o.l) return 1; else { if(this.r>o.r) return -1; else if(this.r<o.r) return 1; else return 0; } } } class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } }
Java
["4\n6\n1 1 1 2 2 1 2 1 2 1 1 2\n2\n1 2 1 2\n3\n1 1 1 1 1 1\n2\n2 1 1 1"]
2 seconds
["6\n0\n6\n2"]
NoteThe picture from the statement describes the first test case.In the second test case the number of strawberry and blueberry jam jars is already equal.In the third test case Karlsson is required to eat all $$$6$$$ jars so that there remain $$$0$$$ jars of both jams.In the fourth test case Karlsson can empty either the second and the third jars or the third and the fourth one. The both scenarios will leave $$$1$$$ jar of both jams.
Java 8
standard input
[ "dp", "implementation", "greedy", "data structures" ]
b010397b6aeab4ad3f0c9f8e45b34691
The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le 2$$$) — $$$a_i=1$$$ means that the $$$i$$$-th jar from the left is a strawberry jam jar and $$$a_i=2$$$ means that it is a blueberry jam jar. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case print the answer to it — the minimum number of jars Karlsson is required to empty so that an equal number of full strawberry and blueberry jam jars is left.
standard output
PASSED
acef6dab2b579fefcb85fa01b9fa405e
train_004.jsonl
1589466900
You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Scanner; public class p1353c { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in); for (int T = in.nextInt(); T > 0; T--) { long n = in.nextInt() / 2; println(4 * n * (n + 1) * (2 * n + 1) / 3); } } private static void print(Object o) { System.out.print(o); } private static void println(Object o) { System.out.println(o); } private static void printf(String fmt, Object... args) { System.out.printf(fmt, args); } }
Java
["3\n1\n5\n499993"]
1 second
["0\n40\n41664916690999888"]
null
Java 8
standard input
[ "math" ]
b4b69320c6040d2d264ac32e9ba5196f
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n &lt; 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).
1,000
For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.
standard output
PASSED
cb71b09b89b1b1513b354124ba5573d9
train_004.jsonl
1589466900
You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Test{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); long t = sc.nextLong(); while(t>0){ long n = sc.nextLong(); long k = n/2; long sum = 0; for (long i = 1; i <= k; i++) { // System.out.println("i "+i); sum += (i * i); } System.out.println(sum*8); t--; } } }
Java
["3\n1\n5\n499993"]
1 second
["0\n40\n41664916690999888"]
null
Java 8
standard input
[ "math" ]
b4b69320c6040d2d264ac32e9ba5196f
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n &lt; 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).
1,000
For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.
standard output
PASSED
574caa5d84e4628a075df212fa616f1d
train_004.jsonl
1589466900
You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); long a,b,c,d,e,f,g,h; a = sc.nextLong(); for(b = 0;b < a;b++){ c = sc.nextLong(); d = 1; f = 8; e = 1; g = c*c; //System.out.println(g); h = 0; while(d != g){ d = d + f; h = h + f*e; e++; f = f + 8; } System.out.println(h); } } }
Java
["3\n1\n5\n499993"]
1 second
["0\n40\n41664916690999888"]
null
Java 8
standard input
[ "math" ]
b4b69320c6040d2d264ac32e9ba5196f
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n &lt; 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).
1,000
For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.
standard output
PASSED
e11e7e41902b82003c6f467ceaabcdb2
train_004.jsonl
1589466900
You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); int cases=Integer.valueOf(br.readLine()); while(cases!=0) { cases--; long n=Long.valueOf(br.readLine()); long k=(n-1)/2; long ans=(4*k*(k+1)*n)/3; System.out.println(ans); } } }
Java
["3\n1\n5\n499993"]
1 second
["0\n40\n41664916690999888"]
null
Java 8
standard input
[ "math" ]
b4b69320c6040d2d264ac32e9ba5196f
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n &lt; 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).
1,000
For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.
standard output
PASSED
9c06af0dc8437f0f44a231c9dcfd92cd
train_004.jsonl
1589466900
You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.math.*; public class Main { public static void main(String[] args) throws java.lang.Exception { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { double n=sc.nextDouble(); long step=8; long sum=0; for(double i=1;i<=n/2;i++) { sum+=i*step; step+=8; } System.out.println(sum); } } }
Java
["3\n1\n5\n499993"]
1 second
["0\n40\n41664916690999888"]
null
Java 8
standard input
[ "math" ]
b4b69320c6040d2d264ac32e9ba5196f
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n &lt; 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).
1,000
For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.
standard output
PASSED
4218900dca0bd429572d8d1f121db199
train_004.jsonl
1589466900
You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.math.*; public class Main { public static void main(String[] args) throws java.lang.Exception { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { long n=sc.nextLong(); long step=8; long sum=0; for(long i=1;i<=n/2;i++) { sum+=i*step; step+=8; } System.out.println(sum); } } }
Java
["3\n1\n5\n499993"]
1 second
["0\n40\n41664916690999888"]
null
Java 8
standard input
[ "math" ]
b4b69320c6040d2d264ac32e9ba5196f
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n &lt; 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).
1,000
For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.
standard output
PASSED
f34b4e804511c18befdf70eb06f0eda3
train_004.jsonl
1589466900
You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.math.BigInteger; import java.util.*; public class Codeforces { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int nExperiments = sc.nextInt(); for (int i = 0; i < nExperiments; i++) { int n = sc.nextInt(); BigInteger ans = sport(n); System.out.println(ans); } } private static BigInteger sport(int n) { if (n == 1) { return BigInteger.valueOf(0); } else { BigInteger[] dp = new BigInteger[n + 1]; dp[1] = BigInteger.valueOf(0); for (int i = 3; i <= n; i++) { if (i % 2 != 0) { BigInteger a = BigInteger.valueOf(4).multiply(BigInteger.valueOf(i)); a = a.subtract(BigInteger.valueOf(4)); BigInteger b = BigInteger.valueOf(i).divide(BigInteger.valueOf(2)); a = a.multiply(b); dp[i] = dp[i - 2].add(a); } } return dp[n]; } } }
Java
["3\n1\n5\n499993"]
1 second
["0\n40\n41664916690999888"]
null
Java 8
standard input
[ "math" ]
b4b69320c6040d2d264ac32e9ba5196f
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n &lt; 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).
1,000
For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.
standard output
PASSED
b0c868613e56c2c3111aa32d9093e721
train_004.jsonl
1589466900
You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Cf294 implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int[] nextArray(int n) { int arr[] = new int[n]; int i; for(i=0;i<n;i++) { arr[i] = nextInt(); } return arr; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public int[] nextIntArray(int n) { int i; int arr[] = new int[n]; for(i=0;i<n;i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { int i; long arr[] = new long[n]; for(i=0;i<n;i++) { arr[i] = nextLong(); } return arr; } public double[] nextDoubleArray(int n) { int i; double arr[] = new double[n]; for(i=0;i<n;i++) { arr[i] = nextDouble(); } return arr; } public Integer[] IntegerArray(int n) { int i; Integer arr[] = new Integer[n]; for(i=0;i<n;i++) { arr[i] = nextInt(); } return arr; } public Long[] LongArray(int n) { int i; Long arr[] = new Long[n]; for(i=0;i<n;i++) { arr[i] = nextLong(); } return arr; } public Double[] DoubleArray(int n) { int i; Double arr[] = new Double[n]; for(i=0;i<n;i++) { arr[i] = nextDouble(); } return arr; } public ArrayList<ArrayList<Integer>> getGraph(int n,int m) { ArrayList<ArrayList<Integer>> g =new ArrayList<>(); int i; for(i=0;i<=n;i++) { g.add(new ArrayList<>()); } for(i=0;i<m;i++) { int x = nextInt(); int y = nextInt(); g.get(x).add(y); g.get(y).add(x); } return g; } public ArrayList<ArrayList<Integer>> getTree(int n) { ArrayList<ArrayList<Integer>> g =new ArrayList<>(); int i; for(i=0;i<=n;i++) { g.add(new ArrayList<>()); } for(i=0;i<n-1;i++) { int x = nextInt(); int y = nextInt(); g.get(x).add(y); g.get(y).add(x); } return g; } } public static int maxInt(int arr[]) { int max = Integer.MIN_VALUE; for(int i : arr) { max = Math.max(i,max); } return max; } public static int minInt(int arr[]) { int min = Integer.MAX_VALUE; for(int i : arr) { min = Math.min(i,min); } return min; } public static long maxLong(long arr[]) { long max = Long.MIN_VALUE; for(long i : arr) { max = Math.max(i,max); } return max; } public static long minLong(long arr[]) { long min = Long.MAX_VALUE; for(long i : arr) { min = Math.min(i,min); } return min; } public static double maxDouble(double arr[]) { double max = Double.MIN_VALUE; for(double i : arr) { max = Math.max(i,max); } return max; } public static double minDouble(double arr[]) { double min = Double.MAX_VALUE; for(double i : arr) { min = Math.min(i,min); } return min; } void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } void sort(int arr[], int l, int r) { if (l < r) { int m = (l+r)/2; sort(arr, l, m); sort(arr , m+1, r); merge(arr, l, m, r); } } static class Pair { int x,y; public Pair(int x,int y) { this.x = x; this.y = y; } public static Comparator<Pair> sortX = new Comparator<Pair>(){ public int compare(Pair p1,Pair p2) { if(p1.x==p2.x) { return p1.y-p2.y; } return p1.x-p2.x; } }; public static Comparator<Pair> sortY = new Comparator<Pair>(){ public int compare(Pair p1,Pair p2) { if(p1.y==p2.y) { return p1.x-p2.x; } return p1.y-p2.y; } }; public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof Pair)) return false; return (this.x == ((Pair) obj).x && this.y == ((Pair)obj).y); } public int hashCode() { if(x<0 || y<0) { return -5*x+-32*y; } return 5*(x+y); } } static class DPair { Pair s,d; public DPair(Pair s,Pair d) { this.s = s; this.d = d; } public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof DPair)) return false; return (this.s.x == ((DPair) obj).s.x && this.s.y == ((DPair) obj).s.y && this.d.x == ((DPair)obj).d.x && this.d.y == ((DPair) obj).d.y); } public int hashCode() { return 5*(s.x+s.y+d.x+d.y); } } static class DSU { public static int rank[],parent[]; int n; HashMap<Integer,Integer> map = new HashMap<>(); public DSU(int n) { rank = new int[n+1]; parent = new int[n+1]; this.n = n; makeSet(n); } public void makeSet(int n) { for(int i=1;i<=n;i++) { parent[i] = i; map.put(i,1); } } public static int find(int x) { if(parent[x]!=x) { parent[x] = find(parent[x]); } return parent[x]; } public void union(int x,int y) { int xRoot = find(x); int yRoot = find(y); if(xRoot==yRoot) { return; } if(rank[xRoot] < rank[yRoot]) { parent[xRoot] = yRoot; map.put(yRoot,map.getOrDefault(yRoot,1)+map.getOrDefault(xRoot,1)); if(map.getOrDefault(xRoot,0)!=0) { map.remove(xRoot); } } else if(rank[yRoot] < rank[xRoot]) { parent[yRoot] = xRoot; map.put(xRoot,map.getOrDefault(xRoot,1) + map.getOrDefault(yRoot,1)); if(map.getOrDefault(yRoot,0)!=0) { map.remove(yRoot); } } else { parent[yRoot] = xRoot; rank[xRoot] = rank[xRoot] + 1; map.put(xRoot,map.getOrDefault(xRoot,1)+map.getOrDefault(yRoot,1)); if(map.getOrDefault(yRoot,0)!=0) { map.remove(yRoot); } } } } public static void main(String args[]) throws Exception { new Thread(null, new Cf294(),"Main",1<<27).start(); } public void run() { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int t = in.nextInt(); while(t-->0) { int n = in.nextInt(); long res = 0; BigInteger b = new BigInteger("0"); int i,j,k; for(i=1;i<=n/2;i++) { res=(long)i*(long)i*(long)8; b = b.add(new BigInteger(Long.toString(res))); } w.println(b); } w.flush(); w.close(); } }
Java
["3\n1\n5\n499993"]
1 second
["0\n40\n41664916690999888"]
null
Java 8
standard input
[ "math" ]
b4b69320c6040d2d264ac32e9ba5196f
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n &lt; 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).
1,000
For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.
standard output
PASSED
93211fab2cc881bc95edd293b63e94e3
train_004.jsonl
1589466900
You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Cf294 implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int[] nextArray(int n) { int arr[] = new int[n]; int i; for(i=0;i<n;i++) { arr[i] = nextInt(); } return arr; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public int[] nextIntArray(int n) { int i; int arr[] = new int[n]; for(i=0;i<n;i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { int i; long arr[] = new long[n]; for(i=0;i<n;i++) { arr[i] = nextLong(); } return arr; } public double[] nextDoubleArray(int n) { int i; double arr[] = new double[n]; for(i=0;i<n;i++) { arr[i] = nextDouble(); } return arr; } public Integer[] IntegerArray(int n) { int i; Integer arr[] = new Integer[n]; for(i=0;i<n;i++) { arr[i] = nextInt(); } return arr; } public Long[] LongArray(int n) { int i; Long arr[] = new Long[n]; for(i=0;i<n;i++) { arr[i] = nextLong(); } return arr; } public Double[] DoubleArray(int n) { int i; Double arr[] = new Double[n]; for(i=0;i<n;i++) { arr[i] = nextDouble(); } return arr; } public ArrayList<ArrayList<Integer>> getGraph(int n,int m) { ArrayList<ArrayList<Integer>> g =new ArrayList<>(); int i; for(i=0;i<=n;i++) { g.add(new ArrayList<>()); } for(i=0;i<m;i++) { int x = nextInt(); int y = nextInt(); g.get(x).add(y); g.get(y).add(x); } return g; } public ArrayList<ArrayList<Integer>> getTree(int n) { ArrayList<ArrayList<Integer>> g =new ArrayList<>(); int i; for(i=0;i<=n;i++) { g.add(new ArrayList<>()); } for(i=0;i<n-1;i++) { int x = nextInt(); int y = nextInt(); g.get(x).add(y); g.get(y).add(x); } return g; } } public static int maxInt(int arr[]) { int max = Integer.MIN_VALUE; for(int i : arr) { max = Math.max(i,max); } return max; } public static int minInt(int arr[]) { int min = Integer.MAX_VALUE; for(int i : arr) { min = Math.min(i,min); } return min; } public static long maxLong(long arr[]) { long max = Long.MIN_VALUE; for(long i : arr) { max = Math.max(i,max); } return max; } public static long minLong(long arr[]) { long min = Long.MAX_VALUE; for(long i : arr) { min = Math.min(i,min); } return min; } public static double maxDouble(double arr[]) { double max = Double.MIN_VALUE; for(double i : arr) { max = Math.max(i,max); } return max; } public static double minDouble(double arr[]) { double min = Double.MAX_VALUE; for(double i : arr) { min = Math.min(i,min); } return min; } void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } void sort(int arr[], int l, int r) { if (l < r) { int m = (l+r)/2; sort(arr, l, m); sort(arr , m+1, r); merge(arr, l, m, r); } } static class Pair { int x,y; public Pair(int x,int y) { this.x = x; this.y = y; } public static Comparator<Pair> sortX = new Comparator<Pair>(){ public int compare(Pair p1,Pair p2) { if(p1.x==p2.x) { return p1.y-p2.y; } return p1.x-p2.x; } }; public static Comparator<Pair> sortY = new Comparator<Pair>(){ public int compare(Pair p1,Pair p2) { if(p1.y==p2.y) { return p1.x-p2.x; } return p1.y-p2.y; } }; public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof Pair)) return false; return (this.x == ((Pair) obj).x && this.y == ((Pair)obj).y); } public int hashCode() { if(x<0 || y<0) { return -5*x+-32*y; } return 5*(x+y); } } static class DPair { Pair s,d; public DPair(Pair s,Pair d) { this.s = s; this.d = d; } public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof DPair)) return false; return (this.s.x == ((DPair) obj).s.x && this.s.y == ((DPair) obj).s.y && this.d.x == ((DPair)obj).d.x && this.d.y == ((DPair) obj).d.y); } public int hashCode() { return 5*(s.x+s.y+d.x+d.y); } } static class DSU { public static int rank[],parent[]; int n; HashMap<Integer,Integer> map = new HashMap<>(); public DSU(int n) { rank = new int[n+1]; parent = new int[n+1]; this.n = n; makeSet(n); } public void makeSet(int n) { for(int i=1;i<=n;i++) { parent[i] = i; map.put(i,1); } } public static int find(int x) { if(parent[x]!=x) { parent[x] = find(parent[x]); } return parent[x]; } public void union(int x,int y) { int xRoot = find(x); int yRoot = find(y); if(xRoot==yRoot) { return; } if(rank[xRoot] < rank[yRoot]) { parent[xRoot] = yRoot; map.put(yRoot,map.getOrDefault(yRoot,1)+map.getOrDefault(xRoot,1)); if(map.getOrDefault(xRoot,0)!=0) { map.remove(xRoot); } } else if(rank[yRoot] < rank[xRoot]) { parent[yRoot] = xRoot; map.put(xRoot,map.getOrDefault(xRoot,1) + map.getOrDefault(yRoot,1)); if(map.getOrDefault(yRoot,0)!=0) { map.remove(yRoot); } } else { parent[yRoot] = xRoot; rank[xRoot] = rank[xRoot] + 1; map.put(xRoot,map.getOrDefault(xRoot,1)+map.getOrDefault(yRoot,1)); if(map.getOrDefault(yRoot,0)!=0) { map.remove(yRoot); } } } } public static void main(String args[]) throws Exception { new Thread(null, new Cf294(),"Main",1<<27).start(); } public void run() { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int t = in.nextInt(); while(t-->0) { int n = in.nextInt(); long res=0; int i,j,k; for(i=1;i<=n/2;i++) { res+=((long)i*(long)i*(long)8); } w.println(res); } w.flush(); w.close(); } }
Java
["3\n1\n5\n499993"]
1 second
["0\n40\n41664916690999888"]
null
Java 8
standard input
[ "math" ]
b4b69320c6040d2d264ac32e9ba5196f
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n &lt; 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).
1,000
For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.
standard output
PASSED
0a109501a2232937e5b80fdae3d4c4c6
train_004.jsonl
1589466900
You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; //import java.lang.*; public class Main{ public static void main(String [] args) { Scanner scan=new Scanner(System.in); int t=scan.nextInt(); for(int j=0;j<t ;j++) { long n=scan.nextLong(); long x=(n-1)/2; long ans = (x*(x+1)*(2*x+1)/6)*8; System.out.println(ans); } } }
Java
["3\n1\n5\n499993"]
1 second
["0\n40\n41664916690999888"]
null
Java 8
standard input
[ "math" ]
b4b69320c6040d2d264ac32e9ba5196f
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n &lt; 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).
1,000
For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.
standard output
PASSED
2aad2984d54180734302900982823a37
train_004.jsonl
1589466900
You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Scanner; public class p1353C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { long n = sc.nextInt()-1,sum=0; for(long x=n/2;x>0;x--,n-=2) sum+=(4*x*n); System.out.println(sum); } } }
Java
["3\n1\n5\n499993"]
1 second
["0\n40\n41664916690999888"]
null
Java 8
standard input
[ "math" ]
b4b69320c6040d2d264ac32e9ba5196f
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n &lt; 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).
1,000
For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.
standard output
PASSED
753a92012aa1ede4f6e66b953c269caf
train_004.jsonl
1589466900
You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.
256 megabytes
/* ⣿⣿⣿⣿⣿⣿⡷⣯⢿⣿⣷⣻⢯⣿⡽⣻⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⠸⣿⣿⣆⠹⣿⣿⢾⣟⣯⣿⣿⣿⣿⣿⣿⣽⣻⣿⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣻⣽⡿⣿⣎⠙⣿⣞⣷⡌⢻⣟⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣿⣿⣿⣿⡄⠹⣿⣿⡆⠻⣿⣟⣯⡿⣽⡿⣿⣿⣿⣿⣽⡷⣯⣿⣿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣟⣷⣿⣿⣿⡀⠹⣟⣾⣟⣆⠹⣯⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢠⡘⣿⣿⡄⠉⢿⣿⣽⡷⣿⣻⣿⣿⣿⣿⡝⣷⣯⢿⣿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣯⢿⣾⢿⣿⡄⢄⠘⢿⣞⡿⣧⡈⢷⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢸⣧⠘⣿⣷⠈⣦⠙⢿⣽⣷⣻⣽⣿⣿⣿⣿⣌⢿⣯⢿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⣟⣯⣿⢿⣿⡆⢸⡷⡈⢻⡽⣷⡷⡄⠻⣽⣿⣿⡿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣿⣿⣏⢰⣯⢷⠈⣿⡆⢹⢷⡌⠻⡾⢋⣱⣯⣿⣿⣿⣿⡆⢻⡿⣿⣿⣿ ⣿⣿⣿⣿⣿⣿⡎⣿⢾⡿⣿⡆⢸⣽⢻⣄⠹⣷⣟⣿⣄⠹⣟⣿⣿⣟⣿⣿⣿⣿⣿⣿⣽⣿⣿⣿⡇⢸⣯⣟⣧⠘⣷⠈⡯⠛⢀⡐⢾⣟⣷⣻⣿⣿⣿⡿⡌⢿⣻⣿⣿ ⣿⣿⣿⣿⣿⣿⣧⢸⡿⣟⣿⡇⢸⣯⣟⣮⢧⡈⢿⣞⡿⣦⠘⠏⣹⣿⣽⢿⣿⣿⣿⣿⣯⣿⣿⣿⡇⢸⣿⣿⣾⡆⠹⢀⣠⣾⣟⣷⡈⢿⣞⣯⢿⣿⣿⣿⢷⠘⣯⣿⣿ ⣿⣿⣿⣿⣿⣿⣿⡈⣿⢿⣽⡇⠘⠛⠛⠛⠓⠓⠈⠛⠛⠟⠇⢀⢿⣻⣿⣯⢿⣿⣿⣿⣷⢿⣿⣿⠁⣾⣿⣿⣿⣧⡄⠇⣹⣿⣾⣯⣿⡄⠻⣽⣯⢿⣻⣿⣿⡇⢹⣾⣿ ⣿⣿⣿⣿⣿⣿⣿⡇⢹⣿⡽⡇⢸⣿⣿⣿⣿⣿⣞⣆⠰⣶⣶⡄⢀⢻⡿⣯⣿⡽⣿⣿⣿⢯⣟⡿⢀⣿⣿⣿⣿⣿⣧⠐⣸⣿⣿⣷⣿⣿⣆⠹⣯⣿⣻⣿⣿⣿⢀⣿⢿ ⣿⣿⣿⣿⣿⣿⣿⣿⠘⣯⡿⡇⢸⣿⣿⣿⣿⣿⣿⣿⣧⡈⢿⣳⠘⡄⠻⣿⢾⣽⣟⡿⣿⢯⣿⡇⢸⣿⣿⣿⣿⣿⣿⡀⢾⣿⣿⣿⣿⣿⣿⣆⠹⣾⣷⣻⣿⡿⡇⢸⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⡇⢹⣿⠇⢸⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⠻⡇⢹⣆⠹⣟⣾⣽⣻⣟⣿⣽⠁⣾⣿⣿⣿⣿⣿⣿⣇⣿⣿⠿⠛⠛⠉⠙⠋⢀⠁⢘⣯⣿⣿⣧⠘⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⣿⡈⣿⡃⢼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡙⠌⣿⣆⠘⣿⣞⡿⣞⡿⡞⢠⣿⣿⣿⣿⣿⡿⠛⠉⠁⢀⣀⣠⣤⣤⣶⣶⣶⡆⢻⣽⣞⡿⣷⠈⣿ ⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⠘⠁⠉⠉⠉⠉⠉⠉⠉⠉⠉⠙⠛⠛⢿⣄⢻⣿⣧⠘⢯⣟⡿⣽⠁⣾⣿⣿⣿⣿⣿⡃⢀⢀⠘⠛⠿⢿⣻⣟⣯⣽⣻⣵⡀⢿⣯⣟⣿⢀⣿ ⣿⣿⣿⣟⣿⣿⣿⣿⣶⣶⡆⢀⣿⣾⣿⣾⣷⣿⣶⠿⠚⠉⢀⢀⣤⣿⣷⣿⣿⣷⡈⢿⣻⢃⣼⣿⣿⣿⣿⣻⣿⣿⣿⡶⣦⣤⣄⣀⡀⠉⠛⠛⠷⣯⣳⠈⣾⡽⣾⢀⣿ ⣿⢿⣿⣿⣻⣿⣿⣿⣿⣿⡿⠐⣿⣿⣿⣿⠿⠋⠁⢀⢀⣤⣾⣿⣿⣿⣿⣿⣿⣿⣿⣌⣥⣾⡿⣿⣿⣷⣿⣿⢿⣷⣿⣿⣟⣾⣽⣳⢯⣟⣶⣦⣤⡾⣟⣦⠘⣿⢾⡁⢺ ⣿⣻⣿⣿⡷⣿⣿⣿⣿⣿⡗⣦⠸⡿⠋⠁⢀⢀⣠⣴⢿⣿⣽⣻⢽⣾⣟⣷⣿⣟⣿⣿⣿⣳⠿⣵⣧⣼⣿⣿⣿⣿⣿⣾⣿⣿⣿⣿⣿⣽⣳⣯⣿⣿⣿⣽⢀⢷⣻⠄⠘ ⣿⢷⣻⣿⣿⣷⣻⣿⣿⣿⡷⠛⣁⢀⣀⣤⣶⣿⣛⡿⣿⣮⣽⡻⣿⣮⣽⣻⢯⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣯⢀⢸⣿⢀⡆ ⠸⣟⣯⣿⣿⣷⢿⣽⣿⣿⣷⣿⣷⣆⠹⣿⣶⣯⠿⣿⣶⣟⣻⢿⣷⣽⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢀⣯⣟⢀⡇ ⣇⠹⣟⣾⣻⣿⣿⢾⡽⣿⣿⣿⣿⣿⣆⢹⣶⣿⣻⣷⣯⣟⣿⣿⣽⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⢀⡿⡇⢸⡇ ⣿⣆⠹⣷⡻⣽⣿⣯⢿⣽⣻⣿⣿⣿⣿⣆⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⢸⣿⠇⣼⡇ ⡙⠾⣆⠹⣿⣦⠛⣿⢯⣷⢿⡽⣿⣿⣿⣿⣆⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃⠎⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠏⢀⣿⣾⣣⡿⡇ ⣿⣷⡌⢦⠙⣿⣿⣌⠻⣽⢯⣿⣽⣻⣿⣿⣿⣧⠩⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⢰⢣⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⢀⢀⢿⣞⣷⢿⡇ ⣿⣽⣆⠹⣧⠘⣿⣿⡷⣌⠙⢷⣯⡷⣟⣿⣿⣿⣷⡀⡹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣈⠃⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⢀⣴⡧⢀⠸⣿⡽⣿⢀ ⢻⣽⣿⡄⢻⣷⡈⢿⣿⣿⢧⢀⠙⢿⣻⡾⣽⣻⣿⣿⣄⠌⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⢁⣰⣾⣟⡿⢀⡄⢿⣟⣿⢀ ⡄⢿⣿⣷⢀⠹⣟⣆⠻⣿⣿⣆⢀⣀⠉⠻⣿⡽⣯⣿⣿⣷⣈⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⢀⣠⠘⣯⣷⣿⡟⢀⢆⠸⣿⡟⢸ ⣷⡈⢿⣿⣇⢱⡘⢿⣷⣬⣙⠿⣧⠘⣆⢀⠈⠻⣷⣟⣾⢿⣿⣆⠹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⣠⡞⢡⣿⢀⣿⣿⣿⠇⡄⢸⡄⢻⡇⣼ ⣿⣷⡈⢿⣿⡆⢣⡀⠙⢾⣟⣿⣿⣷⡈⠂⠘⣦⡈⠿⣯⣿⢾⣿⣆⠙⠻⠿⠿⠿⠿⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠛⢋⣠⣾⡟⢠⣿⣿⢀⣿⣿⡟⢠⣿⢈⣧⠘⢠⣿ ⣿⣿⣿⣄⠻⣿⡄⢳⡄⢆⡙⠾⣽⣿⣿⣆⡀⢹⡷⣄⠙⢿⣿⡾⣿⣆⢀⡀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⣀⣠⣴⡿⣯⠏⣠⣿⣿⡏⢸⣿⡿⢁⣿⣿⢀⣿⠆⢸⣿ ⣿⣿⣿⣿⣦⡙⣿⣆⢻⡌⢿⣶⢤⣉⣙⣿⣷⡀⠙⠽⠷⠄⠹⣿⣟⣿⣆⢙⣋⣤⣤⣤⣄⣀⢀⢀⢀⢀⣾⣿⣟⡷⣯⡿⢃⣼⣿⣿⣿⠇⣼⡟⣡⣿⣿⣿⢀⡿⢠⠈⣿ ⣿⣿⣿⣿⣿⣷⣮⣿⣿⣿⡌⠁⢤⣤⣤⣤⣬⣭⣴⣶⣶⣶⣆⠈⢻⣿⣿⣆⢻⣿⣿⣿⣿⣿⣿⣷⣶⣤⣌⣉⡘⠛⠻⠶⣿⣿⣿⣿⡟⣰⣫⣴⣿⣿⣿⣿⠄⣷⣿⣿⣿ */ import java.io.*; import java.util.*; public class Test { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static String nexts() throws IOException { tokenizer = new StringTokenizer(reader.readLine()); String s=""; while (tokenizer.hasMoreTokens()) { s+=tokenizer.nextElement()+" "; } return s; } //String str=nextToken(); //String[] s = str.split("\\s+"); public static int gcd(int x, int y){ if (y == 0) return x; else return gcd(y, x % y); } public static boolean isPrime(int n) { // Corner cases if (n <= 1){ return false; } if (n <= 3){ return true; } // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0){ return false; } for (int i = 5; i * i <= n; i = i + 6) { //Checking 6i+1 & 6i-1 if (n % i == 0 || n % (i + 2) == 0) { return false; } } //O(sqrt(n)) return true; } static class R implements Comparable<R>{ int x, y; public R(int x, int y) { this.x = x; this.y = y; } public int compareTo(R o) { return x-o.x; //Increasing order(Which is usually required) } } public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } private static void solve() throws IOException { int t = nextInt(); while(t-->0){ int n = nextInt(); if(n==1){ writer.println(0); continue; } long ans=0; int currmove=n/2; int iterator=n/2; for(int i=0;i<iterator;i++){ long count=(2*n+2*(n-2)); ans=ans+count*(long)currmove; currmove--; n=n-2; } writer.println(ans); } } }
Java
["3\n1\n5\n499993"]
1 second
["0\n40\n41664916690999888"]
null
Java 8
standard input
[ "math" ]
b4b69320c6040d2d264ac32e9ba5196f
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n &lt; 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).
1,000
For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.
standard output
PASSED
503dcab93860f55e6209cf24509ed179
train_004.jsonl
1589466900
You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class Main { public static void main(String args[]) { Scanner s=new Scanner(System.in); int t=s.nextInt(); while(t-->0){ int n=s.nextInt(); long sum=0; for(long i=0;i<=n/2;i++){ sum+=(i*i*8); } System.out.println(sum); } } }
Java
["3\n1\n5\n499993"]
1 second
["0\n40\n41664916690999888"]
null
Java 8
standard input
[ "math" ]
b4b69320c6040d2d264ac32e9ba5196f
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n &lt; 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).
1,000
For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.
standard output
PASSED
2c49703b5ee931843dc8310aa1e8d11c
train_004.jsonl
1589466900
You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { // your code goes here BufferedReader buf=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(buf.readLine()); StringBuilder sb=new StringBuilder(); for(int i=0;i<t;i++) { int n=Integer.parseInt(buf.readLine()); long moves=0; long cal; if(n==1) sb.append("0"+"\n"); else { while(n>1) { long part1=n/2; long part2=((4*n)-4); moves=moves+(part1*part2); n=n-2; } sb.append(moves+"\n"); } } System.out.println(sb); } }
Java
["3\n1\n5\n499993"]
1 second
["0\n40\n41664916690999888"]
null
Java 8
standard input
[ "math" ]
b4b69320c6040d2d264ac32e9ba5196f
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n &lt; 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).
1,000
For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.
standard output
PASSED
1dc5bdf24d5729c1457f5d507264b535
train_004.jsonl
1589466900
You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public class Solution{ public static void main(String args[]) { Scanner sc = new Scanner(System.in); int test = sc.nextInt(); while(test>0) { long n = sc.nextLong(); if(n==1) { System.out.println("0"); } else{ long temp =3; long ans=8; long res=8; long i=1; while(temp<n) { i++; res=res+(ans+8)*i; ans=ans+8; temp+=2; } System.out.println(res); } test--; } } }
Java
["3\n1\n5\n499993"]
1 second
["0\n40\n41664916690999888"]
null
Java 8
standard input
[ "math" ]
b4b69320c6040d2d264ac32e9ba5196f
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n &lt; 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).
1,000
For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.
standard output
PASSED
52eb9012b4887328966660c61018394e
train_004.jsonl
1589466900
You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class BoardMoves { public static long BoardMoves(int n) { if(n==1) { return 0; } long c=(n/2); return 8*(c)*(c+1)*((2*c)+1)/6; } public static void main(String[] args) throws IOException { BufferedReader r=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(r.readLine()); for(int i=0;i<t;i++) { int n=Integer.parseInt(r.readLine()); long a=BoardMoves(n); System.out.println(a); } } }
Java
["3\n1\n5\n499993"]
1 second
["0\n40\n41664916690999888"]
null
Java 8
standard input
[ "math" ]
b4b69320c6040d2d264ac32e9ba5196f
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n &lt; 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).
1,000
For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.
standard output
PASSED
88cdc828821b767e85bffc8c02650296
train_004.jsonl
1589466900
You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells: $$$(i - 1, j - 1)$$$; $$$(i - 1, j)$$$; $$$(i - 1, j + 1)$$$; $$$(i, j - 1)$$$; $$$(i, j + 1)$$$; $$$(i + 1, j - 1)$$$; $$$(i + 1, j)$$$; $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class C { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); int req[] = new int[t]; int i =0; int maxi = Integer.MIN_VALUE; while(t-->0) { // System.out.println("t "+t); req[i] = scanner.nextInt(); maxi = Math.max(maxi,req[i]); i++; } long dp[] = new long[maxi+1]; int k =1; for(i =3; i <=maxi;i=i+2){ dp[i]+=dp[i-2]; long sum= (i*2)+((i-2)*2); sum*=k; dp[i]+=sum; k++; // if(i<=10) // System.out.println("i " +i+", val "+dp[i]); // } for(i =0; i <req.length;i++){ int r = req[i]; System.out.println(dp[r]); } } }
Java
["3\n1\n5\n499993"]
1 second
["0\n40\n41664916690999888"]
null
Java 8
standard input
[ "math" ]
b4b69320c6040d2d264ac32e9ba5196f
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n &lt; 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).
1,000
For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.
standard output
PASSED
1f628b9bbe5a0e3d47c81b1d4c7d7156
train_004.jsonl
1518793500
Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route.Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins.You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).Formally, for every you have to calculate , where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; import java.util.PriorityQueue; public class P938D { private static class Node implements Comparable<Node>{ private int u; private long dist; public Node(int a, long c) { u=a; dist=c; } public int compareTo(Node node) { return Long.compare(dist, node.dist); } } private static class Edge{ private int u, v; private long w; public Edge(int a, int b, long c) { u=a; v=b; w=c; } public int other(int x) { return x==u?v:u; } } private static int n, m; private static HashMap<Integer, ArrayList<Edge>> g; static long[] a; public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); n = in.nextInt(); m = in.nextInt(); g = new HashMap<>(); for(int i=0; i<n; i++) g.put(i, new ArrayList<>()); for(int i=0; i<m; i++) { int p = in.nextInt()-1; int q = in.nextInt()-1; long ww = 2*in.nextLong(); Edge e = new Edge(p, q, ww); g.get(p).add(e); g.get(q).add(e); } a = new long[n]; for(int i=0; i<n; i++) a[i] = in.nextLong(); long[] dist = new long[n]; Arrays.fill(dist, (long)1e18); PriorityQueue<Node> pq = new PriorityQueue<>(); HashSet<Integer> relaxed = new HashSet<>(); for(int i=0; i<n; i++) { dist[i] = a[i]; pq.add(new Node(i, a[i])); } while(!pq.isEmpty()) { Node node = pq.poll(); int u = node.u; if (relaxed.contains(u)) continue; relaxed.add(u); for(Edge e: g.get(u)) { int v = e.other(u); if (dist[v]>node.dist+e.w) { dist[v] = node.dist+e.w; pq.add(new Node(v, dist[v])); } } } for(int i=0; i<n; i++) { w.print(dist[i]+" "); } w.println(); w.flush(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["4 2\n1 2 4\n2 3 7\n6 20 1 25", "3 3\n1 2 1\n2 3 1\n1 3 1\n30 10 20"]
2 seconds
["6 14 1 25", "12 10 12"]
null
Java 8
standard input
[ "data structures", "graphs", "shortest paths" ]
f41be1fcb6164181c49b37ed9313696e
The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city.
2,000
Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).
standard output
PASSED
be242b6943ca88c2c767a2e89d63ef8b
train_004.jsonl
1518793500
Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route.Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins.You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).Formally, for every you have to calculate , where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large.
256 megabytes
//package CodeForce; import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; /** * * @author prabhat */ public class P797B { static int[] a; static long[] sum; static int mod=1000000007; static int[][] dp; static boolean[][] isPalin; static int max1=5000+10; static int[][] g; static int ver; static int n,k,m,x; static boolean[] visit,isprime; static LinkedList<Pair> l[]; static int ans=0,max_len=8; static int[] color,log,st[],lpf; static String[] S;static TreeSet<Point> ts; static LinkedList<Pair> adj[]; static InputReader in; static PrintWriter pw; static Point[] point;static char[] s; static String[] node; public static void main(String[] args) throws Exception { in = new InputReader(System.in); // BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //Scanner sc=new Scanner(); pw=new PrintWriter(System.out); n=in.ii(); m=in.ii(); adj=new LinkedList[n]; for(int i=0;i<n;i++)adj[i]=new LinkedList<>(); for(int i=0;i<m;i++) { int u=in.ii()-1; int v=in.ii()-1; long w=in.il(); adj[u].add(new Pair(v,w)); adj[v].add(new Pair(u,w)); } long[] a=in.ila(n); PriorityQueue<Pair> pq=new PriorityQueue<>(); for(int i=0;i<n;i++) pq.add(new Pair(i,a[i])); boolean[] vis=new boolean[n]; while(!pq.isEmpty()) { Pair p=pq.poll(); if(vis[p.x])continue; vis[p.x]=true; int x=p.x; for(Pair b:adj[x]) { if(a[b.x]>a[x]+2*b.y) { a[b.x]=a[x]+2*b.y; pq.add(new Pair(b.x,a[b.x])); } } } // pw.println(Arrays.toString(a)); for(long l:a)pw.print(l+" "); pw.close(); } static class Pair implements Comparable<Pair> { int x,i; long y; public Pair(int x, long y) { this.x = x; this.y = y; } Pair (int x, int y,int i) { this.x = x; this.y = y; this.i = i; } public int compareTo(Pair o) { return Long.compare(this.y,o.y); } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.x == x && p.y==y; } return false; } @Override public String toString() { return x + " "+ y; } public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode(); } } static boolean valid(String s) { boolean b=false; for(int i=0;i<s.length()-1;i++) { if(isVowel(s.charAt(i))&&isVowel(s.charAt(i+1)))return false; } return true; } static boolean isVowel(char c) { if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='y')return true; return false; } static boolean isvalid(int i,int j) { if(i>=0&&i<n&&j>=0&&j<m)return true; return false; } static double dist(double x1,double y1,double x2,double y2) { double ans=(x1-x2)*(x1-x2)+(y1-y2)*(y1-y2); return (Math.ceil(Math.sqrt(ans))); } static boolean inside(Point p) { Point p2, p1=point[0]; double xInt=0; int cnt=0; for(int i=1;i<=n;i++) { p2=point[i%n]; if((p.y>Math.min(p1.y,p2.y))&&(p.y<=Math.max(p1.y,p2.y))) { if(p.x<=Math.max(p1.x,p2.x)) { if(p1.y!=p2.y) { xInt=(p.y-p1.y)*(p2.x-p1.x)/(p2.y-p1.y) +p1.x; if(p1.x==p2.x||p.x<=xInt) cnt++; } } } p1=p2; } if(cnt%2==0) return false; else return true; } static long gcd1(long a,long b) { long res=1L; while(a>0) { res=a; a=b%a; b=res; } return res; } public static double calculateAngle(double x1, double y1, double x2, double y2) { double angle = Math.toDegrees(Math.atan2(x2 - x1, y2 - y1)); // Keep angle between 0 and 360 angle = angle + Math.ceil( -angle / 360 ) * 360; return angle; } static void seive() { isprime=new boolean[1000005]; Arrays.fill(isprime, true); isprime[0]=false; isprime[1]=false; lpf=new int[1000005]; for(int i=1;i<=1000000;i++)lpf[i]=i; for(int i=2;i<=1000;i++) { if(lpf[i]!=i)continue; int j=i+i; while(j<=1000000) { lpf[j]=i; j+=i; } } } static BigInteger power(BigInteger x, BigInteger y, BigInteger m) { if (y.equals(new BigInteger("0"))) return (new BigInteger("1")); BigInteger p = power(x, y.divide(new BigInteger("2")), m).mod(m); p = (p.multiply(p)).mod(m); return (y.mod(new BigInteger("2")).equals(new BigInteger("0")))? p : (p.multiply(x)).mod(m); } static char[][] trans(char[][] s) { int n=s.length; int m=s[0].length; char[][] trans=new char[m][n]; for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { trans[i][j]=s[j][i]; } } return trans; } public static String toBase26(int n) { StringBuffer ret = new StringBuffer(); while(n>0) { --n; ret.append((char)('A' + n%26)); n/=26; } return ret.reverse().toString(); } static void log() { log[1]=0; for(int i=2;i<=n;i++) { log[i]=log[i/2]+1; } } private static class DSU{ int[] parent; int[] rank; int cnt; public DSU(int n){ parent=new int[n]; rank=new int[n]; for(int i=0;i<n;i++){ parent[i]=i; rank[i]=1; } cnt=n; } int find(int i){ while(parent[i] !=i){ parent[i]=parent[parent[i]]; i=parent[i]; } return i; } int Union(int x, int y){ int xset = find(x); int yset = find(y); if(xset!=yset) cnt--; if(rank[xset]<rank[yset]){ parent[xset] = yset; rank[yset]+=rank[xset]; rank[xset]=0; return yset; }else{ parent[yset]=xset; rank[xset]+=rank[yset]; rank[yset]=0; return xset; } } } public static int[][] packU(int n, int[] from, int[] to, int max) { int[][] g = new int[n][]; int[] p = new int[n]; for (int i = 0; i < max; i++) p[from[i]]++; for (int i = 0; i < max; i++) p[to[i]]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < max; i++) { g[from[i]][--p[from[i]]] = to[i]; g[to[i]][--p[to[i]]] = from[i]; } return g; } public static int[][] parents3(int[][] g, int root) { int n = g.length; int[] par = new int[n]; Arrays.fill(par, -1); int[] depth = new int[n]; depth[0] = 0; int[] q = new int[n]; q[0] = root; for (int p = 0, r = 1; p < r; p++) { int cur = q[p]; for (int nex : g[cur]) { if (par[cur] != nex) { q[r++] = nex; par[nex] = cur; depth[nex] = depth[cur] + 1; } } } return new int[][]{par, q, depth}; } public static int lower_bound(int[] nums, int target) { int low = 0, high = nums.length - 1; while (low < high) { int mid = low + (high - low) / 2; if (nums[mid] < target) low = mid + 1; else high = mid; } return nums[low] == target ? low : -1; } public static int upper_bound(int[] nums, int target) { int low = 0, high = nums.length - 1; while (low < high) { int mid = low + (high + 1 - low) / 2; if (nums[mid] > target) high = mid - 1; else low = mid; } return nums[low] == target ? low : -1; } public static boolean palin(String s) { int i=0; int j=s.length()-1; while(i<j) { if(s.charAt(i)==s.charAt(j)) { i++; j--; } else return false; } return true; } static boolean CountPs(String s,int n) { boolean b=false; char[] S=s.toCharArray(); int[][] dp=new int[n][n]; boolean[][] p=new boolean[n][n]; for(int i=0;i<n;i++)p[i][i]=true; for(int i=0;i<n-1;i++) { if(S[i]==S[i+1]) { p[i][i+1]=true; dp[i][i+1]=1; b=true; } } for(int gap=2;gap<n;gap++) { for(int i=0;i<n-gap;i++) { int j=gap+i; if(S[i]==S[j]&&p[i+1][j-1]){p[i][j]=true;} if(p[i][j]) dp[i][j]=dp[i][j-1]+dp[i+1][j]+1-dp[i+1][j-1]; else dp[i][j]=dp[i][j-1]+dp[i+1][j]-dp[i+1][j-1]; if(dp[i][j]>=1){b=true;} } } return b; // return dp[0][n-1]; } public static int gcd(int a,int b) { int res=1; while(a>0) { res=a; a=b%a; b=res; } return res; } public static long pow(long n,long p,long m) { long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } public static long pow(long n,long p) { long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } static class Edge implements Comparator<Edge> { public int u; public int v; public int w; public Edge() { } public Edge(int u, int v, int w) { this.u=u; this.v=v; this.w=w; } public int getU() { return u; } public void setU(int u) { this.u = u; } public int getV() { return v; } public void setV(int v) { this.v = v; } public int getW() { return w; } public void setW(int w) { this.w = w; } @Override public int compare(Edge e1, Edge e2) { return e2.w-e1.w; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private SpaceCharFilter filter; byte inbuffer[] = new byte[1024]; int lenbuffer = 0, ptrbuffer = 0; final int M = (int) 1e9 + 7; int md=(int)(1e7+1); int[] SMP=new int[md]; final double eps = 1e-6; final double pi = Math.PI; PrintWriter out; String check = ""; InputStream obj = check.isEmpty() ? System.in : new ByteArrayInputStream(check.getBytes()); public InputReader(InputStream stream) { this.stream = stream; } int readByte() { if (lenbuffer == -1) throw new InputMismatchException(); if (ptrbuffer >= lenbuffer) { ptrbuffer = 0; try { lenbuffer = obj.read(inbuffer); } catch (IOException e) { throw new InputMismatchException(); } } if (lenbuffer <= 0) return -1; return inbuffer[ptrbuffer++]; } public int read() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } String is() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) // when nextLine, (isSpaceChar(b) && b!=' ') { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int ii() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } public long il() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } boolean isSpaceChar(int c) { return (!(c >= 33 && c <= 126)); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } float nf() { return Float.parseFloat(is()); } double id() { return Double.parseDouble(is()); } char ic() { return (char) skip(); } int[] iia(int n) { int a[] = new int[n]; for (int i = 0; i<n; i++) a[i] = ii(); return a; } long[] ila(int n) { long a[] = new long[n]; for (int i = 0; i <n; i++) a[i] = il(); return a; } String[] isa(int n) { String a[] = new String[n]; for (int i = 0; i < n; i++) a[i] = is(); return a; } long mul(long a, long b) { return a * b % M; } long div(long a, long b) { return mul(a, pow(b, M - 2)); } double[][] idm(int n, int m) { double a[][] = new double[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = id(); return a; } int[][] iim(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] = ii(); return a; } public String readLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["4 2\n1 2 4\n2 3 7\n6 20 1 25", "3 3\n1 2 1\n2 3 1\n1 3 1\n30 10 20"]
2 seconds
["6 14 1 25", "12 10 12"]
null
Java 8
standard input
[ "data structures", "graphs", "shortest paths" ]
f41be1fcb6164181c49b37ed9313696e
The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city.
2,000
Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).
standard output
PASSED
acf462eb72b9af991083ecce64e74303
train_004.jsonl
1518793500
Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route.Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins.You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).Formally, for every you have to calculate , where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large.
256 megabytes
import java.util.*; import java.io.*; public class _938_D_BuyATicket { public static class Pair implements Comparable<Pair>{ int id; long val; public Pair(int id, long val) { this.id = id; this.val = val; } @Override public int compareTo(Pair o) { return Long.compare(this.val, o.val); } } public static void main(String[] args) throws IOException { int N = readInt(), M = readInt(); long d[] = new long[N+1]; ArrayList<Pair> graph[] = new ArrayList[N+1]; for(int i = 1; i<=N; i++) graph[i] = new ArrayList<Pair>(); for(int i = 1; i<=M; i++) { int a = readInt(), b = readInt(); long dis = 2*readLong(); graph[a].add(new Pair(b, dis)); graph[b].add(new Pair(a, dis)); } for(int i = 1; i<=N; i++) d[i] = readLong(); PriorityQueue<Pair> pq = new PriorityQueue<Pair>(); for(int i = 1; i<=N; i++) pq.add(new Pair(i, d[i])); while(!pq.isEmpty()) { Pair p = pq.poll(); if(p.val != d[p.id]) continue; int n = p.id; for(Pair e : graph[n]) if(d[e.id] > d[n] + e.val) { d[e.id] = d[n] + e.val; pq.add(new Pair(e.id, d[e.id])); } } for(int i = 1; i<=N; i++) print(d[i] + " "); exit(); } final private static int BUFFER_SIZE = 1 << 16; private static DataInputStream din = new DataInputStream(System.in); private static byte[] buffer = new byte[BUFFER_SIZE]; private static int bufferPointer = 0, bytesRead = 0; static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public static String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = Read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public static String read() throws IOException { byte[] ret = new byte[1024]; int idx = 0; byte c = Read(); while (c <= ' ') { c = Read(); } do { ret[idx++] = c; c = Read(); } while (c != -1 && c != ' ' && c != '\n' && c != '\r'); return new String(ret, 0, idx); } public static int readInt() throws IOException { int ret = 0; byte c = Read(); while (c <= ' ') c = Read(); boolean neg = (c == '-'); if (neg) c = Read(); do { ret = ret * 10 + c - '0'; } while ((c = Read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public static long readLong() throws IOException { long ret = 0; byte c = Read(); while (c <= ' ') c = Read(); boolean neg = (c == '-'); if (neg) c = Read(); do { ret = ret * 10 + c - '0'; } while ((c = Read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public static double readDouble() throws IOException { double ret = 0, div = 1; byte c = Read(); while (c <= ' ') c = Read(); boolean neg = (c == '-'); if (neg) c = Read(); do { ret = ret * 10 + c - '0'; } while ((c = Read()) >= '0' && c <= '9'); if (c == '.') { while ((c = Read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private static void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private static byte Read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } static void print(Object o) { pr.print(o); } static void println(Object o) { pr.println(o); } static void flush() { pr.flush(); } static void println() { pr.println(); } static void exit() throws IOException { din.close(); pr.close(); System.exit(0); } }
Java
["4 2\n1 2 4\n2 3 7\n6 20 1 25", "3 3\n1 2 1\n2 3 1\n1 3 1\n30 10 20"]
2 seconds
["6 14 1 25", "12 10 12"]
null
Java 8
standard input
[ "data structures", "graphs", "shortest paths" ]
f41be1fcb6164181c49b37ed9313696e
The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city.
2,000
Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).
standard output
PASSED
6dc7cb9a2d9cfe6f5e19b1831644d80a
train_004.jsonl
1518793500
Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route.Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins.You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).Formally, for every you have to calculate , where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import static java.util.Arrays.fill; import static java.lang.Math.*; import static java.util.Arrays.sort; import static java.util.Collections.sort; public class D938 { public static int mod = 1000000007; public static long INF = (1L << 60); static FastScanner2 in = new FastScanner2(); static OutputWriter out = new OutputWriter(System.out); static class Edge implements Comparable<Edge> { int to; long wt; Edge(int to,long wt) { this.to=to; this.wt=wt; } @Override public int compareTo(Edge arg0) { // TODO Auto-generated method stub return Long.compare(this.wt, arg0.wt); } } static class Pair implements Comparable<Pair> { int v; long w; Pair(int v,long w) { this.v=v; this.w=w; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub return Long.compare(this.w, o.w); } } public static void main(String[] args) { int n=in.nextInt(); ArrayList<Edge>[] adjacencylist=new ArrayList[n+1]; for(int i=1;i<=n;i++) { adjacencylist[i]=new ArrayList<>(); } int m=in.nextInt(); for(int i=1;i<=m;i++) { int u=in.nextInt(); int v=in.nextInt(); long w=in.nextLong(); adjacencylist[u].add(new Edge(v, w)); adjacencylist[v].add(new Edge(u, w)); } long[] cost=new long[n+1]; PriorityQueue<Pair> minheap=new PriorityQueue<>(); for(int i=1;i<=n;i++) { long w=in.nextLong(); cost[i]=w; minheap.add(new Pair(i, w)); } boolean[] visited=new boolean[n+1]; while(!minheap.isEmpty()) { Pair p=minheap.poll(); int v=p.v; //out.println("extreacted from heap "+v); if(visited[v]) continue; visited[v]=true; long w=p.w; for(Edge e : adjacencylist[v]) { if(cost[v]+2*e.wt<cost[e.to]) { cost[e.to]=cost[v]+2*e.wt; minheap.add(new Pair(e.to, cost[e.to])); //out.println("added to heap minni "+e.to); } else { minheap.add(new Pair(e.to, cost[e.to])); // out.println("added to heap not minni "+e.to); } } } for(int i=1;i<=n;i++) out.print(cost[i]+" "); out.close(); } public static long pow(long x, long n) { long res = 1; for (long p = x; n > 0; n >>= 1, p = (p * p)) { if ((n & 1) != 0) { res = (res * p); } } return res; } public static long pow(long x, long n, long mod) { long res = 1; for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) { if ((n & 1) != 0) { res = (res * p % mod); } } return res; } public static long gcd(long n1, long n2) { long r; while (n2 != 0) { r = n1 % n2; n1 = n2; n2 = r; } return n1; } public static long lcm(long n1, long n2) { long answer = (n1 * n2) / (gcd(n1, n2)); return answer; } static class FastScanner2 { private byte[] buf = new byte[1024]; private int curChar; private int snumChars; public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String nextLine() { String fullLine = null; while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { fullLine = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return fullLine; } return fullLine; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public int nextInt() { return Integer.parseInt(next()); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } }
Java
["4 2\n1 2 4\n2 3 7\n6 20 1 25", "3 3\n1 2 1\n2 3 1\n1 3 1\n30 10 20"]
2 seconds
["6 14 1 25", "12 10 12"]
null
Java 8
standard input
[ "data structures", "graphs", "shortest paths" ]
f41be1fcb6164181c49b37ed9313696e
The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city.
2,000
Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).
standard output
PASSED
6951cfc9e656574041b32c87cf4c524c
train_004.jsonl
1518793500
Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route.Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins.You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).Formally, for every you have to calculate , where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large.
256 megabytes
import javax.swing.*; import java.io.*; import java.util.*; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; public class Main implements Runnable { static final int MOD = (int) 1e9 + 7; static final int MI = (int) 1e9; static final long ML = (long) 1e18; static final Reader in = new Reader(); static final PrintWriter out = new PrintWriter(System.out); StringBuilder answer = new StringBuilder(); public static void main(String[] args) { new Thread(null, new Main(), "persefone", 1 << 32).start(); } @Override public void run() { solve(); printf(); flush(); } void solve() { int cities = in.nextInt(); int roads = in.nextInt(); List<Pair>[] adj = Stream.generate(ArrayList::new).limit(cities).toArray(List[]::new); for (int i = 0; i < roads; i++) { int from = in.nextInt() - 1; int to = in.nextInt() - 1; long cost = in.nextLong() * 2; adj[from].add(new Pair(to, cost)); adj[to].add(new Pair(from, cost)); } long[] minCost = new long[cities]; PriorityQueue<Pair> queue = new PriorityQueue<>(); for (int i = 0; i < cities; i++) { queue.add(new Pair(i, minCost[i] = in.nextLong())); } while (!queue.isEmpty()) { Pair pair = queue.poll(); int from = pair.city; long cost = pair.cost; if (cost != minCost[from]) { continue; } for (Pair edge : adj[from]) { int to = edge.city; cost = edge.cost; if (minCost[from] + cost < minCost[to]) { minCost[to] = minCost[from] + cost; queue.add(new Pair(to, minCost[to])); } } } printf(minCost); } static class Pair implements Comparable<Pair> { private int city; private long cost; public Pair(int city, long cost) { this.city = city; this.cost = cost; } @Override public int compareTo(Pair o) { return Long.compare(cost, o.cost); } } void printf() { out.print(answer); } void close() { out.close(); } void flush() { out.flush(); } void printf(Stream<?> str) { str.forEach(o -> add(o, " ")); add("\n"); } void printf(Object... obj) { printf(false, obj); } void printfWithDescription(Object... obj) { printf(true, obj); } private void printf(boolean b, Object... obj) { if (obj.length > 1) { for (int i = 0; i < obj.length; i++) { if (b) add(obj[i].getClass().getSimpleName(), " - "); if (obj[i] instanceof Collection<?>) { printf((Collection<?>) obj[i]); } else if (obj[i] instanceof int[][]) { printf((int[][]) obj[i]); } else if (obj[i] instanceof long[][]) { printf((long[][]) obj[i]); } else if (obj[i] instanceof double[][]) { printf((double[][]) obj[i]); } else printf(obj[i]); } return; } if (b) add(obj[0].getClass().getSimpleName(), " - "); printf(obj[0]); } void printf(Object o) { if (o instanceof int[]) printf(Arrays.stream((int[]) o).boxed()); else if (o instanceof char[]) printf(new String((char[]) o)); else if (o instanceof long[]) printf(Arrays.stream((long[]) o).boxed()); else if (o instanceof double[]) printf(Arrays.stream((double[]) o).boxed()); else if (o instanceof boolean[]) { for (boolean b : (boolean[]) o) add(b, " "); add("\n"); } else add(o, "\n"); } void printf(int[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(long[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(double[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(boolean[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(Collection<?> col) { printf(col.stream()); } <T, K> void add(T t, K k) { if (t instanceof Collection<?>) { ((Collection<?>) t).forEach(i -> add(i, " ")); } else if (t instanceof Object[]) { Arrays.stream((Object[]) t).forEach(i -> add(i, " ")); } else add(t); add(k); } <T> void add(T t) { answer.append(t); } static class Reader { private BufferedReader br; private StringTokenizer st; Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } Reader(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } boolean isReady() throws IOException { return br.ready(); } String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } } catch (IOException e) { e.printStackTrace(); } 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 Long.parseLong(next()); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
Java
["4 2\n1 2 4\n2 3 7\n6 20 1 25", "3 3\n1 2 1\n2 3 1\n1 3 1\n30 10 20"]
2 seconds
["6 14 1 25", "12 10 12"]
null
Java 8
standard input
[ "data structures", "graphs", "shortest paths" ]
f41be1fcb6164181c49b37ed9313696e
The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city.
2,000
Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).
standard output
PASSED
8847bb4790531df8a7bcedb806d41750
train_004.jsonl
1518793500
Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route.Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins.You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).Formally, for every you have to calculate , where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large.
256 megabytes
import javax.swing.*; import java.io.*; import java.util.*; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; public class Main implements Runnable { static final int MOD = (int) 1e9 + 7; static final int MI = (int) 1e9; static final long ML = (long) 1e18; static final Reader in = new Reader(); static final PrintWriter out = new PrintWriter(System.out); StringBuilder answer = new StringBuilder(); public static void main(String[] args) { new Thread(null, new Main(), "persefone", 1 << 32).start(); } @Override public void run() { solve(); printf(); flush(); } void solve() { int cities = in.nextInt(); int roads = in.nextInt(); List<Pair>[] adj = new ArrayList[cities]; for (int i = 0; i < cities; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < roads; i++) { int from = in.nextInt() - 1; int to = in.nextInt() - 1; long cost = in.nextLong() * 2; adj[from].add(new Pair(to, cost)); adj[to].add(new Pair(from, cost)); } long[] minCost = new long[cities]; PriorityQueue<Pair> queue = new PriorityQueue<>(); for (int i = 0; i < cities; i++) { queue.add(new Pair(i, minCost[i] = in.nextLong())); } while (!queue.isEmpty()) { Pair pair = queue.poll(); int from = pair.city; long cost = pair.cost; if (cost != minCost[from]) { continue; } for (Pair edge : adj[from]) { int to = edge.city; cost = edge.cost; if (minCost[from] + cost < minCost[to]) { minCost[to] = minCost[from] + cost; queue.add(new Pair(to, minCost[to])); } } } printf(minCost); } static class Pair implements Comparable<Pair> { private int city; private long cost; public Pair(int city, long cost) { this.city = city; this.cost = cost; } @Override public int compareTo(Pair o) { return Long.compare(cost, o.cost); } } void printf() { out.print(answer); } void close() { out.close(); } void flush() { out.flush(); } void printf(Stream<?> str) { str.forEach(o -> add(o, " ")); add("\n"); } void printf(Object... obj) { printf(false, obj); } void printfWithDescription(Object... obj) { printf(true, obj); } private void printf(boolean b, Object... obj) { if (obj.length > 1) { for (int i = 0; i < obj.length; i++) { if (b) add(obj[i].getClass().getSimpleName(), " - "); if (obj[i] instanceof Collection<?>) { printf((Collection<?>) obj[i]); } else if (obj[i] instanceof int[][]) { printf((int[][]) obj[i]); } else if (obj[i] instanceof long[][]) { printf((long[][]) obj[i]); } else if (obj[i] instanceof double[][]) { printf((double[][]) obj[i]); } else printf(obj[i]); } return; } if (b) add(obj[0].getClass().getSimpleName(), " - "); printf(obj[0]); } void printf(Object o) { if (o instanceof int[]) printf(Arrays.stream((int[]) o).boxed()); else if (o instanceof char[]) printf(new String((char[]) o)); else if (o instanceof long[]) printf(Arrays.stream((long[]) o).boxed()); else if (o instanceof double[]) printf(Arrays.stream((double[]) o).boxed()); else if (o instanceof boolean[]) { for (boolean b : (boolean[]) o) add(b, " "); add("\n"); } else add(o, "\n"); } void printf(int[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(long[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(double[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(boolean[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(Collection<?> col) { printf(col.stream()); } <T, K> void add(T t, K k) { if (t instanceof Collection<?>) { ((Collection<?>) t).forEach(i -> add(i, " ")); } else if (t instanceof Object[]) { Arrays.stream((Object[]) t).forEach(i -> add(i, " ")); } else add(t); add(k); } <T> void add(T t) { answer.append(t); } static class Reader { private BufferedReader br; private StringTokenizer st; Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } Reader(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } boolean isReady() throws IOException { return br.ready(); } String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } } catch (IOException e) { e.printStackTrace(); } 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 Long.parseLong(next()); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
Java
["4 2\n1 2 4\n2 3 7\n6 20 1 25", "3 3\n1 2 1\n2 3 1\n1 3 1\n30 10 20"]
2 seconds
["6 14 1 25", "12 10 12"]
null
Java 8
standard input
[ "data structures", "graphs", "shortest paths" ]
f41be1fcb6164181c49b37ed9313696e
The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city.
2,000
Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).
standard output
PASSED
f1b7f0c20da6237b7a0c816b37f56d39
train_004.jsonl
1518793500
Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route.Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins.You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).Formally, for every you have to calculate , where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large.
256 megabytes
import javax.swing.*; import java.io.*; import java.util.*; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; public class Main implements Runnable { static final int MOD = (int) 1e9 + 7; static final int MI = (int) 1e9; static final long ML = (long) 1e18; static final Reader in = new Reader(); static final PrintWriter out = new PrintWriter(System.out); StringBuilder answer = new StringBuilder(); public static void main(String[] args) { new Thread(null, new Main(), "persefone", 1 << 32).start(); } @Override public void run() { solve(); printf(); flush(); } void solve() { int cities = in.nextInt(); int roads = in.nextInt(); List<Pair>[] adj = Stream.generate(ArrayList::new).limit(cities).toArray(List[]::new); for (int i = 0; i < roads; i++) { int from = in.nextInt() - 1; int to = in.nextInt() - 1; long cost = in.nextLong() * 2; adj[from].add(new Pair(to, cost)); adj[to].add(new Pair(from, cost)); } long[] minCost = new long[cities]; PriorityQueue<Pair> queue = new PriorityQueue<>(); for (int i = 0; i < cities; i++) { queue.add(new Pair(i, minCost[i] = in.nextLong())); } while (!queue.isEmpty()) { Pair pair = queue.poll(); int from = pair.city; long cost = pair.cost; if (cost != minCost[from]) { continue; } for (Pair edge : adj[from]) { int to = edge.city; cost = edge.cost; if (minCost[from] + cost < minCost[to]) { minCost[to] = minCost[from] + cost; queue.add(new Pair(to, minCost[to])); } } } printf(minCost); } static class Pair implements Comparable<Pair> { private int city; private long cost; public Pair(int city, long cost) { this.city = city; this.cost = cost; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair) o; return city == pair.city && cost == pair.cost; } @Override public int hashCode() { return Objects.hash(city, cost); } @Override public int compareTo(Pair o) { return Long.compare(cost, o.cost); } @Override public String toString() { return "Pair{" + "city=" + city + ", cost=" + cost + '}'; } } void printf() { out.print(answer); } void close() { out.close(); } void flush() { out.flush(); } void printf(Stream<?> str) { str.forEach(o -> add(o, " ")); add("\n"); } void printf(Object... obj) { printf(false, obj); } void printfWithDescription(Object... obj) { printf(true, obj); } private void printf(boolean b, Object... obj) { if (obj.length > 1) { for (int i = 0; i < obj.length; i++) { if (b) add(obj[i].getClass().getSimpleName(), " - "); if (obj[i] instanceof Collection<?>) { printf((Collection<?>) obj[i]); } else if (obj[i] instanceof int[][]) { printf((int[][]) obj[i]); } else if (obj[i] instanceof long[][]) { printf((long[][]) obj[i]); } else if (obj[i] instanceof double[][]) { printf((double[][]) obj[i]); } else printf(obj[i]); } return; } if (b) add(obj[0].getClass().getSimpleName(), " - "); printf(obj[0]); } void printf(Object o) { if (o instanceof int[]) printf(Arrays.stream((int[]) o).boxed()); else if (o instanceof char[]) printf(new String((char[]) o)); else if (o instanceof long[]) printf(Arrays.stream((long[]) o).boxed()); else if (o instanceof double[]) printf(Arrays.stream((double[]) o).boxed()); else if (o instanceof boolean[]) { for (boolean b : (boolean[]) o) add(b, " "); add("\n"); } else add(o, "\n"); } void printf(int[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(long[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(double[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(boolean[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(Collection<?> col) { printf(col.stream()); } <T, K> void add(T t, K k) { if (t instanceof Collection<?>) { ((Collection<?>) t).forEach(i -> add(i, " ")); } else if (t instanceof Object[]) { Arrays.stream((Object[]) t).forEach(i -> add(i, " ")); } else add(t); add(k); } <T> void add(T t) { answer.append(t); } static class Reader { private BufferedReader br; private StringTokenizer st; Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } Reader(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } boolean isReady() throws IOException { return br.ready(); } String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } } catch (IOException e) { e.printStackTrace(); } 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 Long.parseLong(next()); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
Java
["4 2\n1 2 4\n2 3 7\n6 20 1 25", "3 3\n1 2 1\n2 3 1\n1 3 1\n30 10 20"]
2 seconds
["6 14 1 25", "12 10 12"]
null
Java 8
standard input
[ "data structures", "graphs", "shortest paths" ]
f41be1fcb6164181c49b37ed9313696e
The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city.
2,000
Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).
standard output
PASSED
f9291372fec5acbb1d215f00aba5ec14
train_004.jsonl
1518793500
Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route.Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins.You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).Formally, for every you have to calculate , where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; public class D { public static void main(String[] args) throws Exception { try (FastScanner s = new FastScanner(System.in)) { final int n = s.nextInt(); final int m = s.nextInt(); final List<List<long[]>> graph = new ArrayList<>(n); for (int i = 0; i < n; ++i) { graph.add(new ArrayList<>()); } for (int i = 0; i < m; ++i) { final int u = s.nextInt() - 1; final int v = s.nextInt() - 1; final long w = 2*s.nextLong(); graph.get(u).add(new long[] {v, w}); graph.get(v).add(new long[] {u, w}); } final long[] dist = new long[n]; for (int i = 0; i < n; ++i) { dist[i] = s.nextLong(); } final SortedSet<Pair> q = new TreeSet<>(); for (int i = 0; i < n; ++i) { q.add(new Pair(dist[i], i)); } while (!q.isEmpty()) { final Pair top = q.first(); q.remove(top); final int v = (int) top.b; for (long[] a : graph.get(v)) { final int u = (int) a[0]; final long w = a[1]; if (dist[u] > dist[v] + w) { q.remove(new Pair(dist[u], u)); dist[u] = dist[v] + w; q.add(new Pair(dist[u], u)); } } } for (int i = 0; i < n; ++i) { System.out.print(dist[i] + " "); } } } private static final class FastScanner implements AutoCloseable { private String[] tokens; private int next = 0; private final BufferedReader reader; FastScanner(InputStream in) { this.reader = new BufferedReader(new InputStreamReader(in)); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } String next() throws IOException { if (tokens == null || next == tokens.length) { tokens = reader.readLine().split(" "); next = 0; } return tokens[next++]; } @Override public void close() throws Exception { reader.close(); } } private static class Pair implements Comparable<Pair> { private final long a; private final long b; Pair(long a, long b) { this.a = a; this.b = b; } @Override public int compareTo(Pair o) { int cmp = Long.compare(a, o.a); if (cmp == 0) { cmp = Long.compare(b, o.b); } return cmp; } @Override public boolean equals(Object other) { if (!(other instanceof Pair)) { return false; } Pair pair = (Pair)other; return compareTo(pair) == 0; } @Override public int hashCode() { int hash = 17; hash = 31*hash + Long.hashCode(a); hash = 31*hash + Long.hashCode(b); return hash; } } }
Java
["4 2\n1 2 4\n2 3 7\n6 20 1 25", "3 3\n1 2 1\n2 3 1\n1 3 1\n30 10 20"]
2 seconds
["6 14 1 25", "12 10 12"]
null
Java 8
standard input
[ "data structures", "graphs", "shortest paths" ]
f41be1fcb6164181c49b37ed9313696e
The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city.
2,000
Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).
standard output
PASSED
0c508b6654b000265caef0e1dfc25235
train_004.jsonl
1518793500
Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route.Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins.You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).Formally, for every you have to calculate , where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; public class D { private static final long INF = 1000_000_000_000_000_00L; public static void main(String[] args) throws Exception { try (FastScanner s = new FastScanner(System.in)) { final int n = s.nextInt(); final int m = s.nextInt(); final List<List<long[]>> graph = new ArrayList<>(n + 1); for (int i = 0; i <= n; ++i) { graph.add(new ArrayList<>()); } for (int i = 0; i < m; ++i) { final int u = s.nextInt(); final int v = s.nextInt(); final long w = 2*s.nextLong(); graph.get(u).add(new long[] {v, w}); graph.get(v).add(new long[] {u, w}); } final long[] dist = new long[n + 1]; Arrays.fill(dist, INF); for (int i = 1; i <= n; ++i) { final long ai = s.nextLong(); graph.get(0).add(new long[] {i, ai}); graph.get(i).add(new long[] {0, ai}); } dist[0] = 0; final SortedSet<Pair> q = new TreeSet<>(); q.add(new Pair(0, 0)); while (!q.isEmpty()) { final Pair top = q.first(); q.remove(top); final int v = (int) top.b; for (long[] a : graph.get(v)) { final int u = (int) a[0]; final long w = a[1]; if (dist[u] > dist[v] + w) { q.remove(new Pair(dist[u], u)); dist[u] = dist[v] + w; q.add(new Pair(dist[u], u)); } } } for (int i = 1; i <= n; ++i) { System.out.print(dist[i] + " "); } } } private static final class FastScanner implements AutoCloseable { private String[] tokens; private int next = 0; private final BufferedReader reader; FastScanner(InputStream in) { this.reader = new BufferedReader(new InputStreamReader(in)); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } String next() throws IOException { if (tokens == null || next == tokens.length) { tokens = reader.readLine().split(" "); next = 0; } return tokens[next++]; } @Override public void close() throws Exception { reader.close(); } } private static class Pair implements Comparable<Pair> { private final long a; private final long b; Pair(long a, long b) { this.a = a; this.b = b; } @Override public int compareTo(Pair o) { int cmp = Long.compare(a, o.a); if (cmp == 0) { cmp = Long.compare(b, o.b); } return cmp; } @Override public boolean equals(Object other) { if (!(other instanceof Pair)) { return false; } Pair pair = (Pair)other; return compareTo(pair) == 0; } @Override public int hashCode() { int hash = 17; hash = 31*hash + Long.hashCode(a); hash = 31*hash + Long.hashCode(b); return hash; } } }
Java
["4 2\n1 2 4\n2 3 7\n6 20 1 25", "3 3\n1 2 1\n2 3 1\n1 3 1\n30 10 20"]
2 seconds
["6 14 1 25", "12 10 12"]
null
Java 8
standard input
[ "data structures", "graphs", "shortest paths" ]
f41be1fcb6164181c49b37ed9313696e
The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city.
2,000
Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).
standard output
PASSED
2ec3d8ece7baa031f8009e88a1f10b76
train_004.jsonl
1518793500
Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route.Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins.You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).Formally, for every you have to calculate , where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; /** * * @author Saju * */ public class Main { private static int dx[] = { 1, 0, -1, 0}; private static int dy[] = { 0, -1, 0, 1}; private static final long INF = (long) (1e15); private static final int INT_INF = Integer.MAX_VALUE; private static final long NEG_INF = Long.MIN_VALUE; private static final int NEG_INT_INF = Integer.MIN_VALUE; private static final double EPSILON = 1e-10; private static final int MAX = 1007; private static final long MOD = 1000000007; private static final int MAXN = 100007; private static final int MAXA = 10000009; private static final int MAXLOG = 22; public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); /* */ int n = in.nextInt(); int m = in.nextInt(); Graph g = new Graph(n); for(int i = 0; i < m; i++) { int u = in.nextInt(); int v = in.nextInt(); u--; v--; long cost = in.nextLong(); g.addEdge(u, v, cost); } // List<Long> ticketCost = new ArrayList<Long>(); long[] ticketCost = new long[n]; for(int i = 0; i < n; i++) { long l = in.nextLong(); ticketCost[i] = l; } long[] dist = g.calculateShortestPath(ticketCost); for(int i = 0; i < n; i++) { out.print(dist[i] + " "); if(i == n - 1) { out.println(); } } out.flush(); out.close(); System.exit(0); } private static class PP{ int index; int left; int right; public PP(int index, int left, int right){ this.index = index; this.left = left; this.right = right; } } private static class Graph{ private int node; private List<Edge>[] adj; Graph(int node){ this.node = node; adj = new ArrayList[this.node]; for(int i = 0; i < node; i++) { adj[i] = new ArrayList<Main.Edge>(); } } void addEdge(int u, int v, long cost) { Edge e = new Edge(u, v, cost); Edge e1 = new Edge(v, u, cost); adj[u].add(e); adj[v].add(e1); } long[] calculateShortestPath(long[] ticketCost) { long dist[] = new long[node]; PriorityQueue<Node> queue = new PriorityQueue<Main.Node>(new Comparator<Node>() { @Override public int compare(Node o1, Node o2) { int val = Long.compare(o1.distance, o2.distance); return val; } }); for(int i = 0; i < node; i++) { long val = ticketCost[i]; dist[i] = val; queue.offer(new Node(i, val)); } while(!queue.isEmpty()) { Node nn = queue.remove(); int u = nn.node; long udist = nn.distance; if(udist > dist[u]) { continue; } for(Edge e : adj[u]) { int v = e.v; long vdist = 2 * e.cost; long arrive = udist + vdist; if(arrive < dist[v]) { dist[v] = arrive; queue.add(new Node(v, dist[v])); // System.out.println(u + " " + v + " " + vdist + " " + dist[v]); } } } return dist; } } private static class Node{ int operation; int node; long distance; Node(int operation, int node, long distance){ this.operation = operation; this.node = node; this.distance = distance; } Node(int node, long distance){ this.node = node; this.distance = distance; } } private static class Edge{ int u; int v; long cost; Edge(int u, int v, long cost){ this.u = u; this.v = v; this.cost = cost; } int getNeighbourIndex(int node) { if(this.u == node) { return v; } return u; } } private static boolean isPalindrome(String str) { StringBuilder sb = new StringBuilder(); sb.append(str); String str1 = sb.reverse().toString(); return str.equals(str1); } private static String reverseString(String str) { StringBuilder sb = new StringBuilder(); sb.append(str); return sb.reverse().toString(); } private static double distance(Point p1, Point p2) { long divx = p2.x - p1.x; long divy = p2.y - p1.y; divx = divx * divx; divy = divy * divy; return Math.sqrt(divx + divy); } private static String getBinaryStr(int n, int j) { String str = Integer.toBinaryString(n); int k = str.length(); for(int i = 1; i <= j - k; i++) { str = "0" + str; } return str; } // O(log(max(A,M))) static long modInverse(long a, long m) { extendedEuclid(a, m); return (x % m + m) % m; } static long x; static long y; static long gcdx; private static void extendedEuclid(long a, long b) { if (b == 0) { gcdx = a; x = 1; y = 0; } else { extendedEuclid(b, a % b); long temp = x; x = y; y = temp - ((a / b) * y); } } private static void generatePrime(int n) { //O(NloglogN) boolean arr[] = new boolean[n + 5]; Arrays.fill(arr, true); for(int i = 2; i * i <=n; i++){ if(arr[i] == true){ for(int j = i * i; j <= n; j+=i){ arr[j] = false; } } } int count = 0; int start = 0; for(int i = 2; i <= n; i++){ if(arr[i] == true){ // System.out.println(i + " "); count++; } if(count == (start * 100) + 1) { // System.out.println(i); start++; } } System.out.println(); System.out.println(count); } private static Map<Long, Long> primeFactorization(long n, long m){ Map<Long, Long> map = new HashMap<>(); for(long i = 2; i <= Math.sqrt(n); i++){ if(n % i == 0){ long count = 0; while(n % i == 0){ count++; n = n / i; } long val = count * m; map.put(i, val); // System.out.println("i: " + i + ", count: " + count); } } if(n != 1) { // System.out.println(n); map.put(n, m); } return map; } private static class Pair<T>{ T a; T b; Pair(T a, T b){ this.a = a; this.b = b; } } private static class SegmentTree{ int n; private final int MAXN = 100007; private long[] tree = new long[MAXN << 2]; private long[] lazy = new long[MAXN << 2]; private long[] arr = new long[MAXN]; /*** * * arr is 1 based index. * * @param arr * */ SegmentTree(int n, long[] arr){ this.n = n; for(int i = 0; i < arr.length; i++) { this.arr[i] = arr[i]; } } void build(int index, int left, int right) { if(left == right) { tree[index] = arr[left]; } else { int mid = (left + right) / 2; build(index * 2, left, mid); build((index * 2) + 1, mid + 1, right); tree[index] = max(tree[(index * 2)], tree[(index * 2) + 1]); } } long query(int node, int left, int right, int start, int end) { if(left > end || right < start) { return NEG_INF; } if(left >= start && right <= end) { return tree[node]; } int mid = (left + right) / 2; long val1 = query(2 * node, left, mid, start, end); long val2 = query(2 * node + 1, mid + 1, right, start, end); return max(val1, val2); } void update(int node, int left, int right, int idx, long val) { if(left == right) { tree[node] += val; } else { int mid = (left + right) / 2; if(idx <= mid) { update(2 * node, left, mid, idx, val); } else { update(2 * node + 1, mid + 1, right, idx, val); } tree[node] = max(tree[(2 * node) + 1], tree[(2 * node)]); } } void updateRange(int node, int start, int end, int l, int r, long val) { if(lazy[node] != 0) { // This node needs to be updated tree[node] = lazy[node]; // Update it if(start != end) { lazy[node*2] = lazy[node]; // Mark child as lazy lazy[node*2+1] = lazy[node]; // Mark child as lazy } lazy[node] = 0; // Reset it } if(start > end || start > r || end < l) // Current segment is not within range [l, r] return; if(start >= l && end <= r) { // Segment is fully within range tree[node] = val; if(start != end) { // Not leaf node lazy[node*2] = val; lazy[node*2+1] = val; } return; } int mid = (start + end) / 2; updateRange(node*2, start, mid, l, r, val); // Updating left child updateRange(node*2 + 1, mid + 1, end, l, r, val); // Updating right child tree[node] = max(tree[node*2], tree[node*2+1]); // Updating root with max value } long queryRange(int node, int start, int end, int l, int r) { if(start > end || start > r || end < l) return 0; // Out of range if(lazy[node] != 0) { // This node needs to be updated tree[node] = lazy[node]; // Update it if(start != end) { lazy[node*2] = lazy[node]; // Mark child as lazy lazy[node*2+1] = lazy[node]; // Mark child as lazy } lazy[node] = 0; // Reset it } if(start >= l && end <= r) // Current segment is totally within range [l, r] return tree[node]; int mid = (start + end) / 2; long p1 = queryRange(node*2, start, mid, l, r); // Query left child long p2 = queryRange(node*2 + 1, mid + 1, end, l, r); // Query right child return max(p1, p2); } void buildRange(int node, int low, int high){ if(low == high){ tree[node] = arr[low]; return; } int mid = (low + high) / 2; int left = node << 1; int right = left | 1; buildRange(left, low, mid); buildRange(right, mid + 1, high); tree[node] = max(tree[left], tree[right]); } void printSegmentTree() { System.out.println(Arrays.toString(tree)); } } private static class KMP{ private static char[] t; private static char[] s; public int kmp(char[]t, char[]s) { this.t = t; this.s = s; return this.kmp(); } private int kmp() { List<Integer> prefixTable = getPrefixTable(s); int match = 0; int i = 0; int j = 0; int n = t.length; int m = s.length; while(i < n) { if(t[i] == s[j]) { if(j == m - 1) { match++; j = prefixTable.get(j - 1); continue; } i++; j++; } else if(j > 0) { j = prefixTable.get(j - 1); } else { i++; } } return match; } /*** 1. We compute the prefix values π[i] in a loop by iterating <br/> from i=1 to i=n−1 (π[0] just gets assigned with 0). <br/><br/> 2. To calculate the current value π[i] we set the variable j <br/> denoting the length of the best suffix for i−1. Initially j=π[i−1]. <br/> 3. Test if the suffix of length j+1 is also a prefix by <br/><br/> comparing s[j] and s[i]. If they are equal then we assign π[i]=j+1, <br/> otherwise we reduce j to π[j−1] and repeat this step. <br/><br/> 4. If we have reached the length j=0 and still don't have a match, <br/> then we assign π[i]=0 and go to the next index i+1. <br/><br/> @param pattern(String) ***/ private List<Integer> getPrefixTable(char[] pattern){ List<Integer> prefixTable = new ArrayList<Integer>(); int n = pattern.length; for(int i = 0; i < n; i++) { prefixTable.add(0); } for(int i = 1; i < n; i++) { for(int j = prefixTable.get(i - 1); j >= 0;) { if(pattern[j] == pattern[i]) { prefixTable.set(i, j + 1); break; } else if(j > 0){ j = prefixTable.get(j - 1); } else { break; } } } return prefixTable; } } private static class Point { long x; long y; Point(long x, long y){ this.x = x; this.y = y; } @Override public boolean equals(Object obj) { Point ob = (Point) obj; if(this.x == ob.x && this.y == ob.y){ return true; } return false; } @Override public String toString() { return this.x + " " + this.y; } @Override public int hashCode() { return 0; } } private static long pow(int base, int pow) { long val = 1L; for(int i = 1; i <= pow; i++) { val *= base; } return val; } private static int log(int x, int base) { return (int) (Math.log(x) / Math.log(base)); } private static int log(long x, int base) { return (int) (Math.log(x) / Math.log(base)); } private static long max(long a, long b) { if (a >= b) { return a; } return b; } private static long abs(long a) { if (a < 0) { return -a; } return a; } private static int abs(int a) { if (a < 0) { return -a; } return a; } private static int max(int a, int b) { if (a >= b) { return a; } return b; } private static int min(int a, int b) { if (a <= b) { return a; } return b; } private static long min(long a, long b) { if (a <= b) { return a; } return b; } private static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } private static int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } private static long bigMod(long n, long k, long m) { long ans = 1; while (k > 0) { if ((k & 1) == 1) { ans = (ans * n) % m; } n = (n * n) % m; k >>= 1; } return ans; } /* * Returns an iterator pointing to the first element in the range [first, * last] which does not compare less than val. * */ private static int lowerBoundNew(long[] arr, long num) { int start = 0; int end = arr.length - 1; int index = 0; int len = arr.length; int mid = 0; while (true) { if (start > end) { break; } mid = (start + end) / 2; if (arr[mid] > num) { end = mid - 1; } else if (arr[mid] < num) { start = mid + 1; } else { while (mid >= 0 && arr[mid] == num) { mid--; } return mid + 1; } } if (arr[mid] < num) { return mid + 1; } return mid; } /* * upper_bound() is a standard library function in C++ defined in the header * . It returns an iterator pointing to the first element in the range * [first, last) that is greater than value, or last if no such element is * found * */ private static int upperBoundNew(long arr[], long num) { int start = 0; int end = arr.length - 1; int index = 0; int len = arr.length; int mid = 0; while (true) { if (start > end) { break; } mid = (start + end) / 2; long val = arr[mid]; if (val > num) { end = mid - 1; } else if (val < num) { start = mid + 1; } else { while (mid < len && arr[mid] == num) { mid++; } if (mid == len - 1 && arr[mid] == num) { return mid + 1; } else { return mid; } } } if (arr[mid] < num) { return mid + 1; } return mid; } private static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (IOException e) { return null; } return tokenizer.nextToken(); } public String nextLine() { String line = null; try { tokenizer = null; line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public boolean hasNext() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (Exception e) { return false; } return true; } } }
Java
["4 2\n1 2 4\n2 3 7\n6 20 1 25", "3 3\n1 2 1\n2 3 1\n1 3 1\n30 10 20"]
2 seconds
["6 14 1 25", "12 10 12"]
null
Java 8
standard input
[ "data structures", "graphs", "shortest paths" ]
f41be1fcb6164181c49b37ed9313696e
The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city.
2,000
Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).
standard output
PASSED
ff839e553e519c1048d6172bc3b42f60
train_004.jsonl
1518793500
Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route.Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins.You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).Formally, for every you have to calculate , where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large.
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.Collector; public class Main extends Thread { private static MyScanner scanner = new MyScanner(); private static PrintWriter writer = new PrintWriter(System.out); // private static Scanner scanner = new Scanner(System.in);ff private static Set<Pair<Integer, Long>>[] graph; private static long[] distance; private static int n; public static void main(String[] args) throws IOException { n = scanner.nextInt(); distance = new long[n]; graph = new HashSet[n]; for (int i = 0; i < n; i++) { graph[i] = new HashSet<>(); } int m = scanner.nextInt(); for (int i = 0; i < m; i++) { int v = scanner.nextInt() - 1; int u = scanner.nextInt() - 1; long w = 2 * scanner.nextLong(); graph[v].add(new Pair<>(u, w)); graph[u].add(new Pair<>(v, w)); } for (int i = 0; i < n; i++) { distance[i] = scanner.nextLong(); } findDistances2(); for (int i = 0; i < n; i++) { writer.print(distance[i] + " "); } writer.flush(); writer.close(); } private static void findDistances() { PriorityQueue<Integer> q = new PriorityQueue<>(Comparator.comparingLong(o -> distance[o]) ); for (int i = 0; i < n; i++) { q.add(i); } boolean[] seen = new boolean[n]; while (!q.isEmpty()) { Integer u = q.poll(); if (seen[u]) continue; seen[u] = true; for (Pair<Integer, Long> node : graph[u]) { int v = node.x; long w = node.y; if (distance[v] > distance[u] + w) { distance[v] = distance[u] + w; q.add(v); } } } } private static void findDistances2() { PriorityQueue<Pair<Integer, Long>> q = new PriorityQueue<>(Comparator.comparingLong(o -> o.y)); for (int i = 0; i < n; i++) { q.add(new Pair<>(i, distance[i])); } boolean[] seen = new boolean[n]; while (!q.isEmpty()) { Integer u = q.poll().x; if (seen[u]) continue; seen[u] = true; for (Pair<Integer, Long> node : graph[u]) { int v = node.x; long w = node.y; if (distance[v] > distance[u] + w) { distance[v] = distance[u] + w; q.add(new Pair<>(v, distance[v])); } } } } private static void shit() { long[][] g = new long[16][16]; for (int i = 0; i < 26; i++) { g[scanner.nextInt() - 1][scanner.nextInt() - 1] = scanner.nextLong(); } for (int i = 0; i < 16; i++) { for (int j = 0; j < 16; j++) { System.out.print(g[i][j] + " "); } System.out.print("\n"); } } private static class Pair<X, Y> { public X x; public Y y; public Pair(X x, Y y) { this.x = x; this.y = y; } } 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 FPair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<FPair<U, V>> { public U first; public V second; public FPair(U first, V second) { this.first = first; this.second = second; } public int hashCode() { return (first == null ? 0 : first.hashCode() * 31) + (second == null ? 0 : second.hashCode()); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FPair<U, V> p = (FPair<U, V>) o; return (first == null ? p.first == null : first.equals(p.first)) && (second == null ? p.second == null : second.equals(p.second)); } public int compareTo(FPair<U, V> b) { int cmpU = first.compareTo(b.first); return cmpU != 0 ? cmpU : second.compareTo(b.second); } } }
Java
["4 2\n1 2 4\n2 3 7\n6 20 1 25", "3 3\n1 2 1\n2 3 1\n1 3 1\n30 10 20"]
2 seconds
["6 14 1 25", "12 10 12"]
null
Java 8
standard input
[ "data structures", "graphs", "shortest paths" ]
f41be1fcb6164181c49b37ed9313696e
The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city.
2,000
Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).
standard output
PASSED
9d69e8788ad8e1a37550838d641422b6
train_004.jsonl
1570374300
You are given a sequence $$$a_1, a_2, \dots, a_n$$$, consisting of integers.You can apply the following operation to this sequence: choose some integer $$$x$$$ and move all elements equal to $$$x$$$ either to the beginning, or to the end of $$$a$$$. Note that you have to move all these elements in one direction in one operation.For example, if $$$a = [2, 1, 3, 1, 1, 3, 2]$$$, you can get the following sequences in one operation (for convenience, denote elements equal to $$$x$$$ as $$$x$$$-elements): $$$[1, 1, 1, 2, 3, 3, 2]$$$ if you move all $$$1$$$-elements to the beginning; $$$[2, 3, 3, 2, 1, 1, 1]$$$ if you move all $$$1$$$-elements to the end; $$$[2, 2, 1, 3, 1, 1, 3]$$$ if you move all $$$2$$$-elements to the beginning; $$$[1, 3, 1, 1, 3, 2, 2]$$$ if you move all $$$2$$$-elements to the end; $$$[3, 3, 2, 1, 1, 1, 2]$$$ if you move all $$$3$$$-elements to the beginning; $$$[2, 1, 1, 1, 2, 3, 3]$$$ if you move all $$$3$$$-elements to the end; You have to determine the minimum number of such operations so that the sequence $$$a$$$ becomes sorted in non-descending order. Non-descending order means that for all $$$i$$$ from $$$2$$$ to $$$n$$$, the condition $$$a_{i-1} \le a_i$$$ is satisfied.Note that you have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.*; import java.util.*; /** * @author Komal Nagar */ public class Code { public static void main(String[] args) throws IOException { IoHandler ioHandler = new IoHandler(); new Task().solve(ioHandler, ioHandler.out); ioHandler.out.close(); } private static class Task { private void solve(IoHandler reader, PrintWriter writer) throws IOException { int q = reader.nextInt(); while (q-- > 0) { int n = reader.nextInt(); Map<Integer, MinMax> map = new HashMap<>(); for (int i = 0; i <= n; i++) { map.put(i, new MinMax(Integer.MAX_VALUE, Integer.MIN_VALUE)); } Set<Integer> set = new HashSet<>(); for (int i = 0; i < n; i++) { int value = reader.nextInt(); set.add(value); MinMax minMax = map.get(value); map.put(value, new MinMax(Math.min(minMax.min, i), Math.max(minMax.max, i))); } List<Integer> values = new ArrayList<>(set); Collections.sort(values); int result = n; int[] dp = new int[values.size() + 1]; for (int i = values.size() - 1; i >= 0; i--) { if (i + 1 == values.size() || map.get(values.get(i)).max >= map.get(values.get(i + 1)).min) { dp[i] = 1; } else { dp[i] = dp[i + 1] + 1; } result = Math.min(result, values.size() - dp[i]); } writer.println(result); } } } private static class MinMax { private final int min, max; private MinMax(int min, int max) { this.min = min; this.max = max; } } private static class IoHandler { private final PrintWriter out; private final BufferedReader reader; private StringTokenizer tokenizer; IoHandler() throws IOException { boolean local = new File("input").exists(); InputStream stream = local ? new FileInputStream("input") : System.in; out = local ? new PrintWriter(new FileOutputStream("output")) : new PrintWriter(System.out); reader = new BufferedReader(new InputStreamReader(stream), 32768); } private String nextString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextString()); } } }
Java
["3\n7\n3 1 6 6 3 1 1\n8\n1 1 4 4 4 7 8 8\n7\n4 2 5 2 6 2 7"]
2 seconds
["2\n0\n1"]
NoteIn the first query, you can move all $$$1$$$-elements to the beginning (after that sequence turn into $$$[1, 1, 1, 3, 6, 6, 3]$$$) and then move all $$$6$$$-elements to the end.In the second query, the sequence is sorted initially, so the answer is zero.In the third query, you have to move all $$$2$$$-elements to the beginning.
Java 8
standard input
[ "dp", "two pointers" ]
326dcf837da6909b3f62db16f2800812
The first line contains one integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — the number of the queries. Each query is represented by two consecutive lines. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of elements. The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le n$$$) — the elements. It is guaranteed that the sum of all $$$n$$$ does not exceed $$$3 \cdot 10^5$$$.
2,000
For each query print one integer — the minimum number of operation for sorting sequence $$$a$$$ in non-descending order.
standard output
PASSED
b6028175a404899e18b5ba8c9f6c7bcc
train_004.jsonl
1570374300
You are given a sequence $$$a_1, a_2, \dots, a_n$$$, consisting of integers.You can apply the following operation to this sequence: choose some integer $$$x$$$ and move all elements equal to $$$x$$$ either to the beginning, or to the end of $$$a$$$. Note that you have to move all these elements in one direction in one operation.For example, if $$$a = [2, 1, 3, 1, 1, 3, 2]$$$, you can get the following sequences in one operation (for convenience, denote elements equal to $$$x$$$ as $$$x$$$-elements): $$$[1, 1, 1, 2, 3, 3, 2]$$$ if you move all $$$1$$$-elements to the beginning; $$$[2, 3, 3, 2, 1, 1, 1]$$$ if you move all $$$1$$$-elements to the end; $$$[2, 2, 1, 3, 1, 1, 3]$$$ if you move all $$$2$$$-elements to the beginning; $$$[1, 3, 1, 1, 3, 2, 2]$$$ if you move all $$$2$$$-elements to the end; $$$[3, 3, 2, 1, 1, 1, 2]$$$ if you move all $$$3$$$-elements to the beginning; $$$[2, 1, 1, 1, 2, 3, 3]$$$ if you move all $$$3$$$-elements to the end; You have to determine the minimum number of such operations so that the sequence $$$a$$$ becomes sorted in non-descending order. Non-descending order means that for all $$$i$$$ from $$$2$$$ to $$$n$$$, the condition $$$a_{i-1} \le a_i$$$ is satisfied.Note that you have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.*; import java.util.*; /** * @author Komal Nagar */ public class Code { public static void main(String[] args) throws IOException { IoHandler ioHandler = new IoHandler(); new Task().solve(ioHandler, ioHandler.out); ioHandler.out.close(); } private static class Task { private void solve(IoHandler reader, PrintWriter writer) throws IOException { int q = reader.nextInt(); while (q-- > 0) { int n = reader.nextInt(); Map<Integer, Integer> minMap = new HashMap<>(), maxMap = new HashMap<>(); for (int i = 0; i <= n; i++) { minMap.put(i, Integer.MAX_VALUE); maxMap.put(i, Integer.MIN_VALUE); } Set<Integer> set = new HashSet<>(); for (int i = 0; i < n; i++) { int value = reader.nextInt(); set.add(value); minMap.put(value, Math.min(minMap.get(value), i)); maxMap.put(value, Math.max(maxMap.get(value), i)); } List<Integer> values = new ArrayList<>(set); Collections.sort(values); int result = n; int[] dp = new int[values.size() + 1]; for (int i = values.size() - 1; i >= 0; i--) { if (i + 1 == values.size() || maxMap.get(values.get(i)) >= minMap.get(values.get(i + 1))) { dp[i] = 1; } else { dp[i] = dp[i + 1] + 1; } result = Math.min(result, values.size() - dp[i]); } writer.println(result); } } } private static class IoHandler { private final PrintWriter out; private final BufferedReader reader; private StringTokenizer tokenizer; IoHandler() throws IOException { boolean local = new File("input").exists(); InputStream stream = local ? new FileInputStream("input") : System.in; out = local ? new PrintWriter(new FileOutputStream("output")) : new PrintWriter(System.out); reader = new BufferedReader(new InputStreamReader(stream), 32768); } private String nextString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextString()); } } }
Java
["3\n7\n3 1 6 6 3 1 1\n8\n1 1 4 4 4 7 8 8\n7\n4 2 5 2 6 2 7"]
2 seconds
["2\n0\n1"]
NoteIn the first query, you can move all $$$1$$$-elements to the beginning (after that sequence turn into $$$[1, 1, 1, 3, 6, 6, 3]$$$) and then move all $$$6$$$-elements to the end.In the second query, the sequence is sorted initially, so the answer is zero.In the third query, you have to move all $$$2$$$-elements to the beginning.
Java 8
standard input
[ "dp", "two pointers" ]
326dcf837da6909b3f62db16f2800812
The first line contains one integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — the number of the queries. Each query is represented by two consecutive lines. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of elements. The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le n$$$) — the elements. It is guaranteed that the sum of all $$$n$$$ does not exceed $$$3 \cdot 10^5$$$.
2,000
For each query print one integer — the minimum number of operation for sorting sequence $$$a$$$ in non-descending order.
standard output
PASSED
5716e873013b05acd65c5dbd201cace5
train_004.jsonl
1570374300
You are given a sequence $$$a_1, a_2, \dots, a_n$$$, consisting of integers.You can apply the following operation to this sequence: choose some integer $$$x$$$ and move all elements equal to $$$x$$$ either to the beginning, or to the end of $$$a$$$. Note that you have to move all these elements in one direction in one operation.For example, if $$$a = [2, 1, 3, 1, 1, 3, 2]$$$, you can get the following sequences in one operation (for convenience, denote elements equal to $$$x$$$ as $$$x$$$-elements): $$$[1, 1, 1, 2, 3, 3, 2]$$$ if you move all $$$1$$$-elements to the beginning; $$$[2, 3, 3, 2, 1, 1, 1]$$$ if you move all $$$1$$$-elements to the end; $$$[2, 2, 1, 3, 1, 1, 3]$$$ if you move all $$$2$$$-elements to the beginning; $$$[1, 3, 1, 1, 3, 2, 2]$$$ if you move all $$$2$$$-elements to the end; $$$[3, 3, 2, 1, 1, 1, 2]$$$ if you move all $$$3$$$-elements to the beginning; $$$[2, 1, 1, 1, 2, 3, 3]$$$ if you move all $$$3$$$-elements to the end; You have to determine the minimum number of such operations so that the sequence $$$a$$$ becomes sorted in non-descending order. Non-descending order means that for all $$$i$$$ from $$$2$$$ to $$$n$$$, the condition $$$a_{i-1} \le a_i$$$ is satisfied.Note that you have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.*; import java.util.*; /** * @author Komal Nagar */ public class Code { public static void main(String[] args) throws IOException { IoHandler ioHandler = new IoHandler(); new Task().solve(ioHandler, ioHandler.out); ioHandler.out.close(); } private static class Task { private void solve(IoHandler reader, PrintWriter writer) throws IOException { int q = reader.nextInt(); while (q-- > 0) { int n = reader.nextInt(); SortedMap<Integer, MinMax> map = new TreeMap<>(); for (int i = 0; i < n; i++) { int value = reader.nextInt(); MinMax minMax = map.containsKey(value) ? map.get(value) : new MinMax(Integer.MAX_VALUE, Integer.MIN_VALUE); map.put(value, new MinMax(Math.min(minMax.min, i), Math.max(minMax.max, i))); } int prevValue = 0, result = n; Map.Entry<Integer, MinMax> prev = null; for (Map.Entry<Integer, MinMax> entry : map.entrySet()) { if (prev == null || prev.getValue().max >= entry.getValue().min) { prevValue = 1; } else { prevValue = prevValue + 1; } prev = entry; result = Math.min(result, map.size() - prevValue); } writer.println(result); } } } private static class MinMax { private final int min, max; private MinMax(int min, int max) { this.min = min; this.max = max; } } private static class IoHandler { private final PrintWriter out; private final BufferedReader reader; private StringTokenizer tokenizer; IoHandler() throws IOException { boolean local = new File("input").exists(); InputStream stream = local ? new FileInputStream("input") : System.in; out = local ? new PrintWriter(new FileOutputStream("output")) : new PrintWriter(System.out); reader = new BufferedReader(new InputStreamReader(stream), 32768); } private String nextString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextString()); } } }
Java
["3\n7\n3 1 6 6 3 1 1\n8\n1 1 4 4 4 7 8 8\n7\n4 2 5 2 6 2 7"]
2 seconds
["2\n0\n1"]
NoteIn the first query, you can move all $$$1$$$-elements to the beginning (after that sequence turn into $$$[1, 1, 1, 3, 6, 6, 3]$$$) and then move all $$$6$$$-elements to the end.In the second query, the sequence is sorted initially, so the answer is zero.In the third query, you have to move all $$$2$$$-elements to the beginning.
Java 8
standard input
[ "dp", "two pointers" ]
326dcf837da6909b3f62db16f2800812
The first line contains one integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — the number of the queries. Each query is represented by two consecutive lines. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of elements. The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le n$$$) — the elements. It is guaranteed that the sum of all $$$n$$$ does not exceed $$$3 \cdot 10^5$$$.
2,000
For each query print one integer — the minimum number of operation for sorting sequence $$$a$$$ in non-descending order.
standard output
PASSED
bcac6015f27334e5229b0d9eb2ccf314
train_004.jsonl
1570374300
You are given a sequence $$$a_1, a_2, \dots, a_n$$$, consisting of integers.You can apply the following operation to this sequence: choose some integer $$$x$$$ and move all elements equal to $$$x$$$ either to the beginning, or to the end of $$$a$$$. Note that you have to move all these elements in one direction in one operation.For example, if $$$a = [2, 1, 3, 1, 1, 3, 2]$$$, you can get the following sequences in one operation (for convenience, denote elements equal to $$$x$$$ as $$$x$$$-elements): $$$[1, 1, 1, 2, 3, 3, 2]$$$ if you move all $$$1$$$-elements to the beginning; $$$[2, 3, 3, 2, 1, 1, 1]$$$ if you move all $$$1$$$-elements to the end; $$$[2, 2, 1, 3, 1, 1, 3]$$$ if you move all $$$2$$$-elements to the beginning; $$$[1, 3, 1, 1, 3, 2, 2]$$$ if you move all $$$2$$$-elements to the end; $$$[3, 3, 2, 1, 1, 1, 2]$$$ if you move all $$$3$$$-elements to the beginning; $$$[2, 1, 1, 1, 2, 3, 3]$$$ if you move all $$$3$$$-elements to the end; You have to determine the minimum number of such operations so that the sequence $$$a$$$ becomes sorted in non-descending order. Non-descending order means that for all $$$i$$$ from $$$2$$$ to $$$n$$$, the condition $$$a_{i-1} \le a_i$$$ is satisfied.Note that you have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.*; import java.util.*; /** * @author Komal Nagar */ public class Code { public static void main(String[] args) throws IOException { IoHandler ioHandler = new IoHandler(); new Task().solve(ioHandler, ioHandler.out); ioHandler.out.close(); } private static class Task { private void solve(IoHandler reader, PrintWriter writer) throws IOException { int q = reader.nextInt(); while (q-- > 0) { int n = reader.nextInt(); Map<Integer, MinMax> map = new HashMap<>(); for (int i = 0; i < n; i++) { int value = reader.nextInt(); MinMax minMax = map.containsKey(value) ? map.get(value) : new MinMax(Integer.MAX_VALUE, Integer.MIN_VALUE); map.put(value, new MinMax(Math.min(minMax.min, i), Math.max(minMax.max, i))); } List<Integer> values = new ArrayList<>(map.keySet()); Collections.sort(values); int result = n; int[] dp = new int[values.size() + 1]; for (int i = values.size() - 1; i >= 0; i--) { if (i + 1 == values.size() || map.get(values.get(i)).max >= map.get(values.get(i + 1)).min) { dp[i] = 1; } else { dp[i] = dp[i + 1] + 1; } result = Math.min(result, values.size() - dp[i]); } writer.println(result); } } } private static class MinMax { private final int min, max; private MinMax(int min, int max) { this.min = min; this.max = max; } } private static class IoHandler { private final PrintWriter out; private final BufferedReader reader; private StringTokenizer tokenizer; IoHandler() throws IOException { boolean local = new File("input").exists(); InputStream stream = local ? new FileInputStream("input") : System.in; out = local ? new PrintWriter(new FileOutputStream("output")) : new PrintWriter(System.out); reader = new BufferedReader(new InputStreamReader(stream), 32768); } private String nextString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextString()); } } }
Java
["3\n7\n3 1 6 6 3 1 1\n8\n1 1 4 4 4 7 8 8\n7\n4 2 5 2 6 2 7"]
2 seconds
["2\n0\n1"]
NoteIn the first query, you can move all $$$1$$$-elements to the beginning (after that sequence turn into $$$[1, 1, 1, 3, 6, 6, 3]$$$) and then move all $$$6$$$-elements to the end.In the second query, the sequence is sorted initially, so the answer is zero.In the third query, you have to move all $$$2$$$-elements to the beginning.
Java 8
standard input
[ "dp", "two pointers" ]
326dcf837da6909b3f62db16f2800812
The first line contains one integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — the number of the queries. Each query is represented by two consecutive lines. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of elements. The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le n$$$) — the elements. It is guaranteed that the sum of all $$$n$$$ does not exceed $$$3 \cdot 10^5$$$.
2,000
For each query print one integer — the minimum number of operation for sorting sequence $$$a$$$ in non-descending order.
standard output
PASSED
5cc708c3510d2a6e9c3ffb0e12eac93b
train_004.jsonl
1570374300
You are given a sequence $$$a_1, a_2, \dots, a_n$$$, consisting of integers.You can apply the following operation to this sequence: choose some integer $$$x$$$ and move all elements equal to $$$x$$$ either to the beginning, or to the end of $$$a$$$. Note that you have to move all these elements in one direction in one operation.For example, if $$$a = [2, 1, 3, 1, 1, 3, 2]$$$, you can get the following sequences in one operation (for convenience, denote elements equal to $$$x$$$ as $$$x$$$-elements): $$$[1, 1, 1, 2, 3, 3, 2]$$$ if you move all $$$1$$$-elements to the beginning; $$$[2, 3, 3, 2, 1, 1, 1]$$$ if you move all $$$1$$$-elements to the end; $$$[2, 2, 1, 3, 1, 1, 3]$$$ if you move all $$$2$$$-elements to the beginning; $$$[1, 3, 1, 1, 3, 2, 2]$$$ if you move all $$$2$$$-elements to the end; $$$[3, 3, 2, 1, 1, 1, 2]$$$ if you move all $$$3$$$-elements to the beginning; $$$[2, 1, 1, 1, 2, 3, 3]$$$ if you move all $$$3$$$-elements to the end; You have to determine the minimum number of such operations so that the sequence $$$a$$$ becomes sorted in non-descending order. Non-descending order means that for all $$$i$$$ from $$$2$$$ to $$$n$$$, the condition $$$a_{i-1} \le a_i$$$ is satisfied.Note that you have to answer $$$q$$$ independent queries.
256 megabytes
// package com.company; import java.util.*; import java.lang.*; import java.io.*; //****Use Integer Wrapper Class for Arrays.sort()**** public class AM4 { public static void main(String[] Args){ FastReader scan=new FastReader(); int t=scan.nextInt(); StringBuilder print=new StringBuilder(); while(t-->0){ int n=scan.nextInt(); Map<Integer,ArrayList<Integer>> m=new HashMap<>(); for(int i=0;i<n;i++){ int num=scan.nextInt(); m.putIfAbsent(num,new ArrayList<>()); m.get(num).add(i); } ArrayList<Integer> arr=new ArrayList<>(); for(Integer i:m.keySet()){ arr.add(i); } Collections.sort(arr); int ans=n-1; for (int i = 0; i <arr.size() ;) { int j=i; while(j<arr.size()-1){ int size=m.get(arr.get(j)).size(); if(m.get(arr.get(j)).get(size-1)<m.get(arr.get(j+1)).get(0)){ j++; } else{ break; } } int e=j-i+1; ans=Math.min(ans,arr.size()-e); i=j+1; } print.append(ans+"\n"); } System.out.println(print); } 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; } } }
Java
["3\n7\n3 1 6 6 3 1 1\n8\n1 1 4 4 4 7 8 8\n7\n4 2 5 2 6 2 7"]
2 seconds
["2\n0\n1"]
NoteIn the first query, you can move all $$$1$$$-elements to the beginning (after that sequence turn into $$$[1, 1, 1, 3, 6, 6, 3]$$$) and then move all $$$6$$$-elements to the end.In the second query, the sequence is sorted initially, so the answer is zero.In the third query, you have to move all $$$2$$$-elements to the beginning.
Java 8
standard input
[ "dp", "two pointers" ]
326dcf837da6909b3f62db16f2800812
The first line contains one integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — the number of the queries. Each query is represented by two consecutive lines. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of elements. The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le n$$$) — the elements. It is guaranteed that the sum of all $$$n$$$ does not exceed $$$3 \cdot 10^5$$$.
2,000
For each query print one integer — the minimum number of operation for sorting sequence $$$a$$$ in non-descending order.
standard output
PASSED
c21ce76b7397d18cd4678245ac3e7352
train_004.jsonl
1570374300
You are given a sequence $$$a_1, a_2, \dots, a_n$$$, consisting of integers.You can apply the following operation to this sequence: choose some integer $$$x$$$ and move all elements equal to $$$x$$$ either to the beginning, or to the end of $$$a$$$. Note that you have to move all these elements in one direction in one operation.For example, if $$$a = [2, 1, 3, 1, 1, 3, 2]$$$, you can get the following sequences in one operation (for convenience, denote elements equal to $$$x$$$ as $$$x$$$-elements): $$$[1, 1, 1, 2, 3, 3, 2]$$$ if you move all $$$1$$$-elements to the beginning; $$$[2, 3, 3, 2, 1, 1, 1]$$$ if you move all $$$1$$$-elements to the end; $$$[2, 2, 1, 3, 1, 1, 3]$$$ if you move all $$$2$$$-elements to the beginning; $$$[1, 3, 1, 1, 3, 2, 2]$$$ if you move all $$$2$$$-elements to the end; $$$[3, 3, 2, 1, 1, 1, 2]$$$ if you move all $$$3$$$-elements to the beginning; $$$[2, 1, 1, 1, 2, 3, 3]$$$ if you move all $$$3$$$-elements to the end; You have to determine the minimum number of such operations so that the sequence $$$a$$$ becomes sorted in non-descending order. Non-descending order means that for all $$$i$$$ from $$$2$$$ to $$$n$$$, the condition $$$a_{i-1} \le a_i$$$ is satisfied.Note that you have to answer $$$q$$$ independent queries.
256 megabytes
import java.io.*; import java.util.*; public class D_1223 { static FastReader in; static PrintWriter out; static void solve() { int n = in.nextInt(); int[] a = new int[n]; TreeSet<Integer> ts = new TreeSet<>(); for (int i = 0; i < n; i++) { a[i] = in.nextInt(); ts.add(a[i]); } ArrayList<Integer> uniq = new ArrayList<>(ts); int[] start = new int[n + 1]; Arrays.fill(start, -1); int[] end = new int[n + 1]; Arrays.fill(end, -1); for (int i = 0; i < n; i++) { if (start[a[i]] == -1) start[a[i]] = i; end[a[i]] = i; } int maxSeq = 1, seq = 1; for (int i = 0; i < uniq.size() - 1; i++) { if (start[uniq.get(i + 1)] > end[uniq.get(i)]) { seq++; maxSeq = Math.max(maxSeq, seq); } else { seq = 1; } } out.println(uniq.size() - maxSeq); } public static void main(String[] args) { in = new FastReader(System.in); // in = new FastReader(new FileInputStream("input.txt")); out = new PrintWriter(System.out); // out = new PrintWriter(new FileOutputStream("output.txt")); int q = in.nextInt(); while (q-- > 0) solve(); out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; FastReader(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } Integer nextInt() { return Integer.parseInt(next()); } Long nextLong() { return Long.parseLong(next()); } Double nextDouble() { return Double.parseDouble(next()); } String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
Java
["3\n7\n3 1 6 6 3 1 1\n8\n1 1 4 4 4 7 8 8\n7\n4 2 5 2 6 2 7"]
2 seconds
["2\n0\n1"]
NoteIn the first query, you can move all $$$1$$$-elements to the beginning (after that sequence turn into $$$[1, 1, 1, 3, 6, 6, 3]$$$) and then move all $$$6$$$-elements to the end.In the second query, the sequence is sorted initially, so the answer is zero.In the third query, you have to move all $$$2$$$-elements to the beginning.
Java 8
standard input
[ "dp", "two pointers" ]
326dcf837da6909b3f62db16f2800812
The first line contains one integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — the number of the queries. Each query is represented by two consecutive lines. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of elements. The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le n$$$) — the elements. It is guaranteed that the sum of all $$$n$$$ does not exceed $$$3 \cdot 10^5$$$.
2,000
For each query print one integer — the minimum number of operation for sorting sequence $$$a$$$ in non-descending order.
standard output
PASSED
3a84e44842ba84706e3e64299c1d7344
train_004.jsonl
1570374300
You are given a sequence $$$a_1, a_2, \dots, a_n$$$, consisting of integers.You can apply the following operation to this sequence: choose some integer $$$x$$$ and move all elements equal to $$$x$$$ either to the beginning, or to the end of $$$a$$$. Note that you have to move all these elements in one direction in one operation.For example, if $$$a = [2, 1, 3, 1, 1, 3, 2]$$$, you can get the following sequences in one operation (for convenience, denote elements equal to $$$x$$$ as $$$x$$$-elements): $$$[1, 1, 1, 2, 3, 3, 2]$$$ if you move all $$$1$$$-elements to the beginning; $$$[2, 3, 3, 2, 1, 1, 1]$$$ if you move all $$$1$$$-elements to the end; $$$[2, 2, 1, 3, 1, 1, 3]$$$ if you move all $$$2$$$-elements to the beginning; $$$[1, 3, 1, 1, 3, 2, 2]$$$ if you move all $$$2$$$-elements to the end; $$$[3, 3, 2, 1, 1, 1, 2]$$$ if you move all $$$3$$$-elements to the beginning; $$$[2, 1, 1, 1, 2, 3, 3]$$$ if you move all $$$3$$$-elements to the end; You have to determine the minimum number of such operations so that the sequence $$$a$$$ becomes sorted in non-descending order. Non-descending order means that for all $$$i$$$ from $$$2$$$ to $$$n$$$, the condition $$$a_{i-1} \le a_i$$$ is satisfied.Note that you have to answer $$$q$$$ independent queries.
256 megabytes
import java.util.*; import java.io.*; public class SequenceSorting { public static void main(String[] args) { FastScanner scanner = new FastScanner(); PrintWriter out = new PrintWriter(System.out, false); int q = scanner.nextInt(); while(q-->0) { int n = scanner.nextInt(); int[] arr = new int[n]; int[] first = new int[n+1]; int[] last = new int[n+1]; Arrays.fill(first, -1); int cnt = 0; for(int i = 0; i < n; i++) { arr[i] = scanner.nextInt(); if (first[arr[i]] == -1) { first[arr[i]] = i; cnt++; } last[arr[i]] = i; } int best = 0; int len = 0; int cur = 0; int prev = -1; while(cur <= n) { if (first[cur] == -1) {cur++;continue;} if (prev == -1) { prev = cur; cur++; len++; } else { if (first[cur] > last[prev]) { len++; prev =cur; cur++; } else { best = Math.max(best, len); len = 1; prev = cur; cur++; } } } best = Math.max(best, len); out.println(cnt-best); } out.flush(); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(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 readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n7\n3 1 6 6 3 1 1\n8\n1 1 4 4 4 7 8 8\n7\n4 2 5 2 6 2 7"]
2 seconds
["2\n0\n1"]
NoteIn the first query, you can move all $$$1$$$-elements to the beginning (after that sequence turn into $$$[1, 1, 1, 3, 6, 6, 3]$$$) and then move all $$$6$$$-elements to the end.In the second query, the sequence is sorted initially, so the answer is zero.In the third query, you have to move all $$$2$$$-elements to the beginning.
Java 8
standard input
[ "dp", "two pointers" ]
326dcf837da6909b3f62db16f2800812
The first line contains one integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — the number of the queries. Each query is represented by two consecutive lines. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of elements. The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le n$$$) — the elements. It is guaranteed that the sum of all $$$n$$$ does not exceed $$$3 \cdot 10^5$$$.
2,000
For each query print one integer — the minimum number of operation for sorting sequence $$$a$$$ in non-descending order.
standard output
PASSED
ed12f7d4a52bfed6129bfa425a331736
train_004.jsonl
1570374300
You are given a sequence $$$a_1, a_2, \dots, a_n$$$, consisting of integers.You can apply the following operation to this sequence: choose some integer $$$x$$$ and move all elements equal to $$$x$$$ either to the beginning, or to the end of $$$a$$$. Note that you have to move all these elements in one direction in one operation.For example, if $$$a = [2, 1, 3, 1, 1, 3, 2]$$$, you can get the following sequences in one operation (for convenience, denote elements equal to $$$x$$$ as $$$x$$$-elements): $$$[1, 1, 1, 2, 3, 3, 2]$$$ if you move all $$$1$$$-elements to the beginning; $$$[2, 3, 3, 2, 1, 1, 1]$$$ if you move all $$$1$$$-elements to the end; $$$[2, 2, 1, 3, 1, 1, 3]$$$ if you move all $$$2$$$-elements to the beginning; $$$[1, 3, 1, 1, 3, 2, 2]$$$ if you move all $$$2$$$-elements to the end; $$$[3, 3, 2, 1, 1, 1, 2]$$$ if you move all $$$3$$$-elements to the beginning; $$$[2, 1, 1, 1, 2, 3, 3]$$$ if you move all $$$3$$$-elements to the end; You have to determine the minimum number of such operations so that the sequence $$$a$$$ becomes sorted in non-descending order. Non-descending order means that for all $$$i$$$ from $$$2$$$ to $$$n$$$, the condition $$$a_{i-1} \le a_i$$$ is satisfied.Note that you have to answer $$$q$$$ independent queries.
256 megabytes
/** * @author derrick20 */ import java.io.*; import java.util.*; public class SequenceSorting { public static void main(String args[]) throws Exception { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int Q = sc.nextInt(); int c = 1; while (Q-->0) { int N = sc.nextInt(); int[] arr = new int[N]; int[] lo = new int[N + 1]; int[] hi = new int[N + 1]; Arrays.fill(lo, -1); Arrays.fill(hi, N + 1); HashSet<Integer> nums = new HashSet<>(); for (int i = 0; i < arr.length; i++) { arr[i] = sc.nextInt(); nums.add(arr[i]); if (lo[arr[i]] == -1) { lo[arr[i]] = i; } hi[arr[i]] = i; } // if (c == 165) { // out.println(9); // out.println(N); // for (int val : arr) { // out.println(val); // } // } // Two-pointers, checking the start value and seeing how many // internal intervals can be clustered in the correct order int maxCluster = 1; int right = 2; int last = 1; // the thing right before the right int currCluster = 1; for (int left = 1; left <= N; left++) { if (lo[left] == -1) continue; // int last = left; if (right <= left) { right = left + 1; } last = right - 1; sweep: while (right <= N) { if (lo[right] == -1) { right++; } else if (hi[last] < lo[right]) { last = right; // Update the last thing of the interval right++; currCluster++; // We expanded } else { break sweep; } } if (currCluster > maxCluster) { maxCluster = currCluster; } currCluster = Math.max(currCluster - 1, 1); // Since we are dropping the leftmost value after // sweeping forward } int needMoving = nums.size() - maxCluster; out.println(needMoving); c++; } out.close(); } static class FastScanner { public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double cnt = 1; BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public long nextLong() { cnt=1; boolean neg = false; if(c==NC)c=getChar(); for(;(c<'0' || c>'9'); c = getChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=getChar()) { res = (res<<3)+(res<<1)+c-'0'; cnt*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/cnt; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=getChar(); while(c>32) { res.append(c); c=getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=getChar(); while(c!='\n') { res.append(c); c=getChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=getChar(); if(c==NC)return false; else if(c>32)return true; } } } }
Java
["3\n7\n3 1 6 6 3 1 1\n8\n1 1 4 4 4 7 8 8\n7\n4 2 5 2 6 2 7"]
2 seconds
["2\n0\n1"]
NoteIn the first query, you can move all $$$1$$$-elements to the beginning (after that sequence turn into $$$[1, 1, 1, 3, 6, 6, 3]$$$) and then move all $$$6$$$-elements to the end.In the second query, the sequence is sorted initially, so the answer is zero.In the third query, you have to move all $$$2$$$-elements to the beginning.
Java 8
standard input
[ "dp", "two pointers" ]
326dcf837da6909b3f62db16f2800812
The first line contains one integer $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — the number of the queries. Each query is represented by two consecutive lines. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the number of elements. The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le n$$$) — the elements. It is guaranteed that the sum of all $$$n$$$ does not exceed $$$3 \cdot 10^5$$$.
2,000
For each query print one integer — the minimum number of operation for sorting sequence $$$a$$$ in non-descending order.
standard output
PASSED
29cb5c71c3214295d9c70f9c6cc063a4
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
import java.io.IOException; import java.util.Arrays; import java.util.Scanner; public class Portals { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int t = sc.nextInt(); int[] x = new int[n]; int s=0; x[0]=0; for (int i=1; i<n;i++){ x[i]= sc.nextInt(); } int j=1; while(true){ if (j==t){ System.out.println("YES"); break; }else if (j>t){ System.out.println("NO"); break; } j=x[j]+j; } } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
e16a2afa03fa6c1332c74ef4ea324eb6
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
import java.util.Scanner; /** * New Year is coming in Line World! In this world, there are n cells numbered * by integers from 1 to n, as a 1 × n board. People live in cells. However, it * was hard to move between distinct cells, because of the difficulty of * escaping the cell. People wanted to meet people who live in other cells. * * So, user tncks0121 has made a transportation system to move between these * cells, to celebrate the New Year. First, he thought of n - 1 positive * integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the * condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by * integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and * cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th * portal. Unfortunately, one cannot use the portal backwards, which means one * cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to * see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World * using portals. * * Currently, I am standing at cell 1, and I want to go to cell t. However, I * don't know whether it is possible to go there. Please determine whether I can * go to cell t by only using the construted transportation system. * * Input * The first line contains two space-separated integers n * (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of * the cell which I want to go to. * * The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 * (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation * system, one cannot leave the Line World. * * Output * If I can go to cell t using the transportation system, print "YES". * Otherwise, print "NO". * * Sample test(s) * input * 8 4 * 1 2 1 2 1 2 1 * output * YES * input * 8 5 * 1 2 1 2 1 1 1 * output * NO * Note * In the first sample, the visited cells are: 1, 2, 4; so we can * successfully visit the cell 4. * * In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so * we can't visit the cell 5, which we want to visit. * * @Title: A500NewYearTransportation.java * @author lxh * @date Aug 25, 2015 1:06:28 PM * */ public class Main { public static void main(String []args){ Scanner cin=new Scanner(System.in); int n=cin.nextInt(); int t=cin.nextInt(); int now=1; boolean flag=false; for(int i=1;i<n;i++){ int val=cin.nextInt(); if(t==now)flag=true; if(i==now)now+=val; } if(t==now)flag=true; if(flag)System.out.println("YES"); else System.out.println("NO"); } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
1bfd32676969010fdbf337911483b161
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class a_NewYearTransportation { public static void main(String[] args) { // TODO Auto-generated method stub int n, t, a, c = 1; ArrayList<Integer> arr = new ArrayList<Integer>(); Scanner x = new Scanner(System.in); n = x.nextInt(); t = x.nextInt(); arr.add(0); for (int i = 1; i < n; i++) { a = x.nextInt(); arr.add(a); } for (int j = 1; j <= n;) { if (c < t) { c += arr.get(j); j = c; } else break; if (t == c) { System.out.println("YES"); return; } } System.out.println("NO"); } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
77304ae22eddc1dc3afebfbaf8b4c3c8
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
import java.util.Scanner; /** * Created by NKumar2 on 8/13/2015. */ public class A500 { public static void main(String[] args) { A500 obj = new A500(); obj.init(); } private void init() { String ans = "NO"; boolean flag = true; Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int t = scn.nextInt(); int[] ts = new int[n]; for(int i=0;i<n-1;i++) ts[i] = scn.nextInt(); int i=1; while(flag) { int nval = i+ts[i-1]; if(nval == t) { ans="YES"; flag = false; //break; } else if(nval <= t) { i=nval; } else flag = false; } System.out.println(ans); } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
5f2fa41c980269d429893e3b4df92b77
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
import java.util.*; public class CF500A_NewYearTransportation { public static void main(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt() - 1; int[] a = new int[n]; a[n-1] = 0; boolean ans = (m == 0); for(int i = 0; i < n - 1; i ++)a[i] = in.nextInt(); int at = 0; while(at < n - 1){ at += a[at]; if(at == m){ ans = true; break; } if(at > m)break; } System.out.println(ans ? "YES" : "NO"); in.close(); } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
b437007efa88365ed7f28bc2bfc2c915
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
import java.util.Scanner; public class Problem500A { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int wall = scan.nextInt(); int target = scan.nextInt(); int[] arr = new int[wall]; for(int i=1; i<wall; i++) { arr[i] = scan.nextInt(); } boolean isOK = false; for(int i=1; i<target+1; i++) { if(i+arr[i] == target) { isOK = true; break; } else i = (i+arr[i]-1); } if(isOK) System.out.println("YES"); else System.out.println("NO"); } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
7e18879f877e69607fce53b748ea1c26
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
import java.util.Scanner; public class NewYearTransportation { public static void main(String[]args){ Scanner scan= new Scanner(System.in); int cant= scan.nextInt(); int obj=scan.nextInt(); int over=0; boolean resu=false; if (obj==cant) resu=true; for(int i=1 ; i<cant && !resu ;i++) if(i==obj && over==0) resu=true; else{ //System.out.println("over = "+over+"i="+i); if(over==0) over=scan.nextInt(); else{ scan.nextInt(); } over--; } if(resu) System.out.println("YES"); else System.out.println("NO"); } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
5dfb792309ddb207ff61e9705fb97dae
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; /* int n = sc.nextInt(); // read input as integer long k = sc.nextLong(); // read input as long double d = sc.nextDouble(); // read input as double String str = sc.next(); // read input as String String s = sc.nextLine(); // read whole line as String */ public class Main { public static PrintWriter out; public static void main(String args[]) { MyScanner in = new MyScanner(); int n = in.nextInt(); int t = in.nextInt(); int[] array = new int[n]; for(int i=1;i<n;i++) array[i] = in.nextInt(); boolean[] visited = new boolean[n+1]; visited[1] = true; int i =1; while(i<=n-1){ int index = array[i]+i; if(index>n) break; visited[index] = true; i = index; } if(visited[t]==true) System.out.println("YES"); else System.out.println("NO"); } 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; } } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
a3a04235c2b7590300eae4a4903134d9
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; /** * Created by sreenidhisreesha on 12/30/14. */ public class NYT { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input = null; String line1, line2 = ""; line1 = br.readLine(); line2 = br.readLine(); StringTokenizer st = new StringTokenizer(line1); int n = Integer.parseInt(st.nextToken()); int index = Integer.parseInt((st.nextToken())); st = new StringTokenizer(line2); ArrayList<Integer> list = new ArrayList<Integer>(); list.add(0); while(st.hasMoreTokens()) { list.add(Integer.parseInt(st.nextToken())); } int currentPosition = 1; while(true) { int nextPosition = currentPosition + list.get(currentPosition); if ( nextPosition == index) { System.out.println("YES"); return; } else if(nextPosition > index) { System.out.println("NO"); return; } currentPosition = nextPosition; } } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
18e0a9910152c8f7ec658213a9c70725
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
import java.util.*; public class goodbyeA { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a,b; int arr[]; a = sc.nextInt(); b = sc.nextInt(); arr = new int[a]; for(int i=0;i<a-1;i++){ arr[i] = sc.nextInt(); } int index =0; int j=0; int current = 1; while(current<a){ // System.out.println("hafhds "+current); current += arr[current-1]; if(current == b){ System.out.println("YES"); j++; break; } } if(j==0){ System.out.println("NO"); } } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
c02be21c5d0b39e698bf87724cba823a
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
//Omar brome, lcpc practice, codeforces: *newYearTransportation //basic code for fast java input/output learned from kattis import java.util.*; import java.io.*; public class Main{ public static void main(String[] args){ Kattio tuna= new Kattio(System.in,System.out); int n=tuna.getInt(); int t=tuna.getInt(); int[] w= new int[n]; for(int i=1;i<n;i++){ w[i]=tuna.getInt(); } for(int i=1;i<n+1;){ //tuna.println("I:"+i); if(i==t) { tuna.println("YES"); tuna.flush(); return; } if(i>n-1) break; i=i+w[i]; } tuna.println("NO"); tuna.flush(); } } class Kattio extends PrintWriter { public Kattio(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); } public Kattio(InputStream i, OutputStream o) { super(new BufferedOutputStream(o)); r = new BufferedReader(new InputStreamReader(i)); } public boolean hasMoreTokens() { return peekToken() != null; } public int getInt() { return Integer.parseInt(nextToken()); } public double getDouble() { return Double.parseDouble(nextToken()); } public long getLong() { return Long.parseLong(nextToken()); } public String getWord() { return nextToken(); } private BufferedReader r; private String line; private StringTokenizer st; private String token; private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; } private String nextToken() { String ans = peekToken(); token = null; return ans; } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
2676b5fb38cc3c80223b5d42168ac98b
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class Main { static void solve(InputReader reader, OutputWriter writer) throws IOException { // Scanner scan = new Scanner(System.in); String a = reader.readLine(); String[] split = a.split(" "); int x = Integer.parseInt(split[0]); int y = Integer.parseInt(split[1]); String s = reader.readLine(); String[] splitter = s.split(" "); int[] array = new int[x]; for (int i = 0; i < x; ++i) { if (i < x - 1) { array[i] = Integer.parseInt(splitter[i]); } } boolean check = false; int count = 0; int index = 0; for (int i = index; i < x - 1; ++i) { count = index + 1 + array[index]; // writer.println(count + " " + index); if (count == y) { check = true; break; } else if (count > y) { break; } else { //count -= (i + 1); //writer.println(count); index = (count - 1); //writer.println(count); } } if (check) writer.println("YES"); else writer.println("NO"); } public static void main(String[] args) throws Exception { InputReader reader = new InputReader(System.in); OutputWriter writer = new OutputWriter(System.out); try { solve(reader, writer); } catch (Exception e) { e.printStackTrace(System.out); } finally { writer.close(); } } } class InputReader extends BufferedReader { public InputReader(InputStream in) { super(new InputStreamReader(in)); } } class OutputWriter extends PrintWriter { public OutputWriter(PrintStream out) { super(new BufferedWriter(new OutputStreamWriter(out))); } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
5a257c244f300945c5e640b227e5a9fa
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class cf500A { static PrintWriter out; public static void main(String[] args) throws IOException { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(), m = sc.nextInt(); int cells [] = new int[n+1]; for(int i = 1; i < n; i ++) cells[i] = sc.nextInt(); out.println(hasReached(1, m, n, cells)?"YES":"NO"); out.close(); } static boolean hasReached(int cell, int target, int cellWall, int [] cells){ cell = cell + cells[cell]; if(cell==target)return true; if(cell>=cellWall)return false; return hasReached(cell, target, cellWall, cells); } 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; } } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
71d7ce09725b4839a4735d7ae3affb33
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class RoundGoodBY_A_New_Year_Transportation { public static void main(String[] args) { Scanner x = new Scanner(System.in); int n = x.nextInt(), t = x.nextInt(), c = 1; ArrayList<Integer> list = new ArrayList<Integer>(n); list.add(0); for (int i = 1; i < n; i++) { list.add(x.nextInt()); } for (int i = 1; i <= n;) { if (c < t) { c += list.get(i); i = c; } else break; if (c == t) { System.out.println("YES"); return; } } System.out.println("NO"); } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
05aad0d1ec8deb832fff14d749e3ca41
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
import java.util.Scanner; public class NewYearTransportation500A { public static void main(String[] args) { int cellNum, cellInd, i; String output="", cellMaster[], cell[]; Scanner sc = new Scanner(System.in); cellMaster = (sc.nextLine().trim()).split(" "); cellNum = Integer.parseInt(cellMaster[0]); cellInd = Integer.parseInt(cellMaster[1]); cell = (sc.nextLine().trim()).split(" "); for(i=1; i <= cellNum;) { //System.out.println("loop start : "+i); if(i == cellInd) { output = "YES"; break; } else { output = "NO"; if(i < cellNum) i += Integer.parseInt(cell[i-1]); else break; } } System.out.println(output); } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
e682a826db1b4e40baf96f3a538a9d88
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Ideone { public static void main (String[] args) throws java.lang.Exception { Scanner s=new Scanner(System.in); int n=s.nextInt();int k=s.nextInt(); int a[]=new int[n-1]; for(int i=0;i<n-1;i++) a[i]=s.nextInt(); int q=1; // your code goes here while(q<k) { q+=a[q-1]; } if(q==k) System.out.println("YES"); else System.out.println("NO"); } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
ab2f22552c3539d1a43f7e8cbb4a6802
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { public static void main(String arg[]) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA task = new TaskA(); task.solve(in, out); out.close(); } } class InputReader { private BufferedReader br; private StringTokenizer st; public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in), 32768); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } class TaskA { public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); int t = in.nextInt() - 1; int a[] = new int[n]; for (int i = 0; i < n - 1; i++) { a[i] = in.nextInt(); } boolean isInPath[] = new boolean[n]; isInPath[t] = true; for (int i = t - 1; i >= 0; i--) { if (isInPath[i + a[i]]) { isInPath[i] = true; } } out.println(isInPath[0] ? "YES" : "NO"); } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
365a82a5a02a16742f6e8acedc385d81
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
//package Codeforces.GoodBye2014_Div2A.Code1; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /* * some cheeky quote */ public class Main { FastScanner in; PrintWriter out; public void solve() throws IOException { int n = in.nextInt(); int target = in.nextInt(); int a[] = new int[n + 1]; for (int i = 1; i < a.length - 1; i++) { a[i] = in.nextInt(); } int current = 1; while (true) { int next = a[current] + current; if (next > target || next >= a.length) { System.out.println("NO"); return; } else { if (next == target) { System.out.println("YES"); return; } } current = next; } } public void run() { try { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() { 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()); } } public static void main(String[] arg) { new Main().run(); } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
ea0deea3faa67aa686f6ae0efc301d60
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class Transportation { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String brr[]=br.readLine().trim().split(" "); int n=Integer.parseInt(brr[0]); int t=Integer.parseInt(brr[1]); int arr[]=new int[n]; brr=br.readLine().trim().split(" "); int i; for(i=0;i<n-1;i++) { arr[i]=Integer.parseInt(brr[i]); } int next; i=1; boolean done=true; while(i<n&&done) { next=arr[i-1]+i; // System.out.println(next); if(next==t) done=false; i=next; } if(!done) System.out.println("YES"); else System.out.println("NO"); } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
231a5e3a4288a98a33d2be1fbc15f1a3
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
import java.util.*; import java.io.*; public class A500 { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line[] = br.readLine().split(" "); int length = Integer.parseInt(line[0]); int dest = Integer.parseInt(line[1]) - 1; int src = 0; line = br.readLine().split(" "); while(src != dest && src != length - 1) src = src + Integer.parseInt(line[src]); if(src == dest) System.out.println("YES"); else System.out.println("NO"); } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
f182a4a0619d2e48ad6f546ef2205baa
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
import java.util.Scanner; public class NewYearTransportation { public static void main(String[] args) { Scanner console =new Scanner(System.in); int n=console.nextInt(); int t=console.nextInt(); int arr[]=new int [n-1]; int i; for(i=0;i<arr.length;i++) arr[i]=console.nextInt(); for(i=0;i<arr.length;) {if(i+1==t||i+arr[i]+1==t) { System.out.println("YES"); break; } else if(i==arr.length-1) { System.out.println("NO"); break; } i=i+arr[i]; } if(i>=arr.length) System.out.println("NO"); } }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output
PASSED
4270286b04ebda47f21652c43726b83d
train_004.jsonl
1419951600
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) throws IOException { Reader.init(System.in); int n = Reader.nextInt(); int t = Reader.nextInt(); int[] arr = new int [n-1]; int i =0; Reader.nextIntArrays(arr); while(true){ if((i+1)==t){ System.out.println("YES");return; } if((i+1)>t){ System.out.println("NO");return; } i = i+arr[i]; } } } class dragons implements Comparable<dragons>{ int power ,bounes; public dragons (int p , int b) { this.power = p ; this.bounes = b ; } @Override public int compareTo(dragons o) { return Integer.compare(this.power, o.power); } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** * call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } /** * get next word */ static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static public void nextIntArrays(int[]... arrays) throws IOException { for (int i = 1; i < arrays.length; ++i) { if (arrays[i].length != arrays[0].length) { throw new InputMismatchException("Lengths are different"); } } for (int i = 0; i < arrays[0].length; ++i) { for (int[] array : arrays) { array[i] = nextInt(); } }} static public void nextLineArrays(String[]... arrays) throws IOException { for (int i = 1; i < arrays.length; ++i) { if (arrays[i].length != arrays[0].length) { throw new InputMismatchException("Lengths are different"); } } for (int i = 0; i < arrays[0].length; ++i) { for (String[] array : arrays) { array[i] = reader.readLine(); } }} }
Java
["8 4\n1 2 1 2 1 2 1", "8 5\n1 2 1 2 1 1 1"]
2 seconds
["YES", "NO"]
NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.
Java 7
standard input
[ "implementation", "dfs and similar", "graphs" ]
9ee3d548f93390db0fc2f72500d9eeb0
The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.
1,000
If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".
standard output