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
9b00f55a5d75a64172fca58d0ea5dd65
train_004.jsonl
1438790400
Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library β€” it's a unique integer from 1 to 106. Thus, the system logs events of two forms: "+ ri" β€” the reader with registration number ri entered the room; "- ri" β€” the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); Scanner s = new Scanner(System.in); int n = Integer.parseInt(f.readLine()); int max = 0, cur = 0; boolean[] in = new boolean[(int)1e6+2]; for(int i = 0; i < n; i++) { String[] split = f.readLine().split("\\s+"); int num = Integer.parseInt(split[1]); switch(split[0]) { case "-": if(!in[num]) { //in before we counted max++; } else { in[num] = false; cur--; max = Math.max(max, cur); } break; case "+": in[num] = true; cur++; max = Math.max(max, cur); break; } } System.out.println(max); } } //every - in not in the set is a cur++;
Java
["6\n+ 12001\n- 12001\n- 1\n- 1200\n+ 1\n+ 7", "2\n- 1\n- 2", "2\n+ 1\n- 1"]
1 second
["3", "2", "1"]
NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.
Java 8
standard input
[ "implementation" ]
6cfd3b0a403212ec68bac1667bce9ef1
The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.
1,300
Print a single integer β€” the minimum possible capacity of the reading room.
standard output
PASSED
0c65cd6d21c03f8f4c8bf5a52fd58eed
train_004.jsonl
1438790400
Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library β€” it's a unique integer from 1 to 106. Thus, the system logs events of two forms: "+ ri" β€” the reader with registration number ri entered the room; "- ri" β€” the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class B_pi { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { // TODO code application logic here BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); ArrayList<Integer>ar=new ArrayList<>(); int main=0; int ayagya=0; for (int i = 0; i < n; i++) { String str=br.readLine(); if(str.startsWith("+")){ ar.add(Integer.parseInt(str.substring(2))); ayagya=Math.max(ayagya,ar.size()); } else{ if(ar.contains(Integer.parseInt(str.substring(2)))){ ar.remove((Integer)Integer.parseInt(str.substring(2))); } else{ ayagya++; } } } System.out.println(ayagya); } }
Java
["6\n+ 12001\n- 12001\n- 1\n- 1200\n+ 1\n+ 7", "2\n- 1\n- 2", "2\n+ 1\n- 1"]
1 second
["3", "2", "1"]
NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.
Java 8
standard input
[ "implementation" ]
6cfd3b0a403212ec68bac1667bce9ef1
The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.
1,300
Print a single integer β€” the minimum possible capacity of the reading room.
standard output
PASSED
c58840db175490a59b48ff29a3f8277c
train_004.jsonl
1438790400
Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library β€” it's a unique integer from 1 to 106. Thus, the system logs events of two forms: "+ ri" β€” the reader with registration number ri entered the room; "- ri" β€” the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.
256 megabytes
import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * Created by yuu on 10/4/17. */ public class Problem567B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); Set<Integer> set = new HashSet<>(); int[] people = new int[n+1]; for (int i = 1; i <= n; i++) { String s = sc.next(); int person = sc.nextInt(); people[i] = people[i-1]; if (s.equals("+")) { people[i]++; set.add(person); } else { if (set.contains(person)) { set.remove(person); people[i]--; } else { for (int j = 0; j < i; j++) { people[j]++; } } } } int max = 0; for (int j = 0; j <= n; j++) { if (max < people[j]) max = people[j]; } System.out.println(max); } }
Java
["6\n+ 12001\n- 12001\n- 1\n- 1200\n+ 1\n+ 7", "2\n- 1\n- 2", "2\n+ 1\n- 1"]
1 second
["3", "2", "1"]
NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.
Java 8
standard input
[ "implementation" ]
6cfd3b0a403212ec68bac1667bce9ef1
The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.
1,300
Print a single integer β€” the minimum possible capacity of the reading room.
standard output
PASSED
771c666a6854a1987ec53de8aaef80a7
train_004.jsonl
1438790400
Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library β€” it's a unique integer from 1 to 106. Thus, the system logs events of two forms: "+ ri" β€” the reader with registration number ri entered the room; "- ri" β€” the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Egor Kulikov (egor@egork.net) */ 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(); } static class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int now = 0; int[] guys = new int[1_000_000]; int[] gone = new int[n]; int[] guysHere = new int[n]; for (int i = 0; i < n; i++) { char action = in.readCharacter(); int guy = in.readInt() - 1; if (guys[guy] == 0 && action == '-') { gone[i]++; } else { if (action == '+') { guys[guy]++; now++; } else { guys[guy]--; now--; } guysHere[i] = now; } } int goneTotal = 0; for (int i = n - 1; i >= 0; i--) { goneTotal += gone[i]; guysHere[i] += goneTotal; } out.print(ArrayUtils.maxElement(guysHere)); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.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 boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } 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 interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } 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 close() { writer.close(); } public void print(int i) { writer.print(i); } } static class ArrayUtils { public static int maxElement(int[] array) { return maxElement(array, 0, array.length); } public static int maxElement(int[] array, int from, int to) { int result = Integer.MIN_VALUE; for (int i = from; i < to; i++) result = Math.max(result, array[i]); return result; } } }
Java
["6\n+ 12001\n- 12001\n- 1\n- 1200\n+ 1\n+ 7", "2\n- 1\n- 2", "2\n+ 1\n- 1"]
1 second
["3", "2", "1"]
NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.
Java 8
standard input
[ "implementation" ]
6cfd3b0a403212ec68bac1667bce9ef1
The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.
1,300
Print a single integer β€” the minimum possible capacity of the reading room.
standard output
PASSED
a152cb2a8868c9d2c0694da926c9a72a
train_004.jsonl
1438790400
Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library β€” it's a unique integer from 1 to 106. Thus, the system logs events of two forms: "+ ri" β€” the reader with registration number ri entered the room; "- ri" β€” the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.Set; import java.util.InputMismatchException; import java.io.IOException; import java.util.Deque; import java.util.HashSet; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.ArrayDeque; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Egor Kulikov (egor@egork.net) */ 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(); } static class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); Deque<Integer> queue = new ArrayDeque<>(n); Set<String> was = new HashSet<>(n); for (int i = 0; i < n; i++) { if (in.readCharacter() == '+') { queue.add(+1); was.add(in.next()); } else { queue.add(-1); if (!was.contains(in.next())) queue.addFirst(+1); } } int max = 0; int cur = 0; while (!queue.isEmpty()) max = Math.max(max, cur += queue.poll()); out.print(max); } } 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 close() { writer.close(); } public void print(int i) { writer.print(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.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 { if (Character.isValidCodePoint(c)) 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 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); } } }
Java
["6\n+ 12001\n- 12001\n- 1\n- 1200\n+ 1\n+ 7", "2\n- 1\n- 2", "2\n+ 1\n- 1"]
1 second
["3", "2", "1"]
NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.
Java 8
standard input
[ "implementation" ]
6cfd3b0a403212ec68bac1667bce9ef1
The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.
1,300
Print a single integer β€” the minimum possible capacity of the reading room.
standard output
PASSED
1353c8245fe0d761dc2d7572faa186cf
train_004.jsonl
1438790400
Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library β€” it's a unique integer from 1 to 106. Thus, the system logs events of two forms: "+ ri" β€” the reader with registration number ri entered the room; "- ri" β€” the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.Set; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Queue; import java.util.LinkedList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Egor Kulikov (egor@egork.net) */ 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(); } static class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); Queue<String[]> q = new LinkedList<>(); List<String[]> queries = new ArrayList<>(n); Set<String> was = new HashSet<>(n); for (int i = 0; i < n; i++) { String[] query = in.readLine().split(" "); queries.add(query); String command = query[0]; String guy = query[1]; if (command.equals("+")) was.add(guy); else if (!was.contains(guy)) q.add(new String[]{"+", guy}); } int capacity = 0; q.addAll(queries); Set<String> guysNow = new HashSet<>(); for (String[] query : q) if (query[0].equals("+")) { guysNow.add(query[1]); capacity = Math.max(capacity, guysNow.size()); } else { guysNow.remove(query[1]); } out.print(capacity); // int capacity = 0; // int n = in.readInt(); // Set<Integer> guys = new HashSet<>(n); // for (int i = 0; i < n; i++) { // char type = in.readCharacter(); // int guy = in.readInt(); // // switch (type) { // case '+': // guys.add(guy); // capacity = Math.max(capacity, guys.size()); // break; // // case '-': // if (!guys.remove(guy)) capacity++; // } // } // out.print(capacity); } } 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 close() { writer.close(); } public void print(int i) { writer.print(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.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 boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) s = readLine0(); return s; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["6\n+ 12001\n- 12001\n- 1\n- 1200\n+ 1\n+ 7", "2\n- 1\n- 2", "2\n+ 1\n- 1"]
1 second
["3", "2", "1"]
NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.
Java 8
standard input
[ "implementation" ]
6cfd3b0a403212ec68bac1667bce9ef1
The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.
1,300
Print a single integer β€” the minimum possible capacity of the reading room.
standard output
PASSED
81bf008ad403f1c2654ef7ad13335696
train_004.jsonl
1438790400
Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library β€” it's a unique integer from 1 to 106. Thus, the system logs events of two forms: "+ ri" β€” the reader with registration number ri entered the room; "- ri" β€” the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.Set; import java.util.InputMismatchException; import java.io.IOException; import java.util.HashSet; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Egor Kulikov (egor@egork.net) */ 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(); } static class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int capacity = 0; int n = in.readInt(); Set<Integer> guys = new HashSet<>(n); for (int i = 0; i < n; i++) { char type = in.readCharacter(); int guy = in.readInt(); switch (type) { case '+': guys.add(guy); capacity = Math.max(capacity, guys.size()); break; case '-': if (!guys.remove(guy)) capacity++; } } out.print(capacity); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.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 boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } 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 interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } 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 close() { writer.close(); } public void print(int i) { writer.print(i); } } }
Java
["6\n+ 12001\n- 12001\n- 1\n- 1200\n+ 1\n+ 7", "2\n- 1\n- 2", "2\n+ 1\n- 1"]
1 second
["3", "2", "1"]
NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.
Java 8
standard input
[ "implementation" ]
6cfd3b0a403212ec68bac1667bce9ef1
The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.
1,300
Print a single integer β€” the minimum possible capacity of the reading room.
standard output
PASSED
19d824a546b7eef441a027c8616a16b0
train_004.jsonl
1438790400
Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library β€” it's a unique integer from 1 to 106. Thus, the system logs events of two forms: "+ ri" β€” the reader with registration number ri entered the room; "- ri" β€” the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class p2 { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); int n = in.nextInt(); boolean[] ch = new boolean[1000010]; int res = 0, cur = 0; for (int i = 0; i < n; i++) { String str = in.next(); int m = in.nextInt(); if (str.charAt(0) == '+') { cur++; ch[m] = true; } else { if (ch[m]) { cur--; } else { res++; } ch[m] = false; } res = Math.max(res, cur); } out.println(res); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public boolean hasMoreElements() { while (tokenizer == null || !tokenizer.hasMoreElements()) { String s; try { s = reader.readLine(); } catch (IOException e) { return false; } tokenizer = new StringTokenizer(s); } return tokenizer.hasMoreElements(); } } }
Java
["6\n+ 12001\n- 12001\n- 1\n- 1200\n+ 1\n+ 7", "2\n- 1\n- 2", "2\n+ 1\n- 1"]
1 second
["3", "2", "1"]
NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.
Java 8
standard input
[ "implementation" ]
6cfd3b0a403212ec68bac1667bce9ef1
The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.
1,300
Print a single integer β€” the minimum possible capacity of the reading room.
standard output
PASSED
2b14c6dfc74b1d0f79a03121068411ed
train_004.jsonl
1438790400
Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library β€” it's a unique integer from 1 to 106. Thus, the system logs events of two forms: "+ ri" β€” the reader with registration number ri entered the room; "- ri" β€” the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //package contest_15_8_5; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; /** * * @author Niloo */ public class B { B(){ Scanner scan = new Scanner(System.in); String n = scan.nextLine(); // ArrayList<Boolean> al = new ArrayList<>(); boolean [] al=new boolean[1000001]; int now=0, max=0; Arrays.fill(al, false); for(int i=0;i<Integer.parseInt(n);i++){ String s = scan.nextLine(); if(s.substring(0, 1).equals("-")){ if(al[Integer.parseInt(s.substring(2))]==false) max++; if(al[Integer.parseInt(s.substring(2))]==true){ now--; al[Integer.parseInt(s.substring(2))]=false; } } if(s.substring(0, 1).equals("+")){ now++; al[Integer.parseInt(s.substring(2))]=true; if(now>max) max=now; } } System.out.println(max); } public static void main(String args[]){ new B(); } }
Java
["6\n+ 12001\n- 12001\n- 1\n- 1200\n+ 1\n+ 7", "2\n- 1\n- 2", "2\n+ 1\n- 1"]
1 second
["3", "2", "1"]
NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.
Java 8
standard input
[ "implementation" ]
6cfd3b0a403212ec68bac1667bce9ef1
The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.
1,300
Print a single integer β€” the minimum possible capacity of the reading room.
standard output
PASSED
21ddc98543ddfb63f1d8d682d7ca62da
train_004.jsonl
1438790400
Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library β€” it's a unique integer from 1 to 106. Thus, the system logs events of two forms: "+ ri" β€” the reader with registration number ri entered the room; "- ri" β€” the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { InputReader sc = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); Random gen = new Random(); int test = 1;//sc.nextInt(); while(test-->0) { int n = sc.nextInt(); int max = Integer.MIN_VALUE; HashSet<Integer> set = new HashSet<>(); while(n-->0) { int extra = 0; char c = sc.readString().charAt(0); int id = sc.nextInt(); if(c=='+') { set.add(id); } else { if(set.contains(id)) { set.remove(id); } else { extra =1; } } max = Math.max(set.size(), max); max = max + extra; } pw.println(max); } pw.close(); } 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 static int[] shuffle(int[] a, Random gen) { for(int i = 0, n = a.length;i < n;i++) { int ind = gen.nextInt(n-i)+i; int d = a[i]; a[i] = a[ind]; a[ind] = d; } 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
["6\n+ 12001\n- 12001\n- 1\n- 1200\n+ 1\n+ 7", "2\n- 1\n- 2", "2\n+ 1\n- 1"]
1 second
["3", "2", "1"]
NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.
Java 8
standard input
[ "implementation" ]
6cfd3b0a403212ec68bac1667bce9ef1
The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.
1,300
Print a single integer β€” the minimum possible capacity of the reading room.
standard output
PASSED
c885baca9fc983a230b15c2597ec23ec
train_004.jsonl
1438790400
Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library β€” it's a unique integer from 1 to 106. Thus, the system logs events of two forms: "+ ri" β€” the reader with registration number ri entered the room; "- ri" β€” the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.
256 megabytes
//package c314; import java.util.Scanner; public class q2_2 { public static void main(String args[]) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int max=0; int count=0; int a[]=new int[1000001]; s.nextLine(); for(int i=0;i<n;i++) { String sign=s.nextLine(); String b[]=sign.split(" "); int num=Integer.parseInt(b[1]); if(b[0].equals("+")) { count++; a[num]=1; } else { if(a[num]==0) { max++; a[num]=-1; } else { count--; a[num]=-1; } } max=Math.max(max, count); } System.out.println(max); } }
Java
["6\n+ 12001\n- 12001\n- 1\n- 1200\n+ 1\n+ 7", "2\n- 1\n- 2", "2\n+ 1\n- 1"]
1 second
["3", "2", "1"]
NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.
Java 8
standard input
[ "implementation" ]
6cfd3b0a403212ec68bac1667bce9ef1
The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.
1,300
Print a single integer β€” the minimum possible capacity of the reading room.
standard output
PASSED
0598ae424722915c8022c0608c5959db
train_004.jsonl
1438790400
Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library β€” it's a unique integer from 1 to 106. Thus, the system logs events of two forms: "+ ri" β€” the reader with registration number ri entered the room; "- ri" β€” the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.
256 megabytes
import java.io.*; import java.util.*; import java.nio.charset.StandardCharsets; // import java.math.BigInteger; // remember to check if n=0, n=1 are special cases public class B { static Writer wr; public static void main(String[] args) throws Exception { // long startTime = System.nanoTime(); // String testString = ""; // InputStream stream = new ByteArrayInputStream(testString.getBytes(StandardCharsets.UTF_8)); // Reader in = new Reader(stream); Reader in = new Reader(); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); wr = new Writer(); /* Precomputation */ // long elapsedTime = System.nanoTime() - startTime; // double seconds = (double)elapsedTime / 1000000000.0; // wr.writeRedLn(seconds); /* Input */ int N = in.nextInt(); boolean[] was_already_inside = new boolean[1000000+1]; boolean[] arrived = new boolean[1000000+1]; int[] count = new int[N+1]; for(int i=0;i<N;i++) { char ch = in.nextChar(); int id = in.nextInt(); if(ch=='+') { arrived[id] = true; count[i+1]++; } else { if(!arrived[id]) { count[0]++; } count[i+1]--; arrived[id] = false; } } int max = 0; for(int i=0;i<=N;i++) { if(i>0) { count[i] += count[i-1]; } max = Math.max(max, count[i]); } // wr.writeRedLn(Arrays.toString(count)); out.write(max + "\n"); out.flush(); } } class Writer { public void writeRedLn(Object x) { writeRedLn(x+""); } public void writeBlueLn(Object x) { writeBlueLn(x+""); } public void writeGreenLn(Object x) { writeGreenLn(x+""); } public void writePinkLn(Object x) { writePinkLn(x+""); } public void writeRedLn(String x) { System.out.println((char)27 + "[31m" + (char)27 + "[40m" + x + (char)27 + "[0m"); } public void writeBlueLn(String x) { System.out.println((char)27 + "[34m" + (char)27 + "[3m" + x + (char)27 + "[0m"); } public void writeGreenLn(String x) { System.out.println((char)27 + "[32m" + (char)27 + "[3m" + x + (char)27 + "[0m"); } public void writePinkLn(String x) { System.out.println((char)27 + "[30m" + (char)27 + "[45m" + x + (char)27 + "[0m"); } public void writeRed(String x) { System.out.print((char)27 + "[31m" + (char)27 + "[40m" + x + (char)27 + "[0m"); } public void writeBlue(String x) { System.out.print((char)27 + "[34m" + (char)27 + "[3m" + x + (char)27 + "[0m"); } public void writeGreen(String x) { System.out.print((char)27 + "[32m" + (char)27 + "[3m" + x + (char)27 + "[0m"); } public void writePink(String x) { System.out.print((char)27 + "[30m" + (char)27 + "[45m" + x + (char)27 + "[0m"); } } class Reader { final private int BUFFER_SIZE = 1 << 16;private DataInputStream din;private byte[] buffer;private int bufferPointer, bytesRead; public Reader(){din=new DataInputStream(System.in);buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0;} public Reader(InputStream stream){din=new DataInputStream(stream);buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0;} public String readLine()throws IOException{byte[] buf=new byte[1024];int cnt=0,c; while((c=read())!=-1){if(c=='\n')break;buf[cnt++]=(byte)c;}return new String(buf,0,cnt);} public char nextChar()throws IOException{byte c=read();while(c<=' ')c=read();return (char)c;} public int nextInt()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 long nextLong()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 double nextDouble()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 void fillBuffer()throws IOException{bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE);if(bytesRead==-1)buffer[0]=-1;} private byte read()throws IOException{if(bufferPointer==bytesRead)fillBuffer();return buffer[bufferPointer++];} public void close()throws IOException{if(din==null) return;din.close();} }
Java
["6\n+ 12001\n- 12001\n- 1\n- 1200\n+ 1\n+ 7", "2\n- 1\n- 2", "2\n+ 1\n- 1"]
1 second
["3", "2", "1"]
NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.
Java 8
standard input
[ "implementation" ]
6cfd3b0a403212ec68bac1667bce9ef1
The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.
1,300
Print a single integer β€” the minimum possible capacity of the reading room.
standard output
PASSED
74d18afa80d6a1c751dd86ef94882c31
train_004.jsonl
1438790400
Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library β€” it's a unique integer from 1 to 106. Thus, the system logs events of two forms: "+ ri" β€” the reader with registration number ri entered the room; "- ri" β€” the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; public class PiB { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(bf.readLine()); String[] l; boolean[] whereHere = new boolean[1000001]; int max = 0, curr; int here = 0; for (int i = 0; i < n; i++) { l = bf.readLine().split(" "); curr = Integer.parseInt(l[1]); if (l[0].charAt(0) == '+') { whereHere[curr] = true; here++; max = Math.max(here, max); } else { if (!whereHere[curr]) max++; else { here--; whereHere[curr] = false; } } } System.out.println(max); } }
Java
["6\n+ 12001\n- 12001\n- 1\n- 1200\n+ 1\n+ 7", "2\n- 1\n- 2", "2\n+ 1\n- 1"]
1 second
["3", "2", "1"]
NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.
Java 8
standard input
[ "implementation" ]
6cfd3b0a403212ec68bac1667bce9ef1
The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.
1,300
Print a single integer β€” the minimum possible capacity of the reading room.
standard output
PASSED
17f20070c7ae9a90fbbe6685b71b86ba
train_004.jsonl
1438790400
Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library β€” it's a unique integer from 1 to 106. Thus, the system logs events of two forms: "+ ri" β€” the reader with registration number ri entered the room; "- ri" β€” the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.
256 megabytes
/* * Code Author: Akshay Miterani * DA-IICT */ import java.io.*; import java.util.*; public class Contest { static final int mod=(int)1e9+7; public static void main(String args[]){ InputReader in = new InputReader(System.in); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); //----------My Code Starts Here---------- int n=in.nextInt(); int ans=0; HashSet<Integer> h=new HashSet<Integer>(); for(int i=0;i<n;i++){ String c=in.nextLine(); int next=Integer.parseInt(c.substring(2)); if(c.charAt(0)=='-'){ if(h.contains(next)){ h.remove(next); } else{ ans++; } } else{ h.add(next); } ans=Math.max(ans, h.size()); } System.out.println(ans); out.close(); //---------------The End------------------ } static class Pair implements Comparable<Pair>{ int i,c,p; Pair(int ii,int cc){ i=ii;c=cc; } @Override public int compareTo(Pair o) { return -Integer.compare(this.i, o.i); } } 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 nextInt() { return Integer.parseInt(next()); } } }
Java
["6\n+ 12001\n- 12001\n- 1\n- 1200\n+ 1\n+ 7", "2\n- 1\n- 2", "2\n+ 1\n- 1"]
1 second
["3", "2", "1"]
NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.
Java 8
standard input
[ "implementation" ]
6cfd3b0a403212ec68bac1667bce9ef1
The first line contains a positive integer n (1 ≀ n ≀ 100) β€” the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.
1,300
Print a single integer β€” the minimum possible capacity of the reading room.
standard output
PASSED
601b91e82fe7f750e7765eeca7f41f61
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.io.*; import java.util.*; public class D { static StringBuilder st = new StringBuilder(); public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt() , a [] = new int [n]; for(int i = 0 ; i < n ;i++) a[i] = sc.nextInt(); int m = sc.nextInt() , b [] = new int[m]; for(int i = 0 ; i < m ;i++) b[i] = sc.nextInt(); long [] sumA = new long [n + 1] , sumB = new long [m + 1]; for(int i = 1 ; i <= n ;i++) sumA[i] = sumA[i - 1] + a[i - 1]*1l; for(int i = 1 ; i <= m ;i++) sumB[i] = sumB[i - 1] + b[i - 1]*1l; if(sumA[n] != sumB[m]) { System.out.println(-1); return ; } int len = -1 ; for(int i = 0 , j = 0 ; i <= n && j <= m ; len++ , i++ , j++) { while(sumA[i] != sumB[j]) { if(sumA[i] < sumB[j]) i++; else j++; } } out.println(len); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws Exception {return Integer.parseInt(next());} public long nextLong() throws Exception {return Long.parseLong(next());} public double nextDouble() throws Exception{return Double.parseDouble(next());} } static void shuffle(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } private static boolean oj = System.getProperty("ONLINE_JUDGE") != null; private static void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
19ca1a680b4df15abdc1d5f05a58654f
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
/* package codechef; // 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 Codechef { public static void main (String[] args) throws java.lang.Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); for(int q=0; q<1; q++) { int n =Integer.parseInt(br.readLine()); long[] arr1 = new long[n]; StringTokenizer st = new StringTokenizer(br.readLine()); arr1[0] = Long.parseLong(st.nextToken()); for(int i=1; i<n; i++) { arr1[i] = Long.parseLong(st.nextToken()) + arr1[i-1]; //System.out.println(arr1[i]); } int m = Integer.parseInt(br.readLine()); long[] arr2 = new long[m]; st = new StringTokenizer(br.readLine()); arr2[0] = Long.parseLong(st.nextToken()); for(int i=1; i<m; i++) { arr2[i] = Long.parseLong(st.nextToken()) + arr2[i-1]; } int i = 0, j = 0, count=0; while (i < n && j < m) { //System.out.println(arr1[i]+" "+arr2[j]+" "+count); if (arr1[i] < arr2[j]) i++; else if (arr2[j] < arr1[i]) j++; else { count++; j++; i++; } } if(arr1[n-1]!=arr2[m-1]) System.out.println("-1"); else System.out.println(count); } } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
0abb3a7419eaaf63068753b4e53eadee
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.BufferedReader; import java.io.Reader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; MyInput in = new MyInput(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, MyInput in, PrintWriter out) { int n = in.nextInt(); long[] a = in.nextLongArray(n); int m = in.nextInt(); long[] b = in.nextLongArray(m); int ans = 0; for (int i = 0, j = 0; i < n || j < m; ans++) { if (i == n || j == m) { out.println(-1); return; } long sa = a[i++], sb = b[j++]; while (sa != sb) { if (sa < sb) { if (i >= n) { out.println(-1); return; } sa += a[i++]; } else { if (j >= m) { out.println(-1); return; } sb += b[j++]; } } if (sa != sb) { out.println(-1); return; } } out.println(ans); } } static class MyInput { private final BufferedReader in; private static int pos; private static int readLen; private static final char[] buffer = new char[1024 * 8]; private static char[] str = new char[500 * 8 * 2]; private static boolean[] isDigit = new boolean[256]; private static boolean[] isSpace = new boolean[256]; private static boolean[] isLineSep = new boolean[256]; static { for (int i = 0; i < 10; i++) { isDigit['0' + i] = true; } isDigit['-'] = true; isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true; isLineSep['\r'] = isLineSep['\n'] = true; } public MyInput(InputStream is) { in = new BufferedReader(new InputStreamReader(is)); } public int read() { if (pos >= readLen) { pos = 0; try { readLen = in.read(buffer); } catch (IOException e) { throw new RuntimeException(); } if (readLen <= 0) { throw new MyInput.EndOfFileRuntimeException(); } } return buffer[pos++]; } public int nextInt() { int len = 0; str[len++] = nextChar(); len = reads(len, isSpace); int i = 0; int ret = 0; if (str[0] == '-') { i = 1; } for (; i < len; i++) ret = ret * 10 + str[i] - '0'; if (str[0] == '-') { ret = -ret; } return ret; } public long nextLong() { int len = 0; str[len++] = nextChar(); len = reads(len, isSpace); int i = 0; long ret = 0; if (str[0] == '-') { i = 1; } for (; i < len; i++) ret = ret * 10 + str[i] - '0'; if (str[0] == '-') { ret = -ret; } return ret; } public char nextChar() { while (true) { final int c = read(); if (!isSpace[c]) { return (char) c; } } } int reads(int len, boolean[] accept) { try { while (true) { final int c = read(); if (accept[c]) { break; } if (str.length == len) { char[] rep = new char[str.length * 3 / 2]; System.arraycopy(str, 0, rep, 0, str.length); str = rep; } str[len++] = (char) c; } } catch (MyInput.EndOfFileRuntimeException e) { } return len; } public long[] nextLongArray(final int n) { final long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = nextLong(); } return res; } static class EndOfFileRuntimeException extends RuntimeException { } } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
dceb9f5386be32d689eb2e578f029cad
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.util.*; import java.io.*; public class Solution { Scanner sc = new Scanner(System.in); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); public void run() throws Exception { int a = Integer.parseInt(in.readLine()); int []A = new int[a]; String []temp1 = in.readLine().split(" "); for(int i=0;i<a;i++) A[i] = Integer.parseInt(temp1[i]); int b = Integer.parseInt(in.readLine()); String []temp2 = in.readLine().split(" "); int []B = new int[b]; for(int i=0;i<b;i++) B[i] = Integer.parseInt(temp2[i]); int len = 0; long sa = 0; long sb = 0; int i=0; int j=0; while(i<=a && j<=b) { //printf("%d %d %I64d %I64d\n", i, j, sa, sb); if(sa!=0 && sa==sb) { len++; sa=0; sb=0; } if(sa < sb) { if(i==a) break; sa += A[i]; i++; }else { if(j==b) break; sb += B[j]; j++; } } if(!(sa==0 && sb==0)) { len = -1; } if(!(i==a && j==b)) len=-1; System.out.println(len); } public static void main(String []args) throws Exception { new Solution().run(); } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
3fb43af2582d0fd1f5abb6e2857d1dbf
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Test1 { PrintWriter pw = new PrintWriter(System.out); void run(){ int a = ni(), b, la=1, lb=1, o=0; long sum1=0, sum2=0,s1=0,s2=0; boolean ans=true; int[] m1 = new int[a]; for(int q=0; q<a; q++) { m1[q] = ni(); s1+=m1[q]; } b = ni(); int[] m2 = new int[b]; for(int q=0; q<b; q++){ m2[q] = ni(); s2+=m2[q]; } sum1 = m1[0]; sum2 = m2[0]; if(s1!=s2) pw.print(-1); else{ for(; la<a || lb<b;){ if(sum1==sum2){ o++; } if(sum1<sum2) sum1+=m1[la++]; else sum2+=m2[lb++]; } pw.print(o+1); } pw.flush(); } public static void main(String[] z){ new Test1().run(); } InputStream is = System.in; 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 String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(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 char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); 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 * 10 + (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(); } } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
89d567683431c51a3e92b901d4aa527e
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class VasyaandArrays { public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); int nA =sc.nextInt(); int A[]=new int[nA]; for(int i=0;i<nA;i++) A[i]=sc.nextInt(); int nB =sc.nextInt(); int B[]=new int[nB]; for(int i=0;i<nB;i++) B[i]=sc.nextInt(); int Aptr=0; //points at a last no. used int Bptr=0; long Atemp=A[0]; long Btemp=B[0]; int size=0; int s=-1; while(Aptr<nA && Bptr <nB) { // System.out.println(Atemp+" "+Btemp); if(Atemp==Btemp) { Aptr++; Bptr++; if(Aptr<nA && Bptr<nB) { Atemp=A[Aptr]; Btemp=B[Bptr]; size++; continue; } if(Aptr<nA || Bptr<nB) { break; } if(Aptr==nA && Bptr==nB) { size++; s=size; break; } } else if(Atemp>Btemp) { Bptr++; if(Bptr==nB) break; Btemp+=B[Bptr]; continue; } else if(Atemp<Btemp) { Aptr++; if(Aptr==nA) break; Atemp+=A[Aptr]; } } System.out.println(s); } static class Scanner { StringTokenizer st; BufferedReader br; 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());} } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
82519cd8833d639ecaa2a78a410801ca
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; import static java.lang.Math.abs; import static java.lang.Math.min; import static java.lang.Math.max; import static java.lang.Math.sqrt; @SuppressWarnings("unchecked") public class P1036D { public void run() throws Exception { long sa = 0, sb = 0; int n = nextInt(), a [] = readInt(n), m = nextInt(), b [] = readInt(m), k = 0, i = 0, j = 0; while ((i < n) || (j < m)) { if ((sa == 0) && (i < n) && (j < m)) { sa = a[i++]; sb = b[j++]; } else { if (i == n) { sb += b[j++]; } else if (j == m) { sa += a[i++]; } else { if (sa < sb) { sa += a[i++]; } else { sb += b[j++]; } } } if (sa == sb) { sa = sb = 0; k++; } } println((sa == sb) ? k : -1); } public static void main(String... args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedOutputStream(System.out)); new P1036D().run(); br.close(); pw.close(); System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]"); } static long startTime = System.currentTimeMillis(); static BufferedReader br; static PrintWriter pw; StringTokenizer stok; String nextToken() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.nextToken(); } void print(byte b) { print("" + b); } void print(int i) { print("" + i); } void print(long l) { print("" + l); } void print(double d) { print("" + d); } void print(char c) { print("" + c); } void print(Object o) { if (o instanceof int[]) { print(Arrays.toString((int [])o)); } else if (o instanceof long[]) { print(Arrays.toString((long [])o)); } else if (o instanceof char[]) { print(Arrays.toString((char [])o)); } else if (o instanceof byte[]) { print(Arrays.toString((byte [])o)); } else if (o instanceof short[]) { print(Arrays.toString((short [])o)); } else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o)); } else if (o instanceof float[]) { print(Arrays.toString((float [])o)); } else if (o instanceof double[]) { print(Arrays.toString((double [])o)); } else if (o instanceof Object[]) { print(Arrays.toString((Object [])o)); } else { print("" + o); } } void print(String s) { pw.print(s); } void println() { println(""); } void println(byte b) { println("" + b); } void println(int i) { println("" + i); } void println(long l) { println("" + l); } void println(double d) { println("" + d); } void println(char c) { println("" + c); } void println(Object o) { print(o); println(); } void println(String s) { pw.println(s); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return (char) (br.read()); } String next() throws IOException { return nextToken(); } String nextLine() throws IOException { return br.readLine(); } int [] readInt(int size) throws IOException { int [] array = new int [size]; for (int i = 0; i < size; i++) { array[i] = nextInt(); } return array; } long [] readLong(int size) throws IOException { long [] array = new long [size]; for (int i = 0; i < size; i++) { array[i] = nextLong(); } return array; } double [] readDouble(int size) throws IOException { double [] array = new double [size]; for (int i = 0; i < size; i++) { array[i] = nextDouble(); } return array; } String [] readLines(int size) throws IOException { String [] array = new String [size]; for (int i = 0; i < size; i++) { array[i] = nextLine(); } return array; } int gcd(int a, int b) { if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a); a = Math.abs(a); b = Math.abs(b); int az = Integer.numberOfTrailingZeros(a), bz = Integer.numberOfTrailingZeros(b); a >>>= az; b >>>= bz; while (a != b) { if (a > b) { a -= b; a >>>= Integer.numberOfTrailingZeros(a); } else { b -= a; b >>>= Integer.numberOfTrailingZeros(b); } } return (a << Math.min(az, bz)); } long gcd(long a, long b) { if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a); a = Math.abs(a); b = Math.abs(b); int az = Long.numberOfTrailingZeros(a), bz = Long.numberOfTrailingZeros(b); a >>>= az; b >>>= bz; while (a != b) { if (a > b) { a -= b; a >>>= Long.numberOfTrailingZeros(a); } else { b -= a; b >>>= Long.numberOfTrailingZeros(b); } } return (a << Math.min(az, bz)); } void shuffle(int [] a) { Random r = new Random(); for (int i = a.length - 1; i >= 0; i--) { int j = r.nextInt(a.length); int t = a[i]; a[i] = a[j]; a[j] = t; } } void shuffle(long [] a) { Random r = new Random(); for (int i = a.length - 1; i >= 0; i--) { int j = r.nextInt(a.length); long t = a[i]; a[i] = a[j]; a[j] = t; } } void shuffle(Object [] a) { Random r = new Random(); for (int i = a.length - 1; i >= 0; i--) { int j = r.nextInt(a.length); Object t = a[i]; a[i] = a[j]; a[j] = t; } } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
2b3b942c8c6696accd62e147ffdfe805
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.util.*; import java.io.*; public class MyClass { public static void main(String args[]) { MyScanner sc=new MyScanner(); int n=sc.nextInt(); int a[]=new int [n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); int m=sc.nextInt(); int b[]=new int [m]; for(int j=0;j<m;j++) b[j]=sc.nextInt(); long sa=0; long sb =0; for(int i=0;i<n;i++) sa=sa+a[i]; for(int j=0;j<m;j++) sb=sb+b[j]; if(sa!=sb) System.out.println(-1); else { int len=0; int i=0; int j=0; long csa=0; long csb=0; while(i<n&&j<m) { if(csa<csb) csa=csa+a[i]; else if(csb<csa) csb=csb+b[j]; else { csa=a[i]; csb=b[j]; } if(csa==csb) { len++; i++; j++; } else if(csa<csb) { i++; } else j++; } System.out.println(len); } } 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
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
caf47090a2e277cc5f6ff2e2aff4ed91
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Codechef { static PrintWriter out=new PrintWriter(System.out);static FastScanner in = new FastScanner(System.in);static class FastScanner {BufferedReader br;StringTokenizer stok;FastScanner(InputStream is) {br = new BufferedReader(new InputStreamReader(is));} String next() throws IOException {while (stok == null || !stok.hasMoreTokens()) {String s = br.readLine();if (s == null) {return null;} stok = new StringTokenizer(s);}return stok.nextToken();} int ni() throws IOException {return Integer.parseInt(next());}long nl() throws IOException {return Long.parseLong(next());}double nd() throws IOException {return Double.parseDouble(next());}char nc() throws IOException {return (char) (br.read());}String ns() throws IOException {return br.readLine();} int[] nia(int n) throws IOException{int a[] = new int[n];for (int i = 0; i < n; i++)a[i] = ni();return a;}long[] nla(int n) throws IOException {long a[] = new long[n];for (int i = 0; i < n; i++)a[i] = nl();return a;} double[] nda(int n)throws IOException {double a[] = new double[n];for (int i = 0; i < n; i++)a[i] = nd();return a;}int [][] imat(int n,int m) throws IOException{int mat[][]=new int[n][m];for(int i=0;i<n;i++){for(int j=0;j<m;j++)mat[i][j]=ni();}return mat;} } static long mod=Long.MAX_VALUE; public static void main (String[] args) throws java.lang.Exception { int i,j; HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>(); /* if(hm.containsKey(z)) hm.put(z,hm.get(z)+1); else hm.put(z,1); */ ArrayList<Integer> arr=new ArrayList<Integer>(); HashSet<Integer> set=new HashSet<Integer>(); PriorityQueue<Integer> pq=new PriorityQueue<Integer>(); int n=in.ni(); long a[]=in.nla(n); int m=in.ni(); long b[]=in.nla(m); long sum1=0,sum2=0; for(long c:a) sum1+=c; for(long c:b) sum2+=c; if(sum1!=sum2) {System.out.println(-1);return ;} i=0;j=0;int ans=0; long temp1=0,temp2=0; while(i!=n || j!=m) { if(temp1>=temp2 && j!=m) {temp2+=b[j];j++;} else if(temp1<temp2) {temp1+=a[i];i++;} //System.out.println(i+" "+j); //System.out.println(temp1+ " ** "+temp2); if(temp1==temp2 && temp1!=0) { ans++; temp1=temp2=0; } } out.println(ans); out.close(); } static class pair implements Comparable<pair>{ int x, y; public pair(int x, int y){this.x = x; this.y = y;} @Override public int compareTo(pair arg0) { if(x<arg0.x) return -1; else if(x==arg0.x) { if(y<arg0.y) return -1; else if(y>arg0.y) return 1; else return 0; } else return 1; } } static long gcd(long a,long b) { if(b==0) return a; return gcd(b,a%b); } static long exponent(long a,long n) { long ans=1; while(n!=0) { if(n%2==1) ans=(ans*a)%mod; a=(a*a)%mod; n=n>>1; } return ans; } static int binarySearch(int a[], int item, int low, int high) { if (high <= low) return (item > a[low])? (low + 1): low; int mid = (low + high)/2; if(item == a[mid]) return mid+1; if(item > a[mid]) return binarySearch(a, item, mid+1, high); return binarySearch(a, item, low, mid-1); } static 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++; } } static 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 void sort(int a[]) {Sort(a,0,a.length-1);} }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
927317c4dbb1239e1765caa5bd2f5162
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Harshal Khodifad */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); // out.println("hi"); long a[] = new long[n]; long sa = 0; long sb = 0; // StringTokenizer st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { a[i] = in.nextLong(); // a[i] = i; sa += a[i]; } int m = in.nextInt(); long b[] = new long[m]; for (int i = 0; i < m; i++) { b[i] = in.nextLong(); // b[i] = m-i-1; sb += b[i]; } if (sa != sb) { out.println(-1); return; } long count = 0; int i = 0, j = 0; sa = a[i]; sb = b[j]; while (true) { if (sa == sb) { count++; if (i < n - 1 && j < m - 1) { sa = a[++i]; sb = b[++j]; continue; } else break; } else { if (sa > sb) { sb += b[++j]; } else { sa += a[++i]; } } } out.println(count); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.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 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 boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
59ef00bd776b4854ae5fccbfa12c1713
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.util.*; import java.io.*; // Solution public class Main { public static void main (String[] argv) //throws IOException { new Main(); } boolean test = false; public Main() { FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in))); //FastReader in = new FastReader(new BufferedReader(new FileReader("Main.in"))); int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); int m = in.nextInt(); int[] b = new int[m]; for (int i = 0; i < m; i++) b[i] = in.nextInt(); int len = 0; int i = 0, j = 0; long sa = 0, sb = 0; for (; i < n || j < m; ) { if (sa == 0 && sb == 0) { sa += a[i++]; sb += b[j++]; }else { if (sa < sb) { if (i < n)sa += a[i++]; else {System.out.println(-1); return; } } else if (sa > sb) { if (j < m) sb += b[j++]; else {System.out.println(-1); return; } } } if (sa == sb) { ++len; sa = 0; sb = 0; if (i == n && j == m) break; if (i == n || j == m) { System.out.println(-1); return; } } } if (sa != sb) len = -1; System.out.println(len); } private int nBit1(int v) { int v0 = v; int c = 0; while (v != 0) { ++c; v = v & (v - 1); } return c; } private int common(int v) { int c = 0; while (v != 1) { v = (v >>> 1); ++c; } return c; } private void reverse(char[] a, int i, int j) { while (i < j) { swap(a, i++, j--); } } private void swap(char[] a, int i, int j) { char t = a[i]; a[i] = a[j]; a[j] = t; } private long gcd(long x, long y) { if (y == 0) return x; return gcd(y, x % y); } private int max(int a, int b) { return a > b ? a : b; } private int min(int a, int b) { return a > b ? b : a; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader(BufferedReader in) { br = in; } String next() { while (st == null || !st.hasMoreElements()) { try { String line = br.readLine(); if (line == null || line.length() == 0) return ""; st = new StringTokenizer(line); } catch (IOException e) { return ""; //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) { return ""; //e.printStackTrace(); } return str; } } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
d3d9c5d34365779b459f9968a127dac8
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.io.*; import java.util.*; public class GFG { public static void main (String[] args) { Scanner sc=new Scanner(System.in); Queue<Long> q1=new LinkedList<>(); Queue<Long> q2=new LinkedList<>(); int n=sc.nextInt(),flag=0; for(int i=0;i<n;i++) q1.add(new Long(sc.next())); int m=sc.nextInt(); for(int i=0;i<m;i++) q2.add(new Long(sc.next())); int count=0; Long v1=q1.remove(),v2=q2.remove(); while(q1.size()>0&&q2.size()>0){ if(v1>v2){ if( q2.size()>0) v2+=q2.remove(); } else if(v2>v1){ if(q1.size()>0) v1+=q1.remove(); } else { count++; if(q1.size()>0) v1=q1.remove(); if(q2.size()>0) v2=q2.remove(); } } while(q1.size()!=0) v1+=q1.remove(); while(q2.size()!=0) v2+=q2.remove(); if(v1.equals(v2)) count++; else flag=1; if(flag==0) System.out.println(count); else System.out.println(-1); } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
86da9f55727204a7b510c27eb25406e9
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.io.*; import java.util.*; public class GFG { public static void main (String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); Long[] a=new Long[n]; Long v1=0L,v2=0L; for(int i=0;i<n;i++) {a[i]=new Long(sc.next()); v1+=a[i]; } int m=sc.nextInt(); Long[] b=new Long[m]; for(int i=0;i<m;i++) {b[i]=new Long(sc.next()); v2+=b[i];} if(v1.equals(v2)){ int count=0; int i=0,j=0; v1=new Long(a[i]); v2=new Long(b[j]); while(i<n&&j<m){ if(v1.equals(v2)) { count++; i++; j++; if(i<n&&j<m) {v1=new Long(a[i]); v2=new Long(b[j]);} } else if(v1>v2){ j++; if(j<m) v2+=b[j]; } else{ i++; if(i<n) v1+=a[i];} } System.out.println(count); } else System.out.println(-1); // System.out.println(v1+" "+v2); } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
b8e6d3c27442dc1c0a9d8c2e597bdac8
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { Reader in = new Reader(); int n = in.nextInt(); int[] a = in.na(n); int m = in.nextInt(); int[] b = in.na(m); int i = 0, j = 0; boolean ok = true; int ans = 0; while((i<n||j<m)&&ok) { long suma=i<n?a[i]:0; long sumb=j<m?b[j]:0; ans++; while(suma!=sumb&&i<n&&j<m) { if(suma>sumb) sumb+=++j<m?b[j]:0; else suma+=++i<n?a[i]:0; } if(suma!=sumb) ok = false; i++; j++; } System.out.println(ok?ans:-1); } static class Reader { static BufferedReader br; static StringTokenizer st; public Reader() { this.br = new BufferedReader(new InputStreamReader(System.in)); } public int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public String[] nS(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) a[i] = next(); return a; } public int nextInt() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Integer.parseInt(st.nextToken()); } public double nextDouble() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Double.parseDouble(st.nextToken()); } public Long nextLong() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return Long.parseLong(st.nextToken()); } public String next() { if (st == null || !st.hasMoreTokens()) try { readLine(); } catch (Exception e) { } return st.nextToken(); } public static void readLine() { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { } } } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
8e4239023f183bd1e1980811416bdbe8
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.awt.List; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.InputMismatchException; import java.util.Locale; import java.util.TimeZone; public class D { public static void main(String[] args) { Locale.setDefault(Locale.US); InputStream inputstream = System.in; OutputStream outputstream = System.out; FastReader in = new FastReader(inputstream); PrintWriter out = new PrintWriter(outputstream); TaskA solver = new TaskA(); // int testcase = in.ni(); for (int i = 0; i < 1; i++) solver.solve(i, in, out); out.close(); } } class TaskA { public void solve(int testnumber, FastReader in, PrintWriter out) { int n = in.ni(); int a[] = in.iArr(n); int m = in.ni(); int b[] = in.iArr(m); long sa = 0, sb = 0; for (int i = 0; i < a.length; i++) { sa += a[i]; } for (int i = 0; i < b.length; i++) { sb += b[i]; } if (sa != sb) { System.out.println(-1); return; } int ia = 0, ib = 0, len = 0; sa = 0; sb = 0; while (ia < a.length || ib < b.length) { if (sa <= sb) sa += a[ia++]; else sb += b[ib++]; if (sa == sb) len++; } System.out.println(len); } } class FastReader { public InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public FastReader() { } 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 ni() { 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 ns() { 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 static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] iArr(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public String next() { return ns(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
cefcbe3cd3e19390ade1173bf0cd8015
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Contest9_2_2019 { public static void main(String[] args) throws IOException { InputStreamReader me = new InputStreamReader(System.in) ; BufferedReader br=new BufferedReader(me); String[] s= br.readLine().split(" "); long n = Long.parseLong(s[0]); s= br.readLine().split(" "); long[] a = new long[(int)n] ; long sum= 0; for (int i = 0; i < n; i++) { a[i]=Long.parseLong(s[i]); sum+=a[i] ; } boolean k = false ; s= br.readLine().split(" "); long m = Long.parseLong(s[0]); long[] b = new long[(int)m] ; s= br.readLine().split(" "); for (int i = 0; i < m; i++) { b[i]=Long.parseLong(s[i]); sum-=b[i] ; } if(sum==0){ k=true ; } if(k){ int posa=0,posb=0 ; int res =0; long suma =0;long sumb=0 ; while( posb<m && posa<n ){ res++ ; suma=a[posa++] ; sumb=b[posb++] ; while(suma!=sumb ){ if(suma<sumb){ suma +=a[posa++] ; }else{ sumb+=b[posb++] ; } } } System.out.println(res ); }else System.out.println(-1); } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
a99f6eef9dc2a56dcda5d0453fc48a05
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { PrintWriter writer = new PrintWriter(System.out); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Scanner scanner = new Scanner(System.in); // long a = scanner.nextLong() * 2 + 1; // long b = scanner.nextLong(); // // long ans = (long) Math.ceil((double) b / ((double) a / 2)); // System.out.println(ans % 2 == 0 ? ans + 1 : ans); // int n = scanner.nextInt(); // // while(n-- > 0) { // long a = scanner.nextLong(), b = scanner.nextLong(), k = scanner.nextLong(); // // if(k > Math.max(a, b)) // System.out.println(-1); // else { // // } // } int a = scanner.nextInt(); long[] arr1 = new long[a]; for(int i = 0;i < a;i++) arr1[i] = scanner.nextInt(); int b = scanner.nextInt(); long[] arr2 = new long[b]; for(int i = 0;i < b;i++) arr2[i] = scanner.nextInt(); int ans = 0; long curA = 0, curB = 0; int i = 0, j = 0; while(i < a && j < b) { // System.out.println(curA + " " + curB); if(curA != 0 && curB != 0) { if(curA < curB) { curA+=arr1[i]; if(curA == curB) { j++; i++; ans++; curA = 0; curB = 0; } else if(curA > curB) { j++; } else i++; } else { curB+=arr2[j]; if(curA == curB) { j++; i++; ans++; curA = 0; curB = 0; } else if(curB > curA) { i++; } else j++; } } else if(arr1[i] == arr2[j]) { ans++; i++; j++; } else { curA = arr1[i]; curB = arr2[j]; if(arr1[i] > arr2[j]) j++; else i++; } } if(i == a && j == b) System.out.println(ans); else System.out.println(-1); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(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 boolean ready() throws IOException {return br.ready();} } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
c3ec5d31b9d04db191ad17ee0ef4c36d
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); int[] A = new int[N]; for (int i = 0; i < N; i++) { A[i] = in.nextInt(); } int M = in.nextInt(); int[] B = new int[M]; for (int i = 0; i < M; i++) { B[i] = in.nextInt(); } long curSumA = A[0]; long curSumB = B[0]; int curIndexA = 0; int curIndexB = 0; int res = 0; while (curIndexA < N && curIndexB < M) { if (curSumA == curSumB) { res++; curIndexA++; curIndexB++; if (curIndexA < N) { curSumA = A[curIndexA]; } if (curIndexB < M) { curSumB = B[curIndexB]; } } else if (curSumA < curSumB) { curIndexA++; if (curIndexA < N) { curSumA += A[curIndexA]; } } else { curIndexB++; if (curIndexB < M) { curSumB += B[curIndexB]; } } } if (curIndexA == N && curIndexB == M) { out.println(res); } else { out.println(-1); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
a81b6775817dcadf3cb69c4a45606a7a
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.util.Scanner; public class VaasyaArray { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long[] arr1 = new long[n]; for (int p = 0; p < n; p++){ arr1[p] = sc.nextInt(); } int m = sc.nextInt(); long[] arr2 = new long[m]; for (int p = 0; p < m; p++){ arr2[p] = sc.nextInt(); } int ind1 = 0; int ind2 = 0; boolean foundsol = true; int size; try { while (ind1 < n && ind2 < m) { if (arr1[ind1] == arr2[ind2]) { ind1++; ind2++; } else { int nowind1 = ind1 + 1; int nowind2 = ind2 + 1; while (arr1[ind1] != arr2[ind2]) { if (arr1[ind1] < arr2[ind2]) { arr1[ind1] += arr1[nowind1]; arr1[nowind1] = 0; nowind1++; } else { arr2[ind2] += arr2[nowind2]; arr2[nowind2] = 0; nowind2++; } } ind1 = nowind1; ind2 = nowind2; } } size = 0; for (int i = 0; i < n; i++) { if (arr1[i] != 0) { size++; } } if (ind1 < n || ind2 < m){ size = -1; } }catch (ArrayIndexOutOfBoundsException e){ size = -1; } System.out.println(size); } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
e88012624a708cd93bca397a5db0ef6e
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
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 { BufferedReader bi = new BufferedReader(new InputStreamReader(System.in)); int size_of_first_array = Integer.parseInt(bi.readLine()); int[] firstArray = new int[size_of_first_array]; String line = bi.readLine(); int i = 0; for (String numStr : line.split("\\s")) { firstArray[i] = Integer.parseInt(numStr); i++; } int size_of_second_array = Integer.parseInt(bi.readLine()); int[] secondArray = new int[size_of_second_array]; line = bi.readLine(); i = 0; for (String numStr : line.split("\\s")) { secondArray[i] = Integer.parseInt(numStr); i++; } int length = 0; long firstValue = 0L; long secondValue = 0L; int firstIndex = 0, secondIndex = 0; boolean first = true; while (firstIndex + secondIndex < firstArray.length + secondArray.length) { if (first) { if (firstIndex >= firstArray.length) { System.out.println(-1); return; } firstValue += firstArray[firstIndex]; firstIndex++; } else { if (secondIndex >= secondArray.length) { System.out.println(-1); return; } secondValue += secondArray[secondIndex]; secondIndex ++; } if (firstValue > secondValue) { first = false; } else if (firstValue < secondValue) { first = true; } else { firstValue = 0; secondValue = 0; length++; if (firstIndex < firstArray.length) { first = true; } else { first = false; } } } if (firstValue == secondValue && secondIndex == secondArray.length && firstIndex == firstArray.length) { if (firstValue > 0) { length ++; } System.out.println(length); } else { System.out.println(-1); } } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
416468129aba8b9ab667d27b93cb2cb8
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.io.*; import java.util.*; public class Main implements Runnable { int maxn = (int)3e5+111; long inf = (long)1e18; long n,m,k; int a[] = new int[maxn]; int b[] = new int[maxn]; void solve() throws Exception { int n = in.nextInt(); for (int i=1; i<=n; i++) { a[i] = in.nextInt(); } int m = in.nextInt(); for (int i=1; i<=m; i++) { b[i] = in.nextInt(); } int left = 1; int right = 1; long sumA = -1; long sumB = -1; int cnt = 0; while (left<=n && right<=m) { if (sumA==sumB) { if (sumA!=-1) { cnt++; } sumA = 0; sumB = 0; sumA+=a[left]; sumB+=b[right]; left++; right++; } else if (sumA<sumB) { sumA+=a[left]; left++; } else { sumB+=b[right]; right++; } } while (left<=n) { sumA+=a[left]; left++; } while (right<=m) { sumB+=b[right]; right++; } if (sumA==sumB) { cnt++; out.println(cnt); } else { out.println(-1); } } public class Pair { int x; int y; public Pair (int x, int t) { this.x = x; this.y = y; } } String fileInName = ""; boolean file = false; boolean isAcmp = false; static Throwable throwable; public static void main (String [] args) throws Throwable { Thread thread = new Thread(null, new Main(), "", (1 << 26)); thread.start(); thread.join(); thread.run(); if (throwable != null) throw throwable; } FastReader in; PrintWriter out; public void run() { String fileIn = "absum.in"; String fileOut = "absum.out"; try { if (isAcmp) { if (file) { in = new FastReader(new BufferedReader(new FileReader(fileIn))); out = new PrintWriter (fileOut); } else { in = new FastReader(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); } } else if (file) { in = new FastReader(new BufferedReader(new FileReader(fileInName+".in"))); out = new PrintWriter (fileInName + ".out"); } else { in = new FastReader(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); } solve(); } catch(Exception e) { throwable = e; } finally { out.close(); } } } class FastReader { BufferedReader bf; StringTokenizer tk = null; public FastReader(BufferedReader bf) { this.bf = bf; } public Integer nextInt() throws Exception { return Integer.parseInt(nextToken()); } public Long nextLong() throws Exception { return Long.parseLong(nextToken()); } public Double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } public String nextToken () throws Exception { if (tk==null || !tk.hasMoreTokens()) { tk = new StringTokenizer(bf.readLine()); } if (!tk.hasMoreTokens()) return nextToken(); else return tk.nextToken(); } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
b83ad99b544fa71c84798e25a87920d0
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { private static Reader in; private static PrintWriter out; static class Reader { private BufferedReader br; private StringTokenizer token; protected Reader(FileReader obj) { br = new BufferedReader(obj, 32768); token = null; } protected Reader() { br = new BufferedReader(new InputStreamReader(System.in), 32768); token = null; } protected String next() { while(token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(br.readLine()); } catch (Exception e) {e.printStackTrace();} } return token.nextToken(); } protected int nextInt() {return Integer.parseInt(next());} protected long nextLong() {return Long.parseLong(next());} protected double nextDouble() {return Double.parseDouble(next());} } public static void main(String[] args) throws IOException { // in = new Reader(new FileReader("C:\\Users\\Suhaib\\Desktop\\input.txt")); // out = new PrintWriter(new FileWriter("C:\\Users\\Suhaib\\Desktop\\output.txt")); in = new Reader(); out = new PrintWriter(System.out); long suma=0, sumb=0; int n = in.nextInt(); long[] a = new long[n]; for (int i=0; i<n; i++) {a[i] = in.nextLong(); suma += a[i];} int m = in.nextInt(); long[] b = new long[m]; for (int i=0; i<m; i++) {b[i] = in.nextLong(); sumb += b[i];} if (suma != sumb) out.printf("%d\n", -1); else { int i=0, j=0, ans = 0; while (true) { if (i == n || j == m) break; long lsuma = a[i], lsumb = b[j]; int i1 = i+1, j1 = j+1; while (i1 < n && j1 < m) { if (lsuma == lsumb) break; else if (lsuma < lsumb) { lsuma += a[i1]; i1++; } else { lsumb += b[j1]; j1++; } } ans++; i = i1; j = j1; } out.printf("%d\n", ans); } out.close(); } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
9d0d85cd4a57d55e4a091d871b24f723
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import static java.lang.Math.*; public class Main { private static Reader in; private static PrintWriter out; static class Reader { private BufferedReader br; private StringTokenizer token; protected Reader(FileReader obj) { br = new BufferedReader(obj, 32768); token = null; } protected Reader() { br = new BufferedReader(new InputStreamReader(System.in), 32768); token = null; } protected String next() { while(token == null || !token.hasMoreTokens()) { try { token = new StringTokenizer(br.readLine()); } catch (Exception e) {e.printStackTrace();} } return token.nextToken(); } protected int nextInt() {return Integer.parseInt(next());} protected long nextLong() {return Long.parseLong(next());} protected double nextDouble() {return Double.parseDouble(next());} } public static void main(String[] args) throws IOException { // in = new Reader(new FileReader("C:\\Users\\Suhaib\\Desktop\\input.txt")); // out = new PrintWriter(new FileWriter("C:\\Users\\Suhaib\\Desktop\\output.txt")); in = new Reader(); out = new PrintWriter(System.out); long suma=0, sumb=0; int n = in.nextInt(); long[] a = new long[n]; for (int i=0; i<n; i++) {a[i] = in.nextLong(); suma += a[i];} int m = in.nextInt(); long[] b = new long[m]; for (int i=0; i<m; i++) {b[i] = in.nextLong(); sumb += b[i];} if (suma != sumb) out.println(-1); else { int i=0, j=0, ans = 0; while (true) { if (i == n || j == m) break; long lsuma = a[i], lsumb = b[j]; int i1 = i+1, j1 = j+1; while (i1 < n && j1 < m) { if (lsuma == lsumb) break; else if (lsuma < lsumb) { lsuma += a[i1]; i1++; } else { lsumb += b[j1]; j1++; } } ans++; i = i1; j = j1; } out.println(ans); } out.close(); } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
a47cebf0d8353fd5e02d0ed18002bbcd
train_004.jsonl
1536330900
Vasya has two arrays $$$A$$$ and $$$B$$$ of lengths $$$n$$$ and $$$m$$$, respectively.He can perform the following operation arbitrary number of times (possibly zero): he takes some consecutive subsegment of the array and replaces it with a single element, equal to the sum of all elements on this subsegment. For example, from the array $$$[1, 10, 100, 1000, 10000]$$$ Vasya can obtain array $$$[1, 1110, 10000]$$$, and from array $$$[1, 2, 3]$$$ Vasya can obtain array $$$[6]$$$.Two arrays $$$A$$$ and $$$B$$$ are considered equal if and only if they have the same length and for each valid $$$i$$$ $$$A_i = B_i$$$.Vasya wants to perform some of these operations on array $$$A$$$, some on array $$$B$$$, in such a way that arrays $$$A$$$ and $$$B$$$ become equal. Moreover, the lengths of the resulting arrays should be maximal possible.Help Vasya to determine the maximum length of the arrays that he can achieve or output that it is impossible to make arrays $$$A$$$ and $$$B$$$ equal.
256 megabytes
import java.io.*; import java.util.*; public class VasyaAndArrays { public static void main(String[] args) { InputReader s = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n = s.nextInt(); long a [] = new long[n]; for (int i = 0; i <n ; i++) { a[i] = s.nextLong(); } int m = s.nextInt(); long b[] = new long [m]; for (int i = 0; i <m ; i++) { b[i] = s.nextLong(); } int l = 0; int r = 0; int c = 0; boolean f =false; while(l<n && r<m){ if(a[l]==b[r]){ c++; l++; r++; } else{ int g = l+1; int h = r+1; long s1 = a[l]; long s2 = b[r]; while(g<n && h<m){ if(s1>s2){ s2+= b[h]; h++; } else if(s2>s1){ s1+=a[g]; g++; } else{ l=g; r=h; break; } } if(s1!=s2){ if(g<n){ while (g<n){ s1 +=a[g]; g++; } } else{ while (h<m){ s2 +=b[h]; h++; } } if(s1!=s2) { f = true; } else{ c++; } l = g; r = h; } else{ c++; l=g; r=h; } } } // w.println(l+" "+r); if(f || (l!=n || r!=m)){ w.println("-1"); } else w.println(c); w.close(); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.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 String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } 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); } }
Java
["5\n11 2 3 5 7\n4\n11 7 3 7", "2\n1 2\n1\n100", "3\n1 2 3\n3\n1 2 3"]
1 second
["3", "-1", "3"]
null
Java 8
standard input
[ "two pointers", "greedy" ]
8c36ab13ca1a4155cf97d0803aba11a3
The first line contains a single integer $$$n~(1 \le n \le 3 \cdot 10^5)$$$ β€” the length of the first array. The second line contains $$$n$$$ integers $$$a_1, a_2, \cdots, a_n~(1 \le a_i \le 10^9)$$$ β€” elements of the array $$$A$$$. The third line contains a single integer $$$m~(1 \le m \le 3 \cdot 10^5)$$$ β€” the length of the second array. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \cdots, b_m~(1 \le b_i \le 10^9)$$$ - elements of the array $$$B$$$.
1,600
Print a single integer β€” the maximum length of the resulting arrays after some operations were performed on arrays $$$A$$$ and $$$B$$$ in such a way that they became equal. If there is no way to make array equal, print "-1".
standard output
PASSED
08c5166d5662010f529bad6854b015c0
train_004.jsonl
1529339700
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties: In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero. When all elements of the array become equal to zero, the array explodes. Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.
256 megabytes
import java.util.*; public class Solution { private static Scanner sc = new Scanner(System.in); public static void main(String[] args) { int n = sc.nextInt(); Set<Integer> set = new HashSet<>(); for (int i = 0; i < n;i++) { int a = sc.nextInt(); if (a == 0) continue; set.add(a); } System.out.println(set.size()); } }
Java
["5\n1 1 1 1 1", "3\n2 0 -1", "4\n5 -6 -5 1"]
1 second
["1", "2", "4"]
NoteIn the first example you can add  - 1 to all non-zero elements in one second and make them equal to zero.In the second example you can add  - 2 on the first second, then the array becomes equal to [0, 0,  - 3]. On the second second you can add 3 to the third (the only non-zero) element.
Java 11
standard input
[ "implementation", "sortings" ]
0593f79604377dcfa98d2b69840ec0a6
The first line contains a single integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains n integers a1, a2, ..., an ( - 105 ≀ ai ≀ 105) β€” the elements of the array.
800
Print a single integer β€” the minimum number of seconds needed to make all elements of the array equal to zero.
standard output
PASSED
75b8ad9d1dfecfb30bf9d80d008c565d
train_004.jsonl
1529339700
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties: In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero. When all elements of the array become equal to zero, the array explodes. Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.
256 megabytes
import java.util.*; public class CP { // This is my first step on becoming a Competitive Programmer public static void main(String[] args) { Scanner sc = new Scanner (System.in); int n = sc.nextInt(); Set<Integer> num = new HashSet<>(); for(int i = 0; i < n; i++) { int a = sc.nextInt(); if(a != 0) { num.add(a); } } System.out.println(num.size()); } }
Java
["5\n1 1 1 1 1", "3\n2 0 -1", "4\n5 -6 -5 1"]
1 second
["1", "2", "4"]
NoteIn the first example you can add  - 1 to all non-zero elements in one second and make them equal to zero.In the second example you can add  - 2 on the first second, then the array becomes equal to [0, 0,  - 3]. On the second second you can add 3 to the third (the only non-zero) element.
Java 11
standard input
[ "implementation", "sortings" ]
0593f79604377dcfa98d2b69840ec0a6
The first line contains a single integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains n integers a1, a2, ..., an ( - 105 ≀ ai ≀ 105) β€” the elements of the array.
800
Print a single integer β€” the minimum number of seconds needed to make all elements of the array equal to zero.
standard output
PASSED
05a640c3f0a52e38f90dbc0c5e8d16ff
train_004.jsonl
1529339700
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties: In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero. When all elements of the array become equal to zero, the array explodes. Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int [n]; for(int i=0; i<n; i++) a[i] = sc.nextInt(); Arrays.sort(a); int c=n; if(a[0] == 0) c--; for(int i=1; i<n; i++){ if(a[i] == a[i-1] || a[i] == 0){ c--; } } System.out.println(c); } }
Java
["5\n1 1 1 1 1", "3\n2 0 -1", "4\n5 -6 -5 1"]
1 second
["1", "2", "4"]
NoteIn the first example you can add  - 1 to all non-zero elements in one second and make them equal to zero.In the second example you can add  - 2 on the first second, then the array becomes equal to [0, 0,  - 3]. On the second second you can add 3 to the third (the only non-zero) element.
Java 11
standard input
[ "implementation", "sortings" ]
0593f79604377dcfa98d2b69840ec0a6
The first line contains a single integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains n integers a1, a2, ..., an ( - 105 ≀ ai ≀ 105) β€” the elements of the array.
800
Print a single integer β€” the minimum number of seconds needed to make all elements of the array equal to zero.
standard output
PASSED
3f5881f9e59b500ef334da63172f8bd4
train_004.jsonl
1529339700
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties: In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero. When all elements of the array become equal to zero, the array explodes. Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args)throws IOException { InputStreamReader read=new InputStreamReader(System.in); BufferedReader in=new BufferedReader(read); int n=Integer.parseInt(in.readLine()); String str=in.readLine(); String line[]=str.trim().split(" "); int a[]=new int[n]; int b[]=new int[n]; int i; for(i=0;i<n;i++) { a[i]=0; b[i]=Integer.parseInt(line[i]); } Arrays.sort(b); int count=1; if(n==1 && b[0]==0) count=0; else if(n==1) count=1; else if(Arrays.equals(a,b)) count=0; else { for(i=0;i<n-1;i++) { if(b[i]!=b[i+1] && b[i]!=0) { count++; } } if(b[n-1]==0) count--; } System.out.println(count); } }
Java
["5\n1 1 1 1 1", "3\n2 0 -1", "4\n5 -6 -5 1"]
1 second
["1", "2", "4"]
NoteIn the first example you can add  - 1 to all non-zero elements in one second and make them equal to zero.In the second example you can add  - 2 on the first second, then the array becomes equal to [0, 0,  - 3]. On the second second you can add 3 to the third (the only non-zero) element.
Java 11
standard input
[ "implementation", "sortings" ]
0593f79604377dcfa98d2b69840ec0a6
The first line contains a single integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains n integers a1, a2, ..., an ( - 105 ≀ ai ≀ 105) β€” the elements of the array.
800
Print a single integer β€” the minimum number of seconds needed to make all elements of the array equal to zero.
standard output
PASSED
35764fa84022814794eda95d4e99ef43
train_004.jsonl
1529339700
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties: In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero. When all elements of the array become equal to zero, the array explodes. Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.
256 megabytes
import java.util.*; public class nastya_and_array { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n=in.nextInt(); int arr[]=new int[n]; Set<Integer> set = new HashSet<>(); for(int i=0;i<n;i++) { arr[i]=in.nextInt(); if(arr[i]!=0) { set.add(arr[i]); } } System.out.println(set.size()); } }
Java
["5\n1 1 1 1 1", "3\n2 0 -1", "4\n5 -6 -5 1"]
1 second
["1", "2", "4"]
NoteIn the first example you can add  - 1 to all non-zero elements in one second and make them equal to zero.In the second example you can add  - 2 on the first second, then the array becomes equal to [0, 0,  - 3]. On the second second you can add 3 to the third (the only non-zero) element.
Java 11
standard input
[ "implementation", "sortings" ]
0593f79604377dcfa98d2b69840ec0a6
The first line contains a single integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains n integers a1, a2, ..., an ( - 105 ≀ ai ≀ 105) β€” the elements of the array.
800
Print a single integer β€” the minimum number of seconds needed to make all elements of the array equal to zero.
standard output
PASSED
a6e7765fa99386ed8b2a0b4cd001b5e1
train_004.jsonl
1529339700
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties: In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero. When all elements of the array become equal to zero, the array explodes. Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.
256 megabytes
import java.util.HashMap; import java.util.Scanner; public class nastya_982A { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); HashMap<Integer, Integer> map = new HashMap<>(); for(int i=0; i<n; i++){ int x = s.nextInt(); if(x == 0){ continue; } map.put(x,1); } System.out.println(map.size()); } }
Java
["5\n1 1 1 1 1", "3\n2 0 -1", "4\n5 -6 -5 1"]
1 second
["1", "2", "4"]
NoteIn the first example you can add  - 1 to all non-zero elements in one second and make them equal to zero.In the second example you can add  - 2 on the first second, then the array becomes equal to [0, 0,  - 3]. On the second second you can add 3 to the third (the only non-zero) element.
Java 11
standard input
[ "implementation", "sortings" ]
0593f79604377dcfa98d2b69840ec0a6
The first line contains a single integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains n integers a1, a2, ..., an ( - 105 ≀ ai ≀ 105) β€” the elements of the array.
800
Print a single integer β€” the minimum number of seconds needed to make all elements of the array equal to zero.
standard output
PASSED
53525b36fd1425224b81f44943a90c50
train_004.jsonl
1529339700
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties: In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero. When all elements of the array become equal to zero, the array explodes. Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.
256 megabytes
// practice with kaiboy import java.io.*; import java.util.*; public class CF992A extends PrintWriter { CF992A() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF992A o = new CF992A(); o.main(); o.flush(); } static final int A = 100000; void main() { boolean[] used = new boolean[A + 1 + A]; int ans = 0; for (int n = sc.nextInt(); n > 0; n--) { int a = sc.nextInt(); if (a == 0) continue; a += A; if (!used[a]) { used[a] = true; ans++; } } println(ans); } }
Java
["5\n1 1 1 1 1", "3\n2 0 -1", "4\n5 -6 -5 1"]
1 second
["1", "2", "4"]
NoteIn the first example you can add  - 1 to all non-zero elements in one second and make them equal to zero.In the second example you can add  - 2 on the first second, then the array becomes equal to [0, 0,  - 3]. On the second second you can add 3 to the third (the only non-zero) element.
Java 11
standard input
[ "implementation", "sortings" ]
0593f79604377dcfa98d2b69840ec0a6
The first line contains a single integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains n integers a1, a2, ..., an ( - 105 ≀ ai ≀ 105) β€” the elements of the array.
800
Print a single integer β€” the minimum number of seconds needed to make all elements of the array equal to zero.
standard output
PASSED
1a551bfefb5c639baf223c82f5b5cca2
train_004.jsonl
1529339700
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties: In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero. When all elements of the array become equal to zero, the array explodes. Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.
256 megabytes
// Working program with FastReader import java.io.*; import java.util.*; public class codeforces_992A { 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; } } public static void main(String[] args) { FastReader ob=new FastReader(); int n =ob.nextInt(); HashSet<Integer>set=new HashSet<>(); for (int i = 0; i < n; i++) { int num=ob.nextInt(); if(num!=0){ set.add(num); } } System.out.println(set.size()); } }
Java
["5\n1 1 1 1 1", "3\n2 0 -1", "4\n5 -6 -5 1"]
1 second
["1", "2", "4"]
NoteIn the first example you can add  - 1 to all non-zero elements in one second and make them equal to zero.In the second example you can add  - 2 on the first second, then the array becomes equal to [0, 0,  - 3]. On the second second you can add 3 to the third (the only non-zero) element.
Java 11
standard input
[ "implementation", "sortings" ]
0593f79604377dcfa98d2b69840ec0a6
The first line contains a single integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains n integers a1, a2, ..., an ( - 105 ≀ ai ≀ 105) β€” the elements of the array.
800
Print a single integer β€” the minimum number of seconds needed to make all elements of the array equal to zero.
standard output
PASSED
b2a9d1770c358a6fa2a79c8a7bc9f1ca
train_004.jsonl
1529339700
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties: In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero. When all elements of the array become equal to zero, the array explodes. Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.
256 megabytes
import java.util.HashSet; import java.util.Scanner; public class Nastyaananrray { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n,x; n=input.nextInt(); HashSet<Integer> h=new HashSet<Integer>(); for (int i = 0; i < n; i++) { x=input.nextInt(); if(x!=0){ h.add(x); } } System.out.println(h.size()); } }
Java
["5\n1 1 1 1 1", "3\n2 0 -1", "4\n5 -6 -5 1"]
1 second
["1", "2", "4"]
NoteIn the first example you can add  - 1 to all non-zero elements in one second and make them equal to zero.In the second example you can add  - 2 on the first second, then the array becomes equal to [0, 0,  - 3]. On the second second you can add 3 to the third (the only non-zero) element.
Java 11
standard input
[ "implementation", "sortings" ]
0593f79604377dcfa98d2b69840ec0a6
The first line contains a single integer n (1 ≀ n ≀ 105) β€” the size of the array. The second line contains n integers a1, a2, ..., an ( - 105 ≀ ai ≀ 105) β€” the elements of the array.
800
Print a single integer β€” the minimum number of seconds needed to make all elements of the array equal to zero.
standard output
PASSED
4f4724e6bad8c10dbdda50c26cbaf96a
train_004.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second β€” number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 β€” AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class B_1 { FastScanner in; PrintWriter out; public void run() { try { in = new FastScanner(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } /*public void solve() throws IOException { String s = "R228C494"; //String s = "R228C26"; //String s = "R23C55"; //String s = "RC228"; if (isExcelType(s) == false) { out.println( convertToExcel(Integer.valueOf(s.split("[RC]")[2])) + s.split("[RC]")[1]); } else { out.println(convertFromExcel(s)); } }*/ public void solve() throws IOException { int n = in.nextInt(); String s = null; for (int i=0; i<n; i++) { s = in.next(); if (isExcelType(s) == false) { out.println( convertToExcel(Integer.valueOf(s.split("[RC]")[2])) + s.split("[RC]")[1]); } else { out.println(convertFromExcel(s)); } } } private String convertToExcel(Integer c) { int base = 26; StringBuilder sb = new StringBuilder(); while (c != 0) { sb.append( (char)(c % base + (c % base == 0 ? 'Z' : 64))); //sb.append( (char)(c % base + 65)); c--; c /= base; } return sb.reverse().toString(); } private String convertFromExcel(String input) { int indexD = 0; for (int i=0; i<input.length(); i++) { if (Character.isDigit(input.charAt(i))) { indexD = i; break; } } String column= input.substring(0, indexD); String row = input.substring(indexD); int c = 0; for (int i=column.length()-1; i>=0; i--) { c += convertCharNumber(column.charAt(i), column.length()-i-1); } return "R" + row + "C" + c; } private int convertCharNumber(char c, int p) { int k = (int)c - 64; for (int i=0; i<p; i++) { k *= 26; } return k; } private boolean isExcelType(String input) { int charOccurCount = 0; for (int i = 0; i<input.length(); i++) { if ((i == 0 || Character.isDigit(input.charAt(i-1))) && Character.isLetter(input.charAt(i))) { charOccurCount++; } } if (charOccurCount == 1) { return true; } else { return false; } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStreamReader in) { br = new BufferedReader(in); } String nextLine() { String str = null; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } 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) { B_1 o = new B_1(); o.run(); } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 7
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≀ n ≀ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
a207a84dc4bdd165e5d019b27f9bb144
train_004.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second β€” number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 β€” AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Contest { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); int N = in.nextInt(); String[] s = new String[N]; for (int i = 0; i < N; i++) { s[i] = in.next(); } char[] alfabet = new char[27]; alfabet[0] = 'Z'; for (int i = 1; i < 27; i++) { alfabet[i] = (char) (i + 64); } for (int i = 0; i < s.length; i++) { if (s[i].matches("R\\d+C\\d+")) { String ss = s[i].replace('R', ' ').replace('C', ' ').trim(); int r = Integer.parseInt(ss.split(" ")[0]); int c = Integer.parseInt(ss.split(" ")[1]); int a = 1000000; String str = ""; List<Integer> list = new ArrayList<>(); int j = 0; while (c >= 26) { list.add(c % 26); c /= 26; } list.add(c % 26); for (int m = list.size() - 1; m > 0; m--) { if (list.get(m - 1) == 0) { list.set(m, list.get(m) - 1); list.set(m - 1, 26); } } for (int v = 0; v < list.size()-1; v++) { if (list.get(v) <= 0) { list.set(v, 26 + list.get(v)); list.set(v + 1, list.get(v+1) - 1); } } for (int f = list.size() - 1; f >= 0; f--) { if (list.get(f) != 0) { str += alfabet[list.get(f)]; } } System.out.println(str + r); } else { int p = 0; while (Character.isAlphabetic(s[i].charAt(p))) { p++; } int k = (int) Math.pow(26, p - 1); int str = 0; for (int j = 0; j < p; j++) { str += ((int) s[i].charAt(j) - 64) * k; k /= 26; } String t = "R"; for (int j = p; j < s[i].length(); j++) { t += s[i].charAt(j); } t += "C"; t += str; System.out.println(t); } } } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 7
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≀ n ≀ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
daee825178593b194e5d9cb6393aca30
train_004.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second β€” number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 β€” AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) throws IOException, NumberFormatException{ HashMap map_ato1=mapgenerator(); HashMap map_1toa=mapgenerator2(); BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); String s=input.readLine(); int totalnumber=Integer.parseInt(s); int counter=0; String a=""; while(counter<totalnumber){ s=input.readLine(); String[] temp = s.split("\\d+"); if(temp.length>1 && "R".equals(temp[0]) && "C".equals(temp[1]) ){ //RC system String reverse=new StringBuffer(s).reverse().toString(); temp=reverse.split("\\D+"); int row=Integer.parseInt(new StringBuffer(temp[1]).reverse().toString()); int column=Integer.parseInt(new StringBuffer(temp[0]).reverse().toString()); String alpha_column=columnconverter(column,map_ato1); System.out.println(alpha_column+row); }else{ String column=temp[0]; temp=s.split("\\D+"); int row=Integer.parseInt(temp[1]); column=new StringBuffer(column).reverse().toString(); int num_column=columnreverse(column,map_1toa); System.out.println("R"+row+"C"+num_column); } counter++; } } public static String columnconverter(int column,HashMap map_ato1){ int quotient=(int)Math.floor(column/26);//quotient is the result of the division int remainder=column % 26; String a=map_ato1.get(remainder).toString(); if(remainder==0){ quotient=quotient-1; } while(quotient!=0){ remainder=quotient % 26; if(remainder==0){ quotient=quotient-1; } double quotient_check=(quotient/26.0); quotient=(int)Math.floor(quotient/26); a+=map_ato1.get(remainder).toString(); if(quotient_check==1.0){ break; } } a=new StringBuffer(a).reverse().toString(); return a; } public static int columnreverse(String column,HashMap map_1toa){ int quotient,remainder,i=2; remainder=(int)map_1toa.get(String.valueOf(column.charAt(column.length()-1))); while((column.length()-i)>=0){ quotient=remainder; remainder=(int)map_1toa.get(String.valueOf(column.charAt(column.length()-i))); remainder=quotient*26+remainder; i++; } return remainder; } public static HashMap mapgenerator(){ HashMap map_ato1=new HashMap(); map_ato1.put(1,"A"); map_ato1.put(2,"B"); map_ato1.put(3,"C"); map_ato1.put(4,"D"); map_ato1.put(5,"E"); map_ato1.put(6,"F"); map_ato1.put(7,"G"); map_ato1.put(8,"H"); map_ato1.put(9,"I"); map_ato1.put(10,"J"); map_ato1.put(11,"K"); map_ato1.put(12,"L"); map_ato1.put(13,"M"); map_ato1.put(14,"N"); map_ato1.put(15,"O"); map_ato1.put(16,"P"); map_ato1.put(17,"Q"); map_ato1.put(18,"R"); map_ato1.put(19,"S"); map_ato1.put(20,"T"); map_ato1.put(21,"U"); map_ato1.put(22,"V"); map_ato1.put(23,"W"); map_ato1.put(24,"X"); map_ato1.put(25,"Y"); map_ato1.put(26,"Z"); map_ato1.put(0,"Z"); return map_ato1; } public static HashMap mapgenerator2(){ HashMap map_1toa=new HashMap(); map_1toa.put("A",1); map_1toa.put("B",2); map_1toa.put("C",3); map_1toa.put("D",4); map_1toa.put("E",5); map_1toa.put("F",6); map_1toa.put("G",7); map_1toa.put("H",8); map_1toa.put("I",9); map_1toa.put("J",10); map_1toa.put("K",11); map_1toa.put("L",12); map_1toa.put("M",13); map_1toa.put("N",14); map_1toa.put("O",15); map_1toa.put("P",16); map_1toa.put("Q",17); map_1toa.put("R",18); map_1toa.put("S",19); map_1toa.put("T",20); map_1toa.put("U",21); map_1toa.put("V",22); map_1toa.put("W",23); map_1toa.put("X",24); map_1toa.put("Y",25); map_1toa.put("Z",26); return map_1toa; } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 7
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≀ n ≀ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
bd6ef7f0230f618183aa01908b6c160b
train_004.jsonl
1266580800
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second β€” number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 β€” AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
64 megabytes
import java.util.Scanner; import java.io.PrintWriter; /** * @author Egor Kulikov (kulikov@devexperts.com) */ public class Spreadsheets implements Runnable { private Scanner in = new Scanner(System.in); private PrintWriter out = new PrintWriter(System.out); private String s, ans; public static void main(String[] args) { new Thread(new Spreadsheets()).start(); } private void read() { s = in.next(); } private void solve() { if (s.matches("R\\d+C\\d+")) { s = s.replace('R', ' ').replace('C', ' '); Scanner ss = new Scanner(s); int r = ss.nextInt(); int c = ss.nextInt(); c--; StringBuffer b = new StringBuffer(); int c26 = 26; int cc = 0; while (cc + c26 <= c) { cc += c26; c26 *= 26; } c -= cc; while (c26 > 1) { c26 /= 26; b.append((char) (c / c26 + 'A')); c %= c26; } ans = b.toString() + r; } else { int p = 0; while (!Character.isDigit(s.charAt(p))) { p++; } int c26 = 1; int cc = 0; for (int i = 0; i < p; i++) { cc += c26; c26 *= 26; } for (int i = 0; i < p; i++) { c26 /= 26; cc += c26 * (s.charAt(i) - 'A'); } ans = "R" + s.substring(p) + "C" + cc; } } private void write() { out.println(ans); } public void run() { int n = in.nextInt(); for (int i = 0; i < n; i++) { read(); solve(); write(); } out.close(); } }
Java
["2\nR23C55\nBC23"]
10 seconds
["BC23\nR23C55"]
null
Java 7
standard input
[ "implementation", "math" ]
910c0e650d48af22fa51ab05e8123709
The first line of the input contains integer number n (1 ≀ n ≀ 105), the number of coordinates in the test. Then there follow n lines, each of them contains coordinates. All the coordinates are correct, there are no cells with the column and/or the row numbers larger than 106 .
1,600
Write n lines, each line should contain a cell coordinates in the other numeration system.
standard output
PASSED
c2a16d4273eb989a9704bde8a691bb6e
train_004.jsonl
1544459700
Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters "a" and "b". He calculated $$$c$$$Β β€” the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; public class realfast implements Runnable { private static final int INF = (int) 1e9; long in= (long)Math.pow(10,9)+7; public void solve() throws IOException { int n = readInt(); int k = readInt(); String a = readString(); String b = readString(); int i=0; for(i=0;i<n;i++) { if(a.charAt(i)!=b.charAt(i)) break; } long count =i; long match[]= new long[n]; long val=0; if(i<n) match[i]++; for(int j=i+1;j<n;j++) { val=2*val; if(a.charAt(j)=='a') val++; val=Math.min(val,k); match[j]=match[j]+val+1; } if(i<n) match[i]++; val=0; for(int j=i+1;j<n;j++) { val=2*val; if(b.charAt(j)=='b') val++; val=Math.min(val,k); match[j]=match[j]+val+1; } for(int j=i;j<n;j++) count= count+Math.min(k,match[j]); out.println(count); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void main(String[] args) { new Thread(null, new realfast(), "", 128 * (1L << 20)).start(); } private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader reader; private StringTokenizer tokenizer; private PrintWriter out; @Override public void run() { try { if (ONLINE_JUDGE || !new File("input.txt").exists()) { reader = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { reader = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } solve(); } catch (IOException e) { throw new RuntimeException(e); } finally { try { reader.close(); } catch (IOException e) { // nothing } out.close(); } } private String readString() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } @SuppressWarnings("unused") private int readInt() throws IOException { return Integer.parseInt(readString()); } @SuppressWarnings("unused") private long readLong() throws IOException { return Long.parseLong(readString()); } @SuppressWarnings("unused") private double readDouble() throws IOException { return Double.parseDouble(readString()); } } class edge implements Comparable<edge>{ int u ; int v ; int val; edge(int u1, int v1 , int val1) { this.u=u1; this.v=v1; this.val=val1; } public int compareTo(edge e) { return this.val-e.val; } }
Java
["2 4\naa\nbb", "3 3\naba\nbba", "4 5\nabbb\nbaaa"]
1 second
["6", "8", "8"]
NoteIn the first example, Nut could write strings "aa", "ab", "ba", "bb". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $$$6$$$ strings.In the second example, Nut could write strings "aba", "baa", "bba".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$.
Java 8
standard input
[ "greedy", "strings" ]
a88e4a7c476b9af1ff2ca9137214dfd7
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$)Β β€” the string consisting of letters "a" and "b. The third line contains a string $$$t$$$ ($$$|t| = n$$$)Β β€” the string consisting of letters "a" and "b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.
2,000
Print one numberΒ β€” maximal value of $$$c$$$.
standard output
PASSED
7abb74b38d81eec979b3411fed2b3f75
train_004.jsonl
1544459700
Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters "a" and "b". He calculated $$$c$$$Β β€” the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
256 megabytes
import java.io.*; import java.util.*; public class NutString { private static StringTokenizer ST; private static BufferedReader BR; private static PrintWriter PW; private static int nextInt() throws IOException { return Integer.parseInt(next()); } private static long nextLong() throws IOException { return Long.parseLong(next()); } private static double nextDouble() throws IOException { return Double.parseDouble(next()); } private static String next() throws IOException { while (ST == null || !ST.hasMoreTokens()) ST = new StringTokenizer(BR.readLine()); return ST.nextToken(); } private void run() throws IOException { BR = new BufferedReader(new InputStreamReader(System.in)); PW = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); long k = nextLong(); long D[] = new long[n+1]; String a = next(); String b = next(); if(k==1){ PW.println(n); PW.close(); return; } char[] A = a.toCharArray(); char[] B = b.toCharArray(); for(int i = 1; i<= n ; i++){ D[i] = D[i-1] * 2 + (B[i-1] - A[i-1]); if(D[i] > k+2){ break; } } for(int i = n ; i>=1; i--){ D[i] -= D[i-1]; } int first= n+1; for(int i = 1 ; i <=n ; i++) { if (D[i] == 1) { D[i] = 0; first = i; break; } } long cnt = 2*n-first + 1; long K = k-2; for(int i = 1 ; i <=n && K>0; i++){ if(K>=D[i]){ cnt += D[i] * (n-i+1); K -= D[i]; }else{ cnt += K *(n-i +1); break; } } PW.println(cnt); PW.close(); } public static void main(String[] args) throws IOException { new NutString().run(); } }
Java
["2 4\naa\nbb", "3 3\naba\nbba", "4 5\nabbb\nbaaa"]
1 second
["6", "8", "8"]
NoteIn the first example, Nut could write strings "aa", "ab", "ba", "bb". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $$$6$$$ strings.In the second example, Nut could write strings "aba", "baa", "bba".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$.
Java 8
standard input
[ "greedy", "strings" ]
a88e4a7c476b9af1ff2ca9137214dfd7
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$)Β β€” the string consisting of letters "a" and "b. The third line contains a string $$$t$$$ ($$$|t| = n$$$)Β β€” the string consisting of letters "a" and "b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.
2,000
Print one numberΒ β€” maximal value of $$$c$$$.
standard output
PASSED
237f986fb97c7b629f6353a3cc0a3cdb
train_004.jsonl
1544459700
Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters "a" and "b". He calculated $$$c$$$Β β€” the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
256 megabytes
import java.io.*; import java.util.*; public class NutString { private static StringTokenizer ST; private static BufferedReader BR; private static PrintWriter PW; private static int nextInt() throws IOException { return Integer.parseInt(next()); } private static long nextLong() throws IOException { return Long.parseLong(next()); } private static double nextDouble() throws IOException { return Double.parseDouble(next()); } private static String next() throws IOException { while (ST == null || !ST.hasMoreTokens()) ST = new StringTokenizer(BR.readLine()); return ST.nextToken(); } private void run() throws IOException { BR = new BufferedReader(new InputStreamReader(System.in)); PW = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int n = nextInt(); long k = nextLong(); long C[] = new long[n+1]; long D[] = new long[n+1]; String a = next(); String b = next(); if(k==1){ PW.println(n); PW.close(); return; } char[] A = a.toCharArray(); char[] B = b.toCharArray(); for(int i = 1; i<= n ; i++){ C[i] = C[i-1] * 2 + (B[i-1] - A[i-1]); D[i] = C[i] - C[i-1]; if(C[i] > k+2){ break; } } int first= n+1; for(int i = 1 ; i <=n ; i++) { if (D[i] == 1) { D[i] = 0; first = i; break; } } long cnt = 2*n-first + 1; long K = k-2; for(int i = 1 ; i <=n && K>0; i++){ if(K>=D[i]){ cnt += D[i] * (n-i+1); K -= D[i]; }else{ cnt += K *(n-i +1); break; } } PW.println(cnt); PW.close(); } public static void main(String[] args) throws IOException { new NutString().run(); } }
Java
["2 4\naa\nbb", "3 3\naba\nbba", "4 5\nabbb\nbaaa"]
1 second
["6", "8", "8"]
NoteIn the first example, Nut could write strings "aa", "ab", "ba", "bb". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $$$6$$$ strings.In the second example, Nut could write strings "aba", "baa", "bba".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$.
Java 8
standard input
[ "greedy", "strings" ]
a88e4a7c476b9af1ff2ca9137214dfd7
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$)Β β€” the string consisting of letters "a" and "b. The third line contains a string $$$t$$$ ($$$|t| = n$$$)Β β€” the string consisting of letters "a" and "b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.
2,000
Print one numberΒ β€” maximal value of $$$c$$$.
standard output
PASSED
12ccacf4c136fcbff6c3d42846e8cb3b
train_004.jsonl
1544459700
Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters "a" and "b". He calculated $$$c$$$Β β€” the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.File; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author kessido */ 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); BTheFairNutAndStrings solver = new BTheFairNutAndStrings(); solver.solve(1, in, out); out.close(); } static class BTheFairNutAndStrings { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.NextInt(); int k = in.NextInt(); char[] s = in.next().toCharArray(); char[] t = in.next().toCharArray(); long prefixCount = 0; int index = 0; while (index < n && s[index] == t[index]) { prefixCount++; index++; } long distance = 0; for (; index < n; index++) { distance *= 2; distance -= s[index] == 'b' ? 1 : 0; distance += t[index] == 'b' ? 1 : 0; distance = Math.min(distance, k); long countStringBerween = Math.min(distance + 1, k); prefixCount += countStringBerween; } out.println(prefixCount); } } static class OutputWriter extends PrintWriter { public OutputWriter(Writer out) { super(out); } public OutputWriter(File file) throws FileNotFoundException { super(file); } public OutputWriter(OutputStream out) { super(out); } } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine(), " \t\n\r\f,"); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int NextInt() { return Integer.parseInt(next()); } } }
Java
["2 4\naa\nbb", "3 3\naba\nbba", "4 5\nabbb\nbaaa"]
1 second
["6", "8", "8"]
NoteIn the first example, Nut could write strings "aa", "ab", "ba", "bb". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $$$6$$$ strings.In the second example, Nut could write strings "aba", "baa", "bba".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$.
Java 8
standard input
[ "greedy", "strings" ]
a88e4a7c476b9af1ff2ca9137214dfd7
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$)Β β€” the string consisting of letters "a" and "b. The third line contains a string $$$t$$$ ($$$|t| = n$$$)Β β€” the string consisting of letters "a" and "b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.
2,000
Print one numberΒ β€” maximal value of $$$c$$$.
standard output
PASSED
25f31ba6f8f876ff8b19f350d303e97d
train_004.jsonl
1544459700
Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters "a" and "b". He calculated $$$c$$$Β β€” the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); int K = in.nextInt(); char[] s = in.next().toCharArray(); char[] t = in.next().toCharArray(); long res = 0; int longestPre = 0; for (int i = 0; i <= N; i++) { if (i == N) { longestPre = N; break; } if (t[i] != s[i]) { longestPre = i; break; } } int[] sums = new int[N + 1]; for (int i = longestPre; i < N - 1; i++) { if (s[i + 1] == 'a') { sums[N - i]++; } if (t[i + 1] == 'b') { sums[N - i]++; } } if (K == 1) { out.println(N); } else { res = longestPre + 2 * (N - longestPre); long curMore = 0; int curHeight = N; K -= 2; while (K > 0 && curHeight > 0) { res += (curHeight - 1) * Math.min(K, (sums[curHeight] + curMore)); K -= Math.min(sums[curHeight] + curMore, K); curMore += sums[curHeight] + curMore; curHeight--; } out.println(res); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2 4\naa\nbb", "3 3\naba\nbba", "4 5\nabbb\nbaaa"]
1 second
["6", "8", "8"]
NoteIn the first example, Nut could write strings "aa", "ab", "ba", "bb". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $$$6$$$ strings.In the second example, Nut could write strings "aba", "baa", "bba".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$.
Java 8
standard input
[ "greedy", "strings" ]
a88e4a7c476b9af1ff2ca9137214dfd7
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$)Β β€” the string consisting of letters "a" and "b. The third line contains a string $$$t$$$ ($$$|t| = n$$$)Β β€” the string consisting of letters "a" and "b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.
2,000
Print one numberΒ β€” maximal value of $$$c$$$.
standard output
PASSED
756f3fe38f28be1931017b374a5bb68c
train_004.jsonl
1544459700
Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters "a" and "b". He calculated $$$c$$$Β β€” the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class B { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); // Scanner scan = new Scanner(System.in); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); // int n = Integer.parseInt(bf.readLine()); StringTokenizer st = new StringTokenizer(bf.readLine()); // int[] a = new int[n]; for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); String s = bf.readLine(); String t = bf.readLine(); long v1 = 0; long v2 = 0; long ans = 0; boolean cont = true; for(int i=0; i<n; i++) { if(cont) { v1 *= 2; v2 *= 2; if(s.charAt(i) == 'b') v1++; if(t.charAt(i) == 'b') v2++; if(v2-v1+1 < k) { ans += v2-v1+1; } else { ans += k; cont = false; } } else { ans += k; } } out.println(ans); // int n = scan.nextInt(); out.close(); System.exit(0); } }
Java
["2 4\naa\nbb", "3 3\naba\nbba", "4 5\nabbb\nbaaa"]
1 second
["6", "8", "8"]
NoteIn the first example, Nut could write strings "aa", "ab", "ba", "bb". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $$$6$$$ strings.In the second example, Nut could write strings "aba", "baa", "bba".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$.
Java 8
standard input
[ "greedy", "strings" ]
a88e4a7c476b9af1ff2ca9137214dfd7
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$)Β β€” the string consisting of letters "a" and "b. The third line contains a string $$$t$$$ ($$$|t| = n$$$)Β β€” the string consisting of letters "a" and "b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.
2,000
Print one numberΒ β€” maximal value of $$$c$$$.
standard output
PASSED
249270f1ceec8fa531c37ce7de24da4d
train_004.jsonl
1544459700
Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters "a" and "b". He calculated $$$c$$$Β β€” the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class B { public static void main(String[] args) throws IOException { /**/ Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in))); /*/ Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("src/b.in")))); /**/ int n = sc.nextInt(); int k = sc.nextInt(); String s = sc.next(); String t = sc.next(); long ans = 0; long diff = 0; for (int i = 0; i < n; i++) { diff *= 2; if (s.charAt(i)=='b') diff--; if (t.charAt(i)=='b') diff++; diff = Math.min(diff, k); ans += Math.min(k, diff+1); } System.out.println(ans); } }
Java
["2 4\naa\nbb", "3 3\naba\nbba", "4 5\nabbb\nbaaa"]
1 second
["6", "8", "8"]
NoteIn the first example, Nut could write strings "aa", "ab", "ba", "bb". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $$$6$$$ strings.In the second example, Nut could write strings "aba", "baa", "bba".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$.
Java 8
standard input
[ "greedy", "strings" ]
a88e4a7c476b9af1ff2ca9137214dfd7
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$)Β β€” the string consisting of letters "a" and "b. The third line contains a string $$$t$$$ ($$$|t| = n$$$)Β β€” the string consisting of letters "a" and "b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.
2,000
Print one numberΒ β€” maximal value of $$$c$$$.
standard output
PASSED
6144ef54f3d5bed141abd12a38aca22b
train_004.jsonl
1544459700
Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters "a" and "b". He calculated $$$c$$$Β β€” the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Vadim */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); BDiv1 solver = new BDiv1(); solver.solve(1, in, out); out.close(); } static class BDiv1 { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.ni(); long k = in.ni(); String s = in.ns(); String t = in.ns(); long ans = n; k--; if (k > 0) { int start = 0; while (start < n) { if (s.charAt(start) != t.charAt(start)) { break; } start++; } if (start < n) { ans += n - start; k--; if (k > 0) { long ni = 0; for (int i = start + 1; i < n; i++) { if (ni >= k) { ans += (n - i) * k; k = 0; break; } else { ans += (n - i) * ni; k -= ni; } ni *= 2; if (s.charAt(i) == 'a') { ans += n - i; k--; ni++; } if (k == 0) break; if (t.charAt(i) == 'b') { ans += n - i; k--; ni++; } if (k == 0) break; } } } } out.println(ans); } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String ns() { while (st == null || !st.hasMoreTokens()) { try { String rl = in.readLine(); if (rl == null) { return null; } st = new StringTokenizer(rl); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int ni() { return Integer.parseInt(ns()); } } }
Java
["2 4\naa\nbb", "3 3\naba\nbba", "4 5\nabbb\nbaaa"]
1 second
["6", "8", "8"]
NoteIn the first example, Nut could write strings "aa", "ab", "ba", "bb". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $$$6$$$ strings.In the second example, Nut could write strings "aba", "baa", "bba".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$.
Java 8
standard input
[ "greedy", "strings" ]
a88e4a7c476b9af1ff2ca9137214dfd7
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$)Β β€” the string consisting of letters "a" and "b. The third line contains a string $$$t$$$ ($$$|t| = n$$$)Β β€” the string consisting of letters "a" and "b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.
2,000
Print one numberΒ β€” maximal value of $$$c$$$.
standard output
PASSED
c3eeffb3322d18468639d0de13722690
train_004.jsonl
1544459700
Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters "a" and "b". He calculated $$$c$$$Β β€” the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Egor Kulikov (egor@egork.net) */ 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); BOrehusIStroki solver = new BOrehusIStroki(); solver.solve(1, in, out); out.close(); } static class BOrehusIStroki { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int k = in.readInt(); char[] s = in.readCharArray(n); char[] t = in.readCharArray(n); long inside = 0; boolean equal = true; long answer = 0; for (int i = 0; i < n; i++) { if (equal) { if (s[i] != t[i]) { equal = false; answer += Math.min(k, 2); } else { answer++; } } else { if (s[i] == 'a') { inside++; } if (t[i] == 'b') { inside++; } answer += Math.min(k, 2 + inside); } inside *= 2; inside = Math.min(inside, k); } out.printLine(answer); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public char[] readCharArray(int size) { char[] array = new char[size]; for (int i = 0; i < size; i++) { array[i] = readCharacter(); } return array; } 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 boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } 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 interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } 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 close() { writer.close(); } public void printLine(long i) { writer.println(i); } } }
Java
["2 4\naa\nbb", "3 3\naba\nbba", "4 5\nabbb\nbaaa"]
1 second
["6", "8", "8"]
NoteIn the first example, Nut could write strings "aa", "ab", "ba", "bb". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $$$6$$$ strings.In the second example, Nut could write strings "aba", "baa", "bba".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$.
Java 8
standard input
[ "greedy", "strings" ]
a88e4a7c476b9af1ff2ca9137214dfd7
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$)Β β€” the string consisting of letters "a" and "b. The third line contains a string $$$t$$$ ($$$|t| = n$$$)Β β€” the string consisting of letters "a" and "b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.
2,000
Print one numberΒ β€” maximal value of $$$c$$$.
standard output
PASSED
528cd0afbde05804d792546672cb9b63
train_004.jsonl
1544459700
Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters "a" and "b". He calculated $$$c$$$Β β€” the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Solution{ static long[][] dp; static int[] first; static int[] last; static int n; static long k; static void inisialiser(){ if(first[0]!=last[0]) { k--; dp[0][1] = 1; if(k!=0){ dp[0][2] = 1; k--; } }else{ k--; dp[0][0] = 1; } } static void remplir(){ for(int i=1;i<n;i++){ dp[i][3] += dp[i-1][3]; dp[i][3] += (long) Math.min(k,dp[i-1][3]); k -= (long) Math.min(k,dp[i-1][3]); if(first[i]==last[i]){ dp[i][0] += dp[i-1][0]; }else if(first[i]<last[i]){ dp[i][1] += dp[i-1][0]; dp[i][2] += (long) Math.min(k,dp[i-1][0]); k -= (long) Math.min(k,dp[i-1][0]); } if(last[i]==1){ dp[i][3] += dp[i-1][1]; dp[i][1] += (long) Math.min(k,dp[i-1][1]); k -= (long) Math.min(k,dp[i-1][1]); }else{ dp[i][1] += dp[i-1][1]; } if(first[i]==0){ dp[i][3] += dp[i-1][2]; dp[i][2] += (long) Math.min(k,dp[i-1][2]); k -= (long) Math.min(k,dp[i-1][2]); }else{ dp[i][2] += dp[i-1][2]; } } } static long reponse(){ long res = 0; for(int i=0;i<n;i++){ for(int j=0;j<4;j++){ res += dp[i][j]; } } return res; } public static void main(String[] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); //PrintWriter out = new PrintWriter(System.out); n = Integer.parseInt(st.nextToken()); k = Long.parseLong(st.nextToken()); dp = new long[n][4]; // nombre de string de length i = 1,2,...,n // dp[i][1] les string al akbar 9at3an min s // dp[i][2] les string al asghar 9at3an min t String s = br.readLine(); String t = br.readLine(); first = new int[n]; last = new int[n]; for(int i=0;i<n;i++){ if(s.charAt(i)=='a') first[i] = 0; else first[i] = 1; if(t.charAt(i)=='a') last[i] = 0; else last[i] = 1; } inisialiser(); // pour indice 0; remplir(); // pour remplir dp long resultat = reponse(); // resultat System.out.println(resultat); } }
Java
["2 4\naa\nbb", "3 3\naba\nbba", "4 5\nabbb\nbaaa"]
1 second
["6", "8", "8"]
NoteIn the first example, Nut could write strings "aa", "ab", "ba", "bb". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $$$6$$$ strings.In the second example, Nut could write strings "aba", "baa", "bba".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$.
Java 8
standard input
[ "greedy", "strings" ]
a88e4a7c476b9af1ff2ca9137214dfd7
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$)Β β€” the string consisting of letters "a" and "b. The third line contains a string $$$t$$$ ($$$|t| = n$$$)Β β€” the string consisting of letters "a" and "b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.
2,000
Print one numberΒ β€” maximal value of $$$c$$$.
standard output
PASSED
caea1cea9ca58031b2737830d2eea00c
train_004.jsonl
1544459700
Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters "a" and "b". He calculated $$$c$$$Β β€” the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class _526B { public static void main(String[] args) { FastScanner fs=new FastScanner(); int n=fs.nextInt(), k=fs.nextInt(); if (k==1) { System.out.println(n); return; } char[] s1=fs.next().toCharArray(), s2=fs.next().toCharArray(); int lcp=0; for (; lcp<n && s1[lcp]==s2[lcp]; lcp++); k-=2; long ans=n+n-lcp; // System.out.println(ans); long[] potentials=new long[n+1]; //s1 side of trie for (int index=lcp+1; index<n; index++) { if (s1[index]=='a') { int len=n-index; potentials[len]++; for (int i=0; i<31; i++) { len--; if (len>=0) potentials[len]+=1l<<i; } } } //s2 side of trie for (int index=lcp+1; index<n; index++) { if (s2[index]=='b') { int len=n-index; potentials[len]++; for (int i=0; i<31; i++) { len--; if (len>=0) potentials[len]+=1l<<i; } } } for (int i=n; i>0; i--) { long toSub=Math.min(k, potentials[i]); k-=toSub; ans+=i*toSub; } System.out.println(ans); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } } }
Java
["2 4\naa\nbb", "3 3\naba\nbba", "4 5\nabbb\nbaaa"]
1 second
["6", "8", "8"]
NoteIn the first example, Nut could write strings "aa", "ab", "ba", "bb". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $$$6$$$ strings.In the second example, Nut could write strings "aba", "baa", "bba".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$.
Java 8
standard input
[ "greedy", "strings" ]
a88e4a7c476b9af1ff2ca9137214dfd7
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$)Β β€” the string consisting of letters "a" and "b. The third line contains a string $$$t$$$ ($$$|t| = n$$$)Β β€” the string consisting of letters "a" and "b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.
2,000
Print one numberΒ β€” maximal value of $$$c$$$.
standard output
PASSED
de348b3f84758a530cb606ba63732bae
train_004.jsonl
1544459700
Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters "a" and "b". He calculated $$$c$$$Β β€” the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); String a = sc.next(); String b = sc.next(); int start = 0; for (start = 0; start < n; start++) { if (a.charAt(start) != b.charAt(start)) break; } if (k == 1) { System.out.println(n); return; } else if (k == 2) { System.out.println(2 * n - start); return; } long tot = 2 * n - start; n -= start; a = a.substring(start); b = b.substring(start); k -= 2; int[] arr = new int[n]; for (int i = 1; i < n; i++) { if (a.charAt(i) == 'a') { arr[n - i] += 1; } if (b.charAt(i) == 'b') { arr[n - i] += 1; } } int prev = 0; for (int i = n - 1; i >= 0; i--) { if (k >= arr[i] + prev) { k -= arr[i] + prev; tot += (long) i * (arr[i] + prev); if (i > 0) { prev += arr[i] + prev; } } else { tot += (long) i * k; break; } } System.out.println(tot); } static class Scanner { StringTokenizer st; BufferedReader br; 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()); } } }
Java
["2 4\naa\nbb", "3 3\naba\nbba", "4 5\nabbb\nbaaa"]
1 second
["6", "8", "8"]
NoteIn the first example, Nut could write strings "aa", "ab", "ba", "bb". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $$$6$$$ strings.In the second example, Nut could write strings "aba", "baa", "bba".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$.
Java 8
standard input
[ "greedy", "strings" ]
a88e4a7c476b9af1ff2ca9137214dfd7
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$)Β β€” the string consisting of letters "a" and "b. The third line contains a string $$$t$$$ ($$$|t| = n$$$)Β β€” the string consisting of letters "a" and "b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.
2,000
Print one numberΒ β€” maximal value of $$$c$$$.
standard output
PASSED
7961abf189b51957f253221238363aca
train_004.jsonl
1544459700
Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters "a" and "b". He calculated $$$c$$$Β β€” the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
256 megabytes
import java.util.*; import java.math.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n,k; n=scanner.nextInt(); k=scanner.nextInt(); String as,bs; as=scanner.next(); bs=scanner.next(); BigInteger c=new BigInteger("0"),d=new BigInteger("0"); BigInteger kk=BigInteger.valueOf(k); BigInteger two=new BigInteger("2"); BigInteger one=new BigInteger("1"); long total=0; boolean flag=false; int di=0; for(int i=0;i<n;i++){ if(as.charAt(i)!=bs.charAt(i))break; total+=1; di++; } for(int i=di;i<n;i++){ if(flag){ total+=k; continue; } c=c.multiply(two); d=d.multiply(two); if(as.charAt(i)=='b')c=c.add(one); if(bs.charAt(i)=='b')d=d.add(one); BigInteger diff=d.subtract(c); diff=diff.add(one); if(diff.compareTo(kk)>=1){ total+=k; flag = true; continue; } total += diff.longValue(); } System.out.println(total); } }
Java
["2 4\naa\nbb", "3 3\naba\nbba", "4 5\nabbb\nbaaa"]
1 second
["6", "8", "8"]
NoteIn the first example, Nut could write strings "aa", "ab", "ba", "bb". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $$$6$$$ strings.In the second example, Nut could write strings "aba", "baa", "bba".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$.
Java 8
standard input
[ "greedy", "strings" ]
a88e4a7c476b9af1ff2ca9137214dfd7
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$)Β β€” the string consisting of letters "a" and "b. The third line contains a string $$$t$$$ ($$$|t| = n$$$)Β β€” the string consisting of letters "a" and "b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.
2,000
Print one numberΒ β€” maximal value of $$$c$$$.
standard output
PASSED
d4ab9b9c37cbf006df813cb48ca54d4a
train_004.jsonl
1544459700
Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters "a" and "b". He calculated $$$c$$$Β β€” the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author prakharjain */ 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); BTheFairNutAndStrings solver = new BTheFairNutAndStrings(); solver.solve(1, in, out); out.close(); } static class BTheFairNutAndStrings { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int k = in.nextInt(); if (k == 1) { out.println(n); return; } String s = in.next(); String t = in.next(); long dis = 0; long ans = 0; boolean diff = false; for (int i = 0; i < n; i++) { if (dis == 0) { if (!diff) { if (s.charAt(i) == t.charAt(i)) { ans++; } else { ans += 2; diff = true; } } else { if (s.charAt(i) == 'b' && t.charAt(i) == 'a') { ans += 2; } else if (s.charAt(i) == 'a' && t.charAt(i) == 'a') { if (k >= 3) { ans += 3; dis = 1; } else { ans += k; } } else if (s.charAt(i) == 'b' && t.charAt(i) == 'b') { if (k >= 3) { ans += 3; dis = 1; } else { ans += k; } } else { if (k >= 4) { ans += 4; dis = 2; } else { ans += k; dis = k - 2; } } } } else { long ndis = dis; if (s.charAt(i) == 'b' && t.charAt(i) == 'a') { ndis *= 2; } else if (s.charAt(i) == 'a' && t.charAt(i) == 'a') { ndis *= 2; ndis++; } else if (s.charAt(i) == 'b' && t.charAt(i) == 'b') { ndis *= 2; ndis++; } else { ndis *= 2; ndis += 2; } if (ndis + 2 <= k) { dis = ndis; ans += ndis + 2; } else { dis = k - 2; ans += k; } } } out.println(ans); } } 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 close() { writer.close(); } public void println(long i) { writer.println(i); } public void println(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } 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 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 String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { 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 String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["2 4\naa\nbb", "3 3\naba\nbba", "4 5\nabbb\nbaaa"]
1 second
["6", "8", "8"]
NoteIn the first example, Nut could write strings "aa", "ab", "ba", "bb". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $$$6$$$ strings.In the second example, Nut could write strings "aba", "baa", "bba".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$.
Java 8
standard input
[ "greedy", "strings" ]
a88e4a7c476b9af1ff2ca9137214dfd7
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$)Β β€” the string consisting of letters "a" and "b. The third line contains a string $$$t$$$ ($$$|t| = n$$$)Β β€” the string consisting of letters "a" and "b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.
2,000
Print one numberΒ β€” maximal value of $$$c$$$.
standard output
PASSED
3e369429ec915c1b6d93836fd558666e
train_004.jsonl
1544459700
Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters "a" and "b". He calculated $$$c$$$Β β€” the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author beginner1010 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); long k = in.nextInt(); String s = in.nextToken(); String t = in.nextToken(); long ans = 0; long count = 1; for (int i = 0; i < n; i++) { count *= 2; if (s.charAt(i) == 'b') count--; if (t.charAt(i) == 'a') count--; if (count < k) ans += count; else { ans += (n - i) * k; break; } } out.println(ans); return; } } static class InputReader { private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputStream stream; public InputReader(InputStream stream) { this.stream = stream; } private boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private 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 nextInt() { int c = read(); while (isWhitespace(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 (!isWhitespace(c)); return res * sgn; } public String nextToken() { int c = read(); while (isWhitespace(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isWhitespace(c)); return res.toString(); } } }
Java
["2 4\naa\nbb", "3 3\naba\nbba", "4 5\nabbb\nbaaa"]
1 second
["6", "8", "8"]
NoteIn the first example, Nut could write strings "aa", "ab", "ba", "bb". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $$$6$$$ strings.In the second example, Nut could write strings "aba", "baa", "bba".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$.
Java 8
standard input
[ "greedy", "strings" ]
a88e4a7c476b9af1ff2ca9137214dfd7
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$)Β β€” the string consisting of letters "a" and "b. The third line contains a string $$$t$$$ ($$$|t| = n$$$)Β β€” the string consisting of letters "a" and "b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.
2,000
Print one numberΒ β€” maximal value of $$$c$$$.
standard output
PASSED
c4b07e95605cf998d5fd2f4578fdb6cb
train_004.jsonl
1544459700
Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters "a" and "b". He calculated $$$c$$$Β β€” the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.
256 megabytes
//package round526; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class B { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); long K = nl(); char[] s = ns(n); char[] t = ns(n); if(K == 1){ out.println(n); return; } int state = 1; long free = 0; long ans = 0; for(int i = 0;i < n;i++){ if(state == 1){ if(s[i] != t[i]){ state = 2; } ans += state; }else{ free *= 2; if(s[i] == 'a'){ free++; } if(t[i] == 'b'){ free++; } ans += Math.min(free+state, K); free = Math.min(free, 10000000000L); } } out.println(ans); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new B().run(); } 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 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 char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); 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 * 10 + (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(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["2 4\naa\nbb", "3 3\naba\nbba", "4 5\nabbb\nbaaa"]
1 second
["6", "8", "8"]
NoteIn the first example, Nut could write strings "aa", "ab", "ba", "bb". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $$$6$$$ strings.In the second example, Nut could write strings "aba", "baa", "bba".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$.
Java 8
standard input
[ "greedy", "strings" ]
a88e4a7c476b9af1ff2ca9137214dfd7
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$)Β β€” the string consisting of letters "a" and "b. The third line contains a string $$$t$$$ ($$$|t| = n$$$)Β β€” the string consisting of letters "a" and "b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.
2,000
Print one numberΒ β€” maximal value of $$$c$$$.
standard output
PASSED
e86304e599112eb8e8ddb15b69a7f6bc
train_004.jsonl
1276182000
Nick is attracted by everything unconventional. He doesn't like decimal number system any more, and he decided to study other number systems. A number system with base b caught his attention. Before he starts studying it, he wants to write in his notepad all the numbers of length n without leading zeros in this number system. Each page in Nick's notepad has enough space for c numbers exactly. Nick writes every suitable number only once, starting with the first clean page and leaving no clean spaces. Nick never writes number 0 as he has unpleasant memories about zero divide.Would you help Nick find out how many numbers will be written on the last page.
64 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } } class Task{ int eular(int c) { int ret = c; for (int i = 2; i * i <= c; i ++) { if(c % i == 0) { ret = ret / i * (i - 1); while(c % i == 0) { c = c / i; } } } if(c > 1) ret = ret / c * (c - 1); return ret; } void solve(InputReader in,PrintWriter out){ String s = in.next() , n = in.next(); int c = in.nextInt(); int phi = eular(c); long a = 0,b = 0; for (int i = 0 ; i < s.length() ; i ++) { a = (a * 10 + s.charAt(i) - '0') % c; } if (n.length() < 10) { for (int i = 0 ; i < n.length() ; i ++) { b = b * 10 + n.charAt(i) - '0'; } b --; } else { for (int i = 0 ; i < n.length() ; i ++) { b = (b * 10 + n.charAt(i) - '0') % phi; } b = b + phi -1 ; b = b + phi; } long ret = ((a - 1) % c + c) % c; while (b > 0) { if((b & 1) == 1) ret = ret * a % c; a = a * a % c; b = b >> 1; } if(ret == 0) ret = ret + c; out.println(ret); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } }
Java
["2 3 3", "2 3 4"]
2 seconds
["1", "4"]
NoteIn both samples there are exactly 4 numbers of length 3 in binary number system. In the first sample Nick writes 3 numbers on the first page and 1 on the second page. In the second sample all the 4 numbers can be written on the first page.
Java 7
standard input
[ "number theory" ]
566adc43d2d6df257c26c5f5495a5745
The only input line contains three space-separated integers b, n and c (2 ≀ b &lt; 10106, 1 ≀ n &lt; 10106, 1 ≀ c ≀ 109). You may consider that Nick has infinite patience, endless amount of paper and representations of digits as characters. The numbers doesn't contain leading zeros.
2,400
In the only line output the amount of numbers written on the same page as the last number.
standard output
PASSED
1adffbb21a77e72ae3c5adf6a7e6939d
train_004.jsonl
1276182000
Nick is attracted by everything unconventional. He doesn't like decimal number system any more, and he decided to study other number systems. A number system with base b caught his attention. Before he starts studying it, he wants to write in his notepad all the numbers of length n without leading zeros in this number system. Each page in Nick's notepad has enough space for c numbers exactly. Nick writes every suitable number only once, starting with the first clean page and leaving no clean spaces. Nick never writes number 0 as he has unpleasant memories about zero divide.Would you help Nick find out how many numbers will be written on the last page.
64 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } } class Task{ int eular(int c) { int ret = 1; for (int i = 2; i * i <= c; i ++) { if(c % i == 0) { ret = ret * (i - 1); c = c / i; while(c % i == 0) { c = c / i; ret = ret * i ; } } } if(c > 1) ret = ret * (c - 1); return ret; } void solve(InputReader in,PrintWriter out){ String s = in.next() , n = in.next(); int c = in.nextInt(); int phi = eular(c); long a = 0,b = 0; for (int i = 0 ; i < s.length() ; i ++) { a = (a * 10 + s.charAt(i) - '0') % c; } if (n.length() < 10) { for (int i = 0 ; i < n.length() ; i ++) { b = b * 10 + n.charAt(i) - '0'; } b --; } else { for (int i = 0 ; i < n.length() ; i ++) { b = (b * 10 + n.charAt(i) - '0') % phi; } b = b + phi -1 ; b = b + phi; } long ret = ((a - 1) % c + c) % c; while (b > 0) { if((b & 1) == 1) ret = ret * a % c; a = a * a % c; b = b >> 1; } if(ret == 0) ret = ret + c; out.println(ret); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } }
Java
["2 3 3", "2 3 4"]
2 seconds
["1", "4"]
NoteIn both samples there are exactly 4 numbers of length 3 in binary number system. In the first sample Nick writes 3 numbers on the first page and 1 on the second page. In the second sample all the 4 numbers can be written on the first page.
Java 7
standard input
[ "number theory" ]
566adc43d2d6df257c26c5f5495a5745
The only input line contains three space-separated integers b, n and c (2 ≀ b &lt; 10106, 1 ≀ n &lt; 10106, 1 ≀ c ≀ 109). You may consider that Nick has infinite patience, endless amount of paper and representations of digits as characters. The numbers doesn't contain leading zeros.
2,400
In the only line output the amount of numbers written on the same page as the last number.
standard output
PASSED
a4f0d48852d51a4ecc8c7ab7336c48fa
train_004.jsonl
1276182000
Nick is attracted by everything unconventional. He doesn't like decimal number system any more, and he decided to study other number systems. A number system with base b caught his attention. Before he starts studying it, he wants to write in his notepad all the numbers of length n without leading zeros in this number system. Each page in Nick's notepad has enough space for c numbers exactly. Nick writes every suitable number only once, starting with the first clean page and leaving no clean spaces. Nick never writes number 0 as he has unpleasant memories about zero divide.Would you help Nick find out how many numbers will be written on the last page.
64 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws java.lang.Exception { BufferedReader kek = new BufferedReader(new InputStreamReader(System.in)); //Scanner skek = new Scanner(System.in); // PrintWriter outkek = new PrintWriter(System.out); String[] input = kek.readLine().split(" "); char[] B = input[0].toCharArray(), N = input[1].toCharArray(); long C = Integer.parseInt(input[2]); long S = 0, res = 1; for(int i = 0; i < B.length; i++){ S = (S * 10 + B[i] - '0') % C; } int track = N.length - 1; while(N[track]--== '0'){ N[track] = '9'; track--; } long T; for(int i = 0; i < N.length; i++){ T = res; for(int j = 1; j < 10; j++){ res = res * T % C; } for(int j = 0; j < N[i]-'0'; j++){ res = res * S % C; } } res = res * (S + C - 1) % C; if(res == 0){ outkek.println(C); } else { outkek.println(res); } kek.close(); outkek.close(); } }
Java
["2 3 3", "2 3 4"]
2 seconds
["1", "4"]
NoteIn both samples there are exactly 4 numbers of length 3 in binary number system. In the first sample Nick writes 3 numbers on the first page and 1 on the second page. In the second sample all the 4 numbers can be written on the first page.
Java 7
standard input
[ "number theory" ]
566adc43d2d6df257c26c5f5495a5745
The only input line contains three space-separated integers b, n and c (2 ≀ b &lt; 10106, 1 ≀ n &lt; 10106, 1 ≀ c ≀ 109). You may consider that Nick has infinite patience, endless amount of paper and representations of digits as characters. The numbers doesn't contain leading zeros.
2,400
In the only line output the amount of numbers written on the same page as the last number.
standard output
PASSED
0dc9a05c59465ad2ffed6e75857dcea8
train_004.jsonl
1276182000
Nick is attracted by everything unconventional. He doesn't like decimal number system any more, and he decided to study other number systems. A number system with base b caught his attention. Before he starts studying it, he wants to write in his notepad all the numbers of length n without leading zeros in this number system. Each page in Nick's notepad has enough space for c numbers exactly. Nick writes every suitable number only once, starting with the first clean page and leaving no clean spaces. Nick never writes number 0 as he has unpleasant memories about zero divide.Would you help Nick find out how many numbers will be written on the last page.
64 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws java.lang.Exception { BufferedReader kek = new BufferedReader(new InputStreamReader(System.in)); //Scanner skek = new Scanner(System.in); PrintWriter outkek = new PrintWriter(System.out); String[] input = kek.readLine().split(" "); char[] B = input[0].toCharArray(), N = input[1].toCharArray(); long C = Integer.parseInt(input[2]); long S = 0, res = 1; for(int i = 0; i < B.length; i++){ S = (S * 10 + B[i] - '0') % C; } int track = N.length - 1; while(N[track]--== '0'){ N[track] = '9'; track--; } long T; for(int i = 0; i < N.length; i++){ T = res; for(int j = 1; j < 10; j++){ res = res * T % C; } for(int j = 0; j < N[i]-'0'; j++){ res = res * S % C; } } res = res * (S + C - 1) % C; if(res == 0){ outkek.println(C); } else { outkek.println(res); } kek.close(); outkek.close(); } }
Java
["2 3 3", "2 3 4"]
2 seconds
["1", "4"]
NoteIn both samples there are exactly 4 numbers of length 3 in binary number system. In the first sample Nick writes 3 numbers on the first page and 1 on the second page. In the second sample all the 4 numbers can be written on the first page.
Java 7
standard input
[ "number theory" ]
566adc43d2d6df257c26c5f5495a5745
The only input line contains three space-separated integers b, n and c (2 ≀ b &lt; 10106, 1 ≀ n &lt; 10106, 1 ≀ c ≀ 109). You may consider that Nick has infinite patience, endless amount of paper and representations of digits as characters. The numbers doesn't contain leading zeros.
2,400
In the only line output the amount of numbers written on the same page as the last number.
standard output
PASSED
62ddb00d1b152327c520f5d1d3fb5b3e
train_004.jsonl
1581604500
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.In order to lose weight, Bashar is going to run for $$$k$$$ kilometers. Bashar is going to run in a place that looks like a grid of $$$n$$$ rows and $$$m$$$ columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly $$$(4 n m - 2n - 2m)$$$ roads.Let's take, for example, $$$n = 3$$$ and $$$m = 4$$$. In this case, there are $$$34$$$ roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row $$$i$$$ and in the column $$$j$$$, i.e. in the cell $$$(i, j)$$$ he will move to: in the case 'U' to the cell $$$(i-1, j)$$$; in the case 'D' to the cell $$$(i+1, j)$$$; in the case 'L' to the cell $$$(i, j-1)$$$; in the case 'R' to the cell $$$(i, j+1)$$$; He wants to run exactly $$$k$$$ kilometers, so he wants to make exactly $$$k$$$ moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him $$$a$$$ steps to do and since Bashar can't remember too many steps, $$$a$$$ should not exceed $$$3000$$$. In every step, you should give him an integer $$$f$$$ and a string of moves $$$s$$$ of length at most $$$4$$$ which means that he should repeat the moves in the string $$$s$$$ for $$$f$$$ times. He will perform the steps in the order you print them.For example, if the steps are $$$2$$$ RUD, $$$3$$$ UUL then the moves he is going to move are RUD $$$+$$$ RUD $$$+$$$ UUL $$$+$$$ UUL $$$+$$$ UUL $$$=$$$ RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to $$$k$$$ kilometers or say, that it is impossible?
256 megabytes
import java.util.*; import java.io.*; public class Main { static class Scan { private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; public Scan() { in=System.in; } public int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } public int scanInt()throws IOException { int integer=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { integer*=10; integer+=n-'0'; n=scan(); } else throw new InputMismatchException(); } return neg*integer; } public double scanDouble()throws IOException { double doub=0; int n=scan(); while(isWhiteSpace(n)) n=scan(); int neg=1; if(n=='-') { neg=-1; n=scan(); } while(!isWhiteSpace(n)&&n!='.') { if(n>='0'&&n<='9') { doub*=10; doub+=n-'0'; n=scan(); } else throw new InputMismatchException(); } if(n=='.') { n=scan(); double temp=1; while(!isWhiteSpace(n)) { if(n>='0'&&n<='9') { temp/=10; doub+=(n-'0')*temp; n=scan(); } else throw new InputMismatchException(); } } return doub*neg; } public String scanString()throws IOException { StringBuilder sb=new StringBuilder(); int n=scan(); while(isWhiteSpace(n)) n=scan(); while(!isWhiteSpace(n)) { sb.append((char)n); n=scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } } static ArrayList<Integer> adj_lst[]; static boolean vis[]; public static void main(String args[]) throws IOException { Scan input=new Scan(); int n=input.scanInt(); int m=input.scanInt(); int k=input.scanInt(); StringBuilder ans=new StringBuilder(""); int cnt=0; if(n==1) { if(k>=m-1) { ans.append((m-1)+" "+"R\n"); k-=m-1; cnt++; } else if(k>0) { ans.append(k+" "+"R\n"); k-=k; cnt++; } if(k>=m-1) { ans.append((m-1)+" "+"L\n"); k-=m-1; cnt++; } else if(k>0) { ans.append(k+" "+"L\n"); k-=k; cnt++; } if(k!=0) { System.out.println("NO"); return; } System.out.println("YES\n"+cnt+"\n"+ans); return; } if(m==1) { if(k>=n-1) { ans.append((n-1)+" "+"D\n"); k-=n-1; cnt++; } else if(k>0) { ans.append(k+" "+"D\n"); k-=k; cnt++; } if(k>=n-1) { ans.append((n-1)+" "+"U\n"); k-=n-1; cnt++; } else if(k>0) { ans.append(k+" "+"U\n"); k-=k; cnt++; } if(k!=0) { System.out.println("NO"); return; } System.out.println("YES\n"+cnt+"\n"+ans); return; } for(int i=1;i<=m/2;i++) { if(i!=1) { if(k>=1) { if(k>=1) { ans.append(1+" "+"R\n"); k--; cnt++; } } else { break; } } if(k>=n-1) { ans.append(1+" "+"D\n"); k--; cnt++; int tmp_cnt=0; int j=1; boolean br=false; for(j=1;j<=n-2;j++) { if(k<3) { br=true; break; } tmp_cnt++; k-=3; } if(tmp_cnt>0) { ans.append(tmp_cnt+" "+"RLD\n"); cnt++; } if(br && k>0) { if(k==1) { ans.append(1+" "+"R\n"); k--; cnt++; } else if(k==2) { ans.append(1+" "+"RL\n"); k-=2; cnt++; } } } else if(k!=0) { ans.append(k+" "+"D\n"); k-=k; cnt++; } if(i!=1 && k>0) { ans.append(1+" "+"L\n"); k--; cnt++; } if(i!=1 && k>0) { ans.append(1+" "+"R\n"); k--; cnt++; } if(k==0) { break; } if(k>=1) { ans.append(1+" "+"R\n"); k--; cnt++; } if(k==0) { break; } if(m%2==0 && i==m/2) { if(k>=n-1) { cnt++; k-=n-1; ans.append((n-1)+" "+"U\n"); } else if(k!=0){ ans.append(k+" "+"U\n"); k-=k; cnt++; } } else { if(k>=n-1) { ans.append(1+" "+"U\n"); k--; cnt++; int tmp_cnt=0; int j=1; boolean br=false; for(j=1;j<=n-2;j++) { if(k<3) { br=true; break; } tmp_cnt++; k-=3; } if(tmp_cnt>0) { ans.append(tmp_cnt+" "+"RLU\n"); cnt++; } if(br && k>0) { if(k==1) { ans.append(1+" "+"R\n"); k--; cnt++; } else if(k==2) { ans.append(1+" "+"RL\n"); k-=2; cnt++; } } } else if(k!=0){ ans.append(k+" "+"U\n"); k-=k; cnt++; } } if(k==0) { break; } if(k>=n-1) { ans.append((n-1)+" "+"D\n"); k-=n-1; cnt++; } else if(k!=0){ ans.append(k+" "+"D\n"); k-=k; cnt++; } if(k==0) { break; } if(k>=1) { ans.append(1+" "+"L\n"); k--; cnt++; } if(k==0) { break; } if(k>=n-1) { ans.append((n-1)+" "+"U\n"); k-=n-1; cnt++; } else if(k!=0){ ans.append(k+" "+"U\n"); k-=k; cnt++; } if(k==0) { break; } if(k>=1) { ans.append(1+" "+"R\n"); k--; cnt++; } } if(m%2==1) { if(k>=1) { ans.append(1+" "+"R\n"); k--; cnt++; } if(k>=n-1) { ans.append((n-1)+" "+"D\n"); k-=n-1; cnt++; } else if(k>0){ ans.append(k+" "+"D\n"); k-=k; cnt++; } if(k>=1) { ans.append(1+" "+"L\n"); k--; cnt++; } if(k>=1) { ans.append(1+" "+"R\n"); k--; cnt++; } if(k>=n-1) { ans.append((n-1)+" "+"U\n"); k-=n-1; cnt++; } else if(k!=0) { ans.append(k+" "+"U\n"); k-=k; cnt++; } } if(k>=m-1) { ans.append((m-1)+" "+"L\n"); k-=m-1; cnt++; } else if(k!=0) { ans.append(k+" "+"L\n"); k-=k; cnt++; } if(k!=0) { System.out.println("NO"); return; } System.out.println("YES\n"+cnt+"\n"+ans); } }
Java
["3 3 4", "3 3 1000000000", "3 3 8", "4 4 9", "3 4 16"]
1 second
["YES\n2\n2 R\n2 L", "NO", "YES\n3\n2 R\n2 D\n1 LLRR", "YES\n1\n3 RLD", "YES\n8\n3 R\n3 L\n1 D\n3 R\n1 D\n1 U\n3 L\n1 D"]
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run $$$1000000000$$$ kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
Java 11
standard input
[ "constructive algorithms", "implementation", "graphs" ]
a8c5ecf78a5442758441cd7c075b3d7e
The only line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \leq n, m \leq 500$$$, $$$1 \leq k \leq 10 ^{9}$$$), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
2,000
If there is no possible way to run $$$k$$$ kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line. If the answer is "YES", on the second line print an integer $$$a$$$ ($$$1 \leq a \leq 3000$$$)Β β€” the number of steps, then print $$$a$$$ lines describing the steps. To describe a step, print an integer $$$f$$$ ($$$1 \leq f \leq 10^{9}$$$) and a string of moves $$$s$$$ of length at most $$$4$$$. Every character in $$$s$$$ should be 'U', 'D', 'L' or 'R'. Bashar will start from the top-left cell. Make sure to move exactly $$$k$$$ moves without visiting the same road twice and without going outside the grid. He can finish at any cell. We can show that if it is possible to run exactly $$$k$$$ kilometers, then it is possible to describe the path under such output constraints.
standard output
PASSED
8eeec30bd76a0f8ef5e476f80724aa96
train_004.jsonl
1581604500
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.In order to lose weight, Bashar is going to run for $$$k$$$ kilometers. Bashar is going to run in a place that looks like a grid of $$$n$$$ rows and $$$m$$$ columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly $$$(4 n m - 2n - 2m)$$$ roads.Let's take, for example, $$$n = 3$$$ and $$$m = 4$$$. In this case, there are $$$34$$$ roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row $$$i$$$ and in the column $$$j$$$, i.e. in the cell $$$(i, j)$$$ he will move to: in the case 'U' to the cell $$$(i-1, j)$$$; in the case 'D' to the cell $$$(i+1, j)$$$; in the case 'L' to the cell $$$(i, j-1)$$$; in the case 'R' to the cell $$$(i, j+1)$$$; He wants to run exactly $$$k$$$ kilometers, so he wants to make exactly $$$k$$$ moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him $$$a$$$ steps to do and since Bashar can't remember too many steps, $$$a$$$ should not exceed $$$3000$$$. In every step, you should give him an integer $$$f$$$ and a string of moves $$$s$$$ of length at most $$$4$$$ which means that he should repeat the moves in the string $$$s$$$ for $$$f$$$ times. He will perform the steps in the order you print them.For example, if the steps are $$$2$$$ RUD, $$$3$$$ UUL then the moves he is going to move are RUD $$$+$$$ RUD $$$+$$$ UUL $$$+$$$ UUL $$$+$$$ UUL $$$=$$$ RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to $$$k$$$ kilometers or say, that it is impossible?
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { FastReader scan = new FastReader(); //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("taming.out"))); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); Task solver = new Task(); //int t = scan.nextInt(); int t = 1; for(int i = 1; i <= t; i++) solver.solve(i, scan, out); out.close(); } static class Task { public void solve(int testNumber, FastReader sc, PrintWriter pw) { int n =sc.nextInt(); int m = sc.nextInt(); int c =sc.nextInt(); if(4*n*m-2*n-2*m<c){ pw.println("NO"); return; } ArrayList<tup> arr = new ArrayList<tup>(); if(m>1){ arr.add(new tup(m-1,"R")); arr.add(new tup(m-1,"L")); } for(int i=0;i<n-1;i++){ arr.add(new tup(1,"D")); if(m>1){ arr.add(new tup(m-1,"R")); arr.add(new tup(m-1,"UDL")); } } if(n>0){ arr.add(new tup(n-1,"U")); } int z = 0; StringBuilder sb = new StringBuilder(); for(tup x : arr){ if(x.a*x.b.length()>c){ if(c>=x.b.length()){ z++; sb.append(c/x.b.length()+" "+x.b+"\n"); c-=c/x.b.length()*x.b.length(); } if(c>0){ z++; sb.append(1+" "+x.b.substring(0,c)+"\n"); c=0; } } else{ z++; sb.append(x.a+" "+x.b+"\n"); c-=x.a*x.b.length(); } if(c<=0)break; } pw.println("YES"); pw.println(z); pw.println(sb); } } static class tup{ int a;String b; tup(){}; tup(int a, String b){ this.a=a; this.b=b; } } static class bit { int n; int[] bit; public bit(int n) { this.n=n; bit=new int[n+1]; } void add(int ind, int c) { for(; ind<n;ind|=(ind+1)) { bit[ind]=Math.max(bit[ind],c); } } int getMax(int r) { int ret = Integer.MIN_VALUE; for (; r >= 0; r = (r & (r + 1)) - 1) ret = Math.max(ret, bit[r]); return ret; } } static void shuffle(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffle(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } 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 3 4", "3 3 1000000000", "3 3 8", "4 4 9", "3 4 16"]
1 second
["YES\n2\n2 R\n2 L", "NO", "YES\n3\n2 R\n2 D\n1 LLRR", "YES\n1\n3 RLD", "YES\n8\n3 R\n3 L\n1 D\n3 R\n1 D\n1 U\n3 L\n1 D"]
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run $$$1000000000$$$ kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
Java 11
standard input
[ "constructive algorithms", "implementation", "graphs" ]
a8c5ecf78a5442758441cd7c075b3d7e
The only line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \leq n, m \leq 500$$$, $$$1 \leq k \leq 10 ^{9}$$$), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
2,000
If there is no possible way to run $$$k$$$ kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line. If the answer is "YES", on the second line print an integer $$$a$$$ ($$$1 \leq a \leq 3000$$$)Β β€” the number of steps, then print $$$a$$$ lines describing the steps. To describe a step, print an integer $$$f$$$ ($$$1 \leq f \leq 10^{9}$$$) and a string of moves $$$s$$$ of length at most $$$4$$$. Every character in $$$s$$$ should be 'U', 'D', 'L' or 'R'. Bashar will start from the top-left cell. Make sure to move exactly $$$k$$$ moves without visiting the same road twice and without going outside the grid. He can finish at any cell. We can show that if it is possible to run exactly $$$k$$$ kilometers, then it is possible to describe the path under such output constraints.
standard output
PASSED
ac837a0e1123081f8dcc2913bbb8a7eb
train_004.jsonl
1581604500
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.In order to lose weight, Bashar is going to run for $$$k$$$ kilometers. Bashar is going to run in a place that looks like a grid of $$$n$$$ rows and $$$m$$$ columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly $$$(4 n m - 2n - 2m)$$$ roads.Let's take, for example, $$$n = 3$$$ and $$$m = 4$$$. In this case, there are $$$34$$$ roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row $$$i$$$ and in the column $$$j$$$, i.e. in the cell $$$(i, j)$$$ he will move to: in the case 'U' to the cell $$$(i-1, j)$$$; in the case 'D' to the cell $$$(i+1, j)$$$; in the case 'L' to the cell $$$(i, j-1)$$$; in the case 'R' to the cell $$$(i, j+1)$$$; He wants to run exactly $$$k$$$ kilometers, so he wants to make exactly $$$k$$$ moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him $$$a$$$ steps to do and since Bashar can't remember too many steps, $$$a$$$ should not exceed $$$3000$$$. In every step, you should give him an integer $$$f$$$ and a string of moves $$$s$$$ of length at most $$$4$$$ which means that he should repeat the moves in the string $$$s$$$ for $$$f$$$ times. He will perform the steps in the order you print them.For example, if the steps are $$$2$$$ RUD, $$$3$$$ UUL then the moves he is going to move are RUD $$$+$$$ RUD $$$+$$$ UUL $$$+$$$ UUL $$$+$$$ UUL $$$=$$$ RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to $$$k$$$ kilometers or say, that it is impossible?
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class f { public static void print(String str,int val){ System.out.println(str+" "+val); } public long gcd(long a, long b) { if (b==0L) return a; return gcd(b,a%b); } public static void debug(long[][] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.println(Arrays.toString(arr[i])); } } public static void debug(int[][] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.println(Arrays.toString(arr[i])); } } public static void debug(String[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.println(arr[i]); } } public static void print(int[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.print(arr[i]+" "); } System.out.print('\n'); } public static void print(String[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.print(arr[i]+" "); } System.out.print('\n'); } public static void print(long[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.print(arr[i]+" "); } System.out.print('\n'); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String path) throws FileNotFoundException { br = new BufferedReader(new FileReader(path)); } 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; } } public static void main(String[] args) { FastReader s=new FastReader(); // int t = s.nextInt(); // for(int tt=0;tt<t;tt++){ int n = s.nextInt(); int m = s.nextInt(); int k = s.nextInt(); solve(n,m,k) ; } static void print(ArrayList<String> list){ System.out.println(list.size()); for(String s:list){ System.out.println(s); } } static void solve(long n,long m,long k){ if(k>(4*n*m - 2*n-2*m)){ System.out.println("NO"); return ; } ArrayList<String> list = new ArrayList<>(); System.out.println("YES"); for(int i=0;i<n-1;i++){ if(k==0){ print(list); return; } //frontwards if(k>=(m-1)){ if((m-1)!=0) list.add((m-1)+" R"); k-=(m-1); } else { list.add(k+" R"); print(list); return; } if(k==0){ print(list); return; } //backwards if(k>=3*(m-1)){ if((m-1)!=0) list.add((m-1)+" DUL"); k-=(3*(m-1)); } else { long n_times = k/3; if(n_times!=0){ list.add(n_times+" DUL"); } int rem = (int)(k%3); if(rem==1){ list.add(1+" D"); } if(rem==2){ list.add(1+" DU"); } print(list); return; } if(k==0){ print(list); return; } if(k>=1){ list.add(1+" D"); k--; } } //now one down and (m-1) right if(k==0){ print(list); return; } if(k>=(m-1)){ if((m-1)!=0) list.add((m-1)+" R"); k-=(m-1); } else { list.add((k)+" R"); print(list); return; } if(k==0){ print(list); return; } if(k>=(m-1)){ if((m-1)!=0) list.add((m-1)+" L"); k-=(m-1); } else { list.add((k)+" L"); print(list); return; } if(k==0){ print(list); return; } list.add(k+" U"); print(list); } // OutputStream out = new BufferedOutputStream( System.out ); // for(int i=1;i<n;i++){ // out.write((arr[i]+" ").getBytes()); // } // out.flush(); // long start_time = System.currentTimeMillis(); // long end_time = System.currentTimeMillis(); // System.out.println((end_time - start_time) + "ms"); }
Java
["3 3 4", "3 3 1000000000", "3 3 8", "4 4 9", "3 4 16"]
1 second
["YES\n2\n2 R\n2 L", "NO", "YES\n3\n2 R\n2 D\n1 LLRR", "YES\n1\n3 RLD", "YES\n8\n3 R\n3 L\n1 D\n3 R\n1 D\n1 U\n3 L\n1 D"]
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run $$$1000000000$$$ kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
Java 11
standard input
[ "constructive algorithms", "implementation", "graphs" ]
a8c5ecf78a5442758441cd7c075b3d7e
The only line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \leq n, m \leq 500$$$, $$$1 \leq k \leq 10 ^{9}$$$), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
2,000
If there is no possible way to run $$$k$$$ kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line. If the answer is "YES", on the second line print an integer $$$a$$$ ($$$1 \leq a \leq 3000$$$)Β β€” the number of steps, then print $$$a$$$ lines describing the steps. To describe a step, print an integer $$$f$$$ ($$$1 \leq f \leq 10^{9}$$$) and a string of moves $$$s$$$ of length at most $$$4$$$. Every character in $$$s$$$ should be 'U', 'D', 'L' or 'R'. Bashar will start from the top-left cell. Make sure to move exactly $$$k$$$ moves without visiting the same road twice and without going outside the grid. He can finish at any cell. We can show that if it is possible to run exactly $$$k$$$ kilometers, then it is possible to describe the path under such output constraints.
standard output
PASSED
45b65d67c12351e7c9d6aaf96379deb1
train_004.jsonl
1581604500
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.In order to lose weight, Bashar is going to run for $$$k$$$ kilometers. Bashar is going to run in a place that looks like a grid of $$$n$$$ rows and $$$m$$$ columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly $$$(4 n m - 2n - 2m)$$$ roads.Let's take, for example, $$$n = 3$$$ and $$$m = 4$$$. In this case, there are $$$34$$$ roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row $$$i$$$ and in the column $$$j$$$, i.e. in the cell $$$(i, j)$$$ he will move to: in the case 'U' to the cell $$$(i-1, j)$$$; in the case 'D' to the cell $$$(i+1, j)$$$; in the case 'L' to the cell $$$(i, j-1)$$$; in the case 'R' to the cell $$$(i, j+1)$$$; He wants to run exactly $$$k$$$ kilometers, so he wants to make exactly $$$k$$$ moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him $$$a$$$ steps to do and since Bashar can't remember too many steps, $$$a$$$ should not exceed $$$3000$$$. In every step, you should give him an integer $$$f$$$ and a string of moves $$$s$$$ of length at most $$$4$$$ which means that he should repeat the moves in the string $$$s$$$ for $$$f$$$ times. He will perform the steps in the order you print them.For example, if the steps are $$$2$$$ RUD, $$$3$$$ UUL then the moves he is going to move are RUD $$$+$$$ RUD $$$+$$$ UUL $$$+$$$ UUL $$$+$$$ UUL $$$=$$$ RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to $$$k$$$ kilometers or say, that it is impossible?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * 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; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); if (k > (4 * n * m - 2 * n - 2 * m)) { out.println("NO"); return; } out.println("YES"); int cr = 0, st = 0; StringBuilder sb = new StringBuilder(); if (n == 1) { if (k < m) { out.println("1\n" + k + " R"); } out.println("2\n" + (m - 1) + " R"); out.println(k - (m - 1) + " L"); return; } if (k < n) { out.println(1); out.println(k + " D\n"); return; } sb.append((n - 1) + " D\n"); if (k <= 2 * (n - 1)) { out.println(2); out.println((n - 1) + " D"); out.println(k - n + 1 + " U"); return; } sb.append((n - 1) + " U\n"); k -= 2 * (n - 1); st = 2; for (int i = 1; i < m; ++i) { if (3 * (n - 1) >= k) { if (k / 3 > 0) { sb.append(k / 3 + " RDL\n"); st += 1; k -= k / 3 * 3; } if (k > 0) { st++; k--; sb.append("1 R\n"); } if (k > 0) { st++; k--; sb.append("1 D\n"); } break; } st++; sb.append((n - 1) + " RDL\n"); k -= 3 * (n - 1); st++; k--; sb.append("1 R\n"); if (k == 0) { break; } st++; if (k < n) { sb.append(k + " U\n"); k = 0; break; } sb.append(n - 1 + " U\n"); k -= n - 1; } if (k > 0) { st++; sb.append(k + " L\n"); } out.println(st); out.println(sb.toString()); } } }
Java
["3 3 4", "3 3 1000000000", "3 3 8", "4 4 9", "3 4 16"]
1 second
["YES\n2\n2 R\n2 L", "NO", "YES\n3\n2 R\n2 D\n1 LLRR", "YES\n1\n3 RLD", "YES\n8\n3 R\n3 L\n1 D\n3 R\n1 D\n1 U\n3 L\n1 D"]
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run $$$1000000000$$$ kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
Java 11
standard input
[ "constructive algorithms", "implementation", "graphs" ]
a8c5ecf78a5442758441cd7c075b3d7e
The only line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \leq n, m \leq 500$$$, $$$1 \leq k \leq 10 ^{9}$$$), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
2,000
If there is no possible way to run $$$k$$$ kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line. If the answer is "YES", on the second line print an integer $$$a$$$ ($$$1 \leq a \leq 3000$$$)Β β€” the number of steps, then print $$$a$$$ lines describing the steps. To describe a step, print an integer $$$f$$$ ($$$1 \leq f \leq 10^{9}$$$) and a string of moves $$$s$$$ of length at most $$$4$$$. Every character in $$$s$$$ should be 'U', 'D', 'L' or 'R'. Bashar will start from the top-left cell. Make sure to move exactly $$$k$$$ moves without visiting the same road twice and without going outside the grid. He can finish at any cell. We can show that if it is possible to run exactly $$$k$$$ kilometers, then it is possible to describe the path under such output constraints.
standard output
PASSED
6d7a13103ab2d211ac687bd76488cbce
train_004.jsonl
1581604500
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.In order to lose weight, Bashar is going to run for $$$k$$$ kilometers. Bashar is going to run in a place that looks like a grid of $$$n$$$ rows and $$$m$$$ columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly $$$(4 n m - 2n - 2m)$$$ roads.Let's take, for example, $$$n = 3$$$ and $$$m = 4$$$. In this case, there are $$$34$$$ roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row $$$i$$$ and in the column $$$j$$$, i.e. in the cell $$$(i, j)$$$ he will move to: in the case 'U' to the cell $$$(i-1, j)$$$; in the case 'D' to the cell $$$(i+1, j)$$$; in the case 'L' to the cell $$$(i, j-1)$$$; in the case 'R' to the cell $$$(i, j+1)$$$; He wants to run exactly $$$k$$$ kilometers, so he wants to make exactly $$$k$$$ moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him $$$a$$$ steps to do and since Bashar can't remember too many steps, $$$a$$$ should not exceed $$$3000$$$. In every step, you should give him an integer $$$f$$$ and a string of moves $$$s$$$ of length at most $$$4$$$ which means that he should repeat the moves in the string $$$s$$$ for $$$f$$$ times. He will perform the steps in the order you print them.For example, if the steps are $$$2$$$ RUD, $$$3$$$ UUL then the moves he is going to move are RUD $$$+$$$ RUD $$$+$$$ UUL $$$+$$$ UUL $$$+$$$ UUL $$$=$$$ RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to $$$k$$$ kilometers or say, that it is impossible?
256 megabytes
/** * @author derrick20 */ import java.io.*; import java.util.*; public class TimeToRun { public static void main(String[] args) throws Exception { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int N = sc.nextInt(); int M = sc.nextInt(); int K = sc.nextInt(); if (K > 4 * M * N - 2 * M - 2 * N) { out.println("NO"); } else { ArrayList<Integer> f = new ArrayList<>(); ArrayList<Character> dir = new ArrayList<>(); for (int i = 0; i < M - 1; i++) { if (N > 1) { f.add(N - 1); dir.add('D'); f.add(N - 1); dir.add('U'); } f.add(1); dir.add('R'); } for (int i = 0; i < N - 1; i++) { f.add(1); dir.add('D'); if (M > 1) { f.add(M - 1); dir.add('L'); f.add(M - 1); dir.add('R'); } } if (N > 1) { f.add(N - 1); dir.add('U'); } if (M > 1) { f.add(M - 1); dir.add('L'); } int steps = 0; int ptr = 0; ArrayList<Integer> ansSteps = new ArrayList<>(); ArrayList<Character> ansDir = new ArrayList<>(); while (ptr < f.size() && steps + f.get(ptr) <= K) { steps += f.get(ptr); ansSteps.add(f.get(ptr)); ansDir.add(dir.get(ptr)); ptr++; } if (steps < K) { ansSteps.add(K - steps); ansDir.add(dir.get(ptr)); } out.println("YES"); out.println(ansSteps.size()); for (int i = 0; i < ansSteps.size(); i++) { out.println(ansSteps.get(i) + " " + ansDir.get(i)); } } out.close(); } static class FastScanner { private int BS = 1<<16; private char NC = (char)0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private 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 int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } 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 3 4", "3 3 1000000000", "3 3 8", "4 4 9", "3 4 16"]
1 second
["YES\n2\n2 R\n2 L", "NO", "YES\n3\n2 R\n2 D\n1 LLRR", "YES\n1\n3 RLD", "YES\n8\n3 R\n3 L\n1 D\n3 R\n1 D\n1 U\n3 L\n1 D"]
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run $$$1000000000$$$ kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
Java 11
standard input
[ "constructive algorithms", "implementation", "graphs" ]
a8c5ecf78a5442758441cd7c075b3d7e
The only line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \leq n, m \leq 500$$$, $$$1 \leq k \leq 10 ^{9}$$$), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
2,000
If there is no possible way to run $$$k$$$ kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line. If the answer is "YES", on the second line print an integer $$$a$$$ ($$$1 \leq a \leq 3000$$$)Β β€” the number of steps, then print $$$a$$$ lines describing the steps. To describe a step, print an integer $$$f$$$ ($$$1 \leq f \leq 10^{9}$$$) and a string of moves $$$s$$$ of length at most $$$4$$$. Every character in $$$s$$$ should be 'U', 'D', 'L' or 'R'. Bashar will start from the top-left cell. Make sure to move exactly $$$k$$$ moves without visiting the same road twice and without going outside the grid. He can finish at any cell. We can show that if it is possible to run exactly $$$k$$$ kilometers, then it is possible to describe the path under such output constraints.
standard output
PASSED
0c9f8ddfdfc6c169f4499a9b5d6e49ea
train_004.jsonl
1581604500
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.In order to lose weight, Bashar is going to run for $$$k$$$ kilometers. Bashar is going to run in a place that looks like a grid of $$$n$$$ rows and $$$m$$$ columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly $$$(4 n m - 2n - 2m)$$$ roads.Let's take, for example, $$$n = 3$$$ and $$$m = 4$$$. In this case, there are $$$34$$$ roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row $$$i$$$ and in the column $$$j$$$, i.e. in the cell $$$(i, j)$$$ he will move to: in the case 'U' to the cell $$$(i-1, j)$$$; in the case 'D' to the cell $$$(i+1, j)$$$; in the case 'L' to the cell $$$(i, j-1)$$$; in the case 'R' to the cell $$$(i, j+1)$$$; He wants to run exactly $$$k$$$ kilometers, so he wants to make exactly $$$k$$$ moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him $$$a$$$ steps to do and since Bashar can't remember too many steps, $$$a$$$ should not exceed $$$3000$$$. In every step, you should give him an integer $$$f$$$ and a string of moves $$$s$$$ of length at most $$$4$$$ which means that he should repeat the moves in the string $$$s$$$ for $$$f$$$ times. He will perform the steps in the order you print them.For example, if the steps are $$$2$$$ RUD, $$$3$$$ UUL then the moves he is going to move are RUD $$$+$$$ RUD $$$+$$$ UUL $$$+$$$ UUL $$$+$$$ UUL $$$=$$$ RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to $$$k$$$ kilometers or say, that it is impossible?
256 megabytes
import java.io.*; import java.util.*; public class CF1301D extends PrintWriter { CF1301D() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1301D o = new CF1301D(); o.main(); o.flush(); } int[] oo, oj; int __ = 1; int[] ae; int link(int o, int j) { oo[__] = o; oj[__] = j; return __++; } int node(int j) { oj[__] = j; return __++; } void init(int n, int m) { oo = new int[1 + m]; oj = new int[1 + m]; ae = new int[n]; } int get(int i) { int o = ae[i]; ae[i] = oo[o]; return o == 0 ? -1 : oj[o]; } int extend(int p, int j) { while ((j = get(j)) != -1) p = oo[p] = node(j); return p; } void main() { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int n_ = n * m, m_ = 2 * (n * (m - 1) + m * (n - 1)); if (k > m_) { println("NO"); return; } init(n_, m_ + 1 + m_); for (int i = 1; i < n; i++) for (int j = 0; j < m; j++) { int u = (i - 1) * m + j; int v = i * m + j; ae[u] = link(ae[u], v); ae[v] = link(ae[v], u); } for (int j = 1; j < m; j++) for (int i = 0; i < n; i++) { int u = i * m + j - 1; int v = i * m + j; ae[u] = link(ae[u], v); ae[v] = link(ae[v], u); } int p_ = node(0); extend(p_, 0); for (int p = p_; p != 0; p = oo[p]) { int q = oo[p], j = oj[p]; oo[extend(p, j)] = q; } int[] kk = new int[k]; char[] dd = new char[k]; int k_ = 0; for (int p = oo[p_], u = 0; p != 0 && k-- > 0; p = oo[p]) { int v = oj[p]; int ui = u / m, uj = u % m; int vi = v / m, vj = v % m; char d; if (vi == ui - 1) d = 'U'; else if (vi == ui + 1) d = 'D'; else if (vj == uj - 1) d = 'L'; else d = 'R'; dd[k_++] = d; u = v; } k = 1; kk[0] = 1; for (int h = 1; h < k_; h++) { if (dd[k - 1] == dd[h]) kk[k - 1]++; else { kk[k] = 1; dd[k] = dd[h]; k++; } } println("YES"); println(k); for (int h = 0; h < k; h++) println(kk[h] + " " + dd[h]); } }
Java
["3 3 4", "3 3 1000000000", "3 3 8", "4 4 9", "3 4 16"]
1 second
["YES\n2\n2 R\n2 L", "NO", "YES\n3\n2 R\n2 D\n1 LLRR", "YES\n1\n3 RLD", "YES\n8\n3 R\n3 L\n1 D\n3 R\n1 D\n1 U\n3 L\n1 D"]
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run $$$1000000000$$$ kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
Java 11
standard input
[ "constructive algorithms", "implementation", "graphs" ]
a8c5ecf78a5442758441cd7c075b3d7e
The only line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \leq n, m \leq 500$$$, $$$1 \leq k \leq 10 ^{9}$$$), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
2,000
If there is no possible way to run $$$k$$$ kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line. If the answer is "YES", on the second line print an integer $$$a$$$ ($$$1 \leq a \leq 3000$$$)Β β€” the number of steps, then print $$$a$$$ lines describing the steps. To describe a step, print an integer $$$f$$$ ($$$1 \leq f \leq 10^{9}$$$) and a string of moves $$$s$$$ of length at most $$$4$$$. Every character in $$$s$$$ should be 'U', 'D', 'L' or 'R'. Bashar will start from the top-left cell. Make sure to move exactly $$$k$$$ moves without visiting the same road twice and without going outside the grid. He can finish at any cell. We can show that if it is possible to run exactly $$$k$$$ kilometers, then it is possible to describe the path under such output constraints.
standard output
PASSED
02fcb3abe39fc644bebaaa2e9f0cfc43
train_004.jsonl
1581604500
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.In order to lose weight, Bashar is going to run for $$$k$$$ kilometers. Bashar is going to run in a place that looks like a grid of $$$n$$$ rows and $$$m$$$ columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly $$$(4 n m - 2n - 2m)$$$ roads.Let's take, for example, $$$n = 3$$$ and $$$m = 4$$$. In this case, there are $$$34$$$ roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row $$$i$$$ and in the column $$$j$$$, i.e. in the cell $$$(i, j)$$$ he will move to: in the case 'U' to the cell $$$(i-1, j)$$$; in the case 'D' to the cell $$$(i+1, j)$$$; in the case 'L' to the cell $$$(i, j-1)$$$; in the case 'R' to the cell $$$(i, j+1)$$$; He wants to run exactly $$$k$$$ kilometers, so he wants to make exactly $$$k$$$ moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him $$$a$$$ steps to do and since Bashar can't remember too many steps, $$$a$$$ should not exceed $$$3000$$$. In every step, you should give him an integer $$$f$$$ and a string of moves $$$s$$$ of length at most $$$4$$$ which means that he should repeat the moves in the string $$$s$$$ for $$$f$$$ times. He will perform the steps in the order you print them.For example, if the steps are $$$2$$$ RUD, $$$3$$$ UUL then the moves he is going to move are RUD $$$+$$$ RUD $$$+$$$ UUL $$$+$$$ UUL $$$+$$$ UUL $$$=$$$ RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to $$$k$$$ kilometers or say, that it is impossible?
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 n=sc.nextInt(),m=sc.nextInt(),k=sc.nextInt(); if(k>4*n*m-2*n-2*m) { pw.println("NO"); pw.flush(); return; } pw.println("YES"); if(m==1) { int c=0; StringBuilder ans=new StringBuilder(); for(int i=0;i<n-1 && k>0;i++) { ans.append(1+" D"); ans.append('\n');c++; k--; } for(int i=0;i<n-1 && k>0;i++) { ans.append(1+" U"); ans.append('\n');c++; k--; } pw.println(c); pw.print(ans); pw.flush(); return; } int c=0; StringBuilder ans=new StringBuilder(); if(k<=(m-1)*2) { for(int i=0;i<m-1 && k>0;i++) { ans.append(1+" R"); ans.append('\n');c++; k--; } for(int i=0;i<m-1 && k>0;i++) { ans.append(1+" L"); ans.append('\n');c++; k--; } } else { ans.append((m-1)+" R"); ans.append('\n');c++; ans.append((m-1)+" L"); ans.append('\n');c++; k-=2*(m-1); if(k>0) { ans.append(1+" D");ans.append('\n');k--;c++; } int curx=1; while(curx<n && k>0) { if(3*(m-1)>k) { if(k>=3) { ans.append((k/3)+" RUD");ans.append('\n');c++; k=k%3; } if(k==1) { ans.append(1+" R");ans.append('\n');c++; } else { if(k==2) { ans.append(1+" RU");ans.append('\n');c++; } } k=0; } else { k-=3*(m-1); ans.append((m-1)+" RUD");ans.append('\n');c++; } if(k==0)break; if(m-1>k) { ans.append(k+" L");ans.append('\n');c++; k=0; } else { k-=(m-1); ans.append((m-1)+" L");ans.append('\n');c++; } if(k>0 && curx!=n-1) { ans.append(1+" D");ans.append('\n');k--;c++; } curx++; } for(int i=0;i<n-1 && k>0;i++) { ans.append(1+" U");ans.append('\n');k--;c++; } } pw.println(c); pw.print(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
["3 3 4", "3 3 1000000000", "3 3 8", "4 4 9", "3 4 16"]
1 second
["YES\n2\n2 R\n2 L", "NO", "YES\n3\n2 R\n2 D\n1 LLRR", "YES\n1\n3 RLD", "YES\n8\n3 R\n3 L\n1 D\n3 R\n1 D\n1 U\n3 L\n1 D"]
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run $$$1000000000$$$ kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
Java 11
standard input
[ "constructive algorithms", "implementation", "graphs" ]
a8c5ecf78a5442758441cd7c075b3d7e
The only line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \leq n, m \leq 500$$$, $$$1 \leq k \leq 10 ^{9}$$$), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
2,000
If there is no possible way to run $$$k$$$ kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line. If the answer is "YES", on the second line print an integer $$$a$$$ ($$$1 \leq a \leq 3000$$$)Β β€” the number of steps, then print $$$a$$$ lines describing the steps. To describe a step, print an integer $$$f$$$ ($$$1 \leq f \leq 10^{9}$$$) and a string of moves $$$s$$$ of length at most $$$4$$$. Every character in $$$s$$$ should be 'U', 'D', 'L' or 'R'. Bashar will start from the top-left cell. Make sure to move exactly $$$k$$$ moves without visiting the same road twice and without going outside the grid. He can finish at any cell. We can show that if it is possible to run exactly $$$k$$$ kilometers, then it is possible to describe the path under such output constraints.
standard output
PASSED
080a01183263af509ec1dbb9163a865f
train_004.jsonl
1581604500
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.In order to lose weight, Bashar is going to run for $$$k$$$ kilometers. Bashar is going to run in a place that looks like a grid of $$$n$$$ rows and $$$m$$$ columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly $$$(4 n m - 2n - 2m)$$$ roads.Let's take, for example, $$$n = 3$$$ and $$$m = 4$$$. In this case, there are $$$34$$$ roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row $$$i$$$ and in the column $$$j$$$, i.e. in the cell $$$(i, j)$$$ he will move to: in the case 'U' to the cell $$$(i-1, j)$$$; in the case 'D' to the cell $$$(i+1, j)$$$; in the case 'L' to the cell $$$(i, j-1)$$$; in the case 'R' to the cell $$$(i, j+1)$$$; He wants to run exactly $$$k$$$ kilometers, so he wants to make exactly $$$k$$$ moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him $$$a$$$ steps to do and since Bashar can't remember too many steps, $$$a$$$ should not exceed $$$3000$$$. In every step, you should give him an integer $$$f$$$ and a string of moves $$$s$$$ of length at most $$$4$$$ which means that he should repeat the moves in the string $$$s$$$ for $$$f$$$ times. He will perform the steps in the order you print them.For example, if the steps are $$$2$$$ RUD, $$$3$$$ UUL then the moves he is going to move are RUD $$$+$$$ RUD $$$+$$$ UUL $$$+$$$ UUL $$$+$$$ UUL $$$=$$$ RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to $$$k$$$ kilometers or say, that it is impossible?
256 megabytes
import java.io.*; import java.util.*; public class HelloWorld{ static class Step{ long no; String comm; Step(long no, String comm){ this.no = no; this.comm = comm; } } private static ArrayList<Step> ls; private static long k; private static void check(){ if(k > 0) return; PrintWriter pw = new PrintWriter(System.out); pw.println("YES"); pw.println(ls.size()); for(Step step : ls) pw.println(+step.no+" "+step.comm); pw.flush(); pw.close(); System.exit(0); } private static void addStep(long no, String comm){ if(no == 0 || comm.length() == 0) return; Step ns = new Step(no, comm); ls.add(ns); k -= no*comm.length(); check(); //System.out.println(+k); } public static void main(String []args){ Scanner sc = new Scanner(System.in); int r = sc.nextInt(), c = sc.nextInt(); k = sc.nextLong(); long max = 4*r*c-2*r-2*c; if(k > max){ System.out.println("NO"); System.exit(0); } ls = new ArrayList<>(); for(int i=0; i<r; i++){ String sdir = (i%2 == 0)?"R":"L"; long lim = Math.min(k, c-1); //System.out.println(+lim+" "+sdir); addStep(lim, sdir); if(i != r-1) addStep(1, "D"); } for(int i=0; i<r-1; i++){ String sdir = ((i+r)%2 == 1)?"UDL":"UDR"; long lim = Math.min(k, 3*(c-1)); addStep(lim/3, sdir); addStep(1, sdir.substring(0, (int)(lim%3))); addStep(1, "U"); } addStep(k, "L"); } }
Java
["3 3 4", "3 3 1000000000", "3 3 8", "4 4 9", "3 4 16"]
1 second
["YES\n2\n2 R\n2 L", "NO", "YES\n3\n2 R\n2 D\n1 LLRR", "YES\n1\n3 RLD", "YES\n8\n3 R\n3 L\n1 D\n3 R\n1 D\n1 U\n3 L\n1 D"]
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run $$$1000000000$$$ kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
Java 11
standard input
[ "constructive algorithms", "implementation", "graphs" ]
a8c5ecf78a5442758441cd7c075b3d7e
The only line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \leq n, m \leq 500$$$, $$$1 \leq k \leq 10 ^{9}$$$), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
2,000
If there is no possible way to run $$$k$$$ kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line. If the answer is "YES", on the second line print an integer $$$a$$$ ($$$1 \leq a \leq 3000$$$)Β β€” the number of steps, then print $$$a$$$ lines describing the steps. To describe a step, print an integer $$$f$$$ ($$$1 \leq f \leq 10^{9}$$$) and a string of moves $$$s$$$ of length at most $$$4$$$. Every character in $$$s$$$ should be 'U', 'D', 'L' or 'R'. Bashar will start from the top-left cell. Make sure to move exactly $$$k$$$ moves without visiting the same road twice and without going outside the grid. He can finish at any cell. We can show that if it is possible to run exactly $$$k$$$ kilometers, then it is possible to describe the path under such output constraints.
standard output
PASSED
dbe9bd0adfe5536d2f9619ef9d28c6df
train_004.jsonl
1581604500
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.In order to lose weight, Bashar is going to run for $$$k$$$ kilometers. Bashar is going to run in a place that looks like a grid of $$$n$$$ rows and $$$m$$$ columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly $$$(4 n m - 2n - 2m)$$$ roads.Let's take, for example, $$$n = 3$$$ and $$$m = 4$$$. In this case, there are $$$34$$$ roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row $$$i$$$ and in the column $$$j$$$, i.e. in the cell $$$(i, j)$$$ he will move to: in the case 'U' to the cell $$$(i-1, j)$$$; in the case 'D' to the cell $$$(i+1, j)$$$; in the case 'L' to the cell $$$(i, j-1)$$$; in the case 'R' to the cell $$$(i, j+1)$$$; He wants to run exactly $$$k$$$ kilometers, so he wants to make exactly $$$k$$$ moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him $$$a$$$ steps to do and since Bashar can't remember too many steps, $$$a$$$ should not exceed $$$3000$$$. In every step, you should give him an integer $$$f$$$ and a string of moves $$$s$$$ of length at most $$$4$$$ which means that he should repeat the moves in the string $$$s$$$ for $$$f$$$ times. He will perform the steps in the order you print them.For example, if the steps are $$$2$$$ RUD, $$$3$$$ UUL then the moves he is going to move are RUD $$$+$$$ RUD $$$+$$$ UUL $$$+$$$ UUL $$$+$$$ UUL $$$=$$$ RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to $$$k$$$ kilometers or say, that it is impossible?
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1301d { public static void main(String[] args) throws IOException { int n = rni(), m = ni(), k = ni(); if (k > 4 * n * m - 2 * n - 2 * m) { prN(); } else { prY(); List<step> ans = new ArrayList<>(); if (m > 1) { if (k > m - 1) { ans.add(new step(m - 1, "R")); k -= m - 1; } else if(k > 0) { ans.add(new step(k, "R")); k = 0; } if (k > m - 1) { ans.add(new step(m - 1, "L")); k -= m - 1; } else if(k > 0) { ans.add(new step(k, "L")); k = 0; } } if (k >= 1) { ans.add(new step(1, "D")); k -= 1; } for (int i = 1; i < n; ++i) { if (m > 1) { if (k > 3 * (m - 1)) { ans.add(new step(m - 1, "RUD")); k -= 3 * (m - 1); } else { if (k > 3) { ans.add(new step(k / 3, "RUD")); k %= 3; } if (k > 0) { ans.add(new step(1, "RUD".substring(0, k))); k = 0; } } if (k > m - 1) { ans.add(new step(m - 1, "L")); k -= m - 1; } else if (k > 0) { ans.add(new step(k, "L")); k = 0; } } if (i < n - 1 && k >= 1) { ans.add(new step(1, "D")); k -= 1; } } if (k > n - 1) { assert false; ans.add(new step(n - 1, "U")); k -= n - 1; } else if (k > 0) { ans.add(new step(k, "U")); } prln(ans.size()); for (step s : ans) { pr(s.n); pr(' '); prln(s.op); } } close(); } static class step { int n; String op; step(int n_, String op_) { n = n_; op = op_; } } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int)d;} static int cei(double d) {return (int)ceil(d);} static long fll(double d) {return (long)d;} static long cel(double d) {return (long)ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int lcm(int a, int b) {return a * b / gcf(a, b);} static long lcm(long a, long b) {return a * b / gcf(a, b);} static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // graph util static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;} static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;} static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);} static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);} static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);} static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for(int i = 0; i < n; ++i) a[i] = ni(); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for(int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for(int i = 0; i < n; ++i) a[i] = nl(); return a;} static char[] rcha() throws IOException {return rline().toCharArray();} static String rline() throws IOException {return __in.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;} static void rg(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);} static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;} static void rdg(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);} static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;} static void rsg(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);} static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;} static void rdsg(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(double... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next()); else __out.println();} static void h() {__out.println("hlfd"); flush();} static void flush() {__out.flush();} static void close() {__out.close();} }
Java
["3 3 4", "3 3 1000000000", "3 3 8", "4 4 9", "3 4 16"]
1 second
["YES\n2\n2 R\n2 L", "NO", "YES\n3\n2 R\n2 D\n1 LLRR", "YES\n1\n3 RLD", "YES\n8\n3 R\n3 L\n1 D\n3 R\n1 D\n1 U\n3 L\n1 D"]
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run $$$1000000000$$$ kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
Java 11
standard input
[ "constructive algorithms", "implementation", "graphs" ]
a8c5ecf78a5442758441cd7c075b3d7e
The only line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \leq n, m \leq 500$$$, $$$1 \leq k \leq 10 ^{9}$$$), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
2,000
If there is no possible way to run $$$k$$$ kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line. If the answer is "YES", on the second line print an integer $$$a$$$ ($$$1 \leq a \leq 3000$$$)Β β€” the number of steps, then print $$$a$$$ lines describing the steps. To describe a step, print an integer $$$f$$$ ($$$1 \leq f \leq 10^{9}$$$) and a string of moves $$$s$$$ of length at most $$$4$$$. Every character in $$$s$$$ should be 'U', 'D', 'L' or 'R'. Bashar will start from the top-left cell. Make sure to move exactly $$$k$$$ moves without visiting the same road twice and without going outside the grid. He can finish at any cell. We can show that if it is possible to run exactly $$$k$$$ kilometers, then it is possible to describe the path under such output constraints.
standard output
PASSED
6ba5e6b49986eec7236a824f5d2bf47d
train_004.jsonl
1581604500
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.In order to lose weight, Bashar is going to run for $$$k$$$ kilometers. Bashar is going to run in a place that looks like a grid of $$$n$$$ rows and $$$m$$$ columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly $$$(4 n m - 2n - 2m)$$$ roads.Let's take, for example, $$$n = 3$$$ and $$$m = 4$$$. In this case, there are $$$34$$$ roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row $$$i$$$ and in the column $$$j$$$, i.e. in the cell $$$(i, j)$$$ he will move to: in the case 'U' to the cell $$$(i-1, j)$$$; in the case 'D' to the cell $$$(i+1, j)$$$; in the case 'L' to the cell $$$(i, j-1)$$$; in the case 'R' to the cell $$$(i, j+1)$$$; He wants to run exactly $$$k$$$ kilometers, so he wants to make exactly $$$k$$$ moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him $$$a$$$ steps to do and since Bashar can't remember too many steps, $$$a$$$ should not exceed $$$3000$$$. In every step, you should give him an integer $$$f$$$ and a string of moves $$$s$$$ of length at most $$$4$$$ which means that he should repeat the moves in the string $$$s$$$ for $$$f$$$ times. He will perform the steps in the order you print them.For example, if the steps are $$$2$$$ RUD, $$$3$$$ UUL then the moves he is going to move are RUD $$$+$$$ RUD $$$+$$$ UUL $$$+$$$ UUL $$$+$$$ UUL $$$=$$$ RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to $$$k$$$ kilometers or say, that it is impossible?
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main{ static int p=1000000007; public static void main (String args[])throws IOException{ Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n=sc.nextInt(), m=sc.nextInt(), k=sc.nextInt(); String str = ""; int cnt=0; loop: for(int row=0; row<n; row++) { //out.println(k); if(m!=1) { str+=min(k,m-1)+" R\n"; k-=min(k,m-1); cnt++; if(k==0) break loop; if(row==0) { str+=min(k,m-1)+" L\n"; k-=min(k,m-1); cnt++; if(k==0) break loop; } if (row != 0) { int min=min(k/3,m-1); if(min!=0) { str+=min+" UDL\n"; k-=(3*min); cnt++; if(k==0) break loop; } if(k<3 && min!=m-1) { str+=1+" UDL".substring(0,k+1)+"\n"; k=0; cnt++; break loop; } } } if (row == n - 1) { str+=min(k,n-1)+" U\n"; k-=min(k,n-1); cnt++; if(k==0) break loop; } else { str += 1 + " D\n"; k--; cnt++; if (k == 0) break loop; } } //out.println(k); if (k > 0) out.println("NO"); else { out.println("YES"); out.println(cnt); out.println(str); } out.flush(); } public static String reverseString(String str){ StringBuilder sb=new StringBuilder(str); sb.reverse(); return sb.toString(); } static boolean isPalindrome(String str) { int i = 0, j = str.length() - 1; while (i < j) { if (str.charAt(i) != str.charAt(j)) return false; i++; j--; } return true; } static void print(int[] arr) { for(int i=0; i<arr.length; i++) System.out.print(arr[i]+" "); System.out.println(); } public static int abs(int x) {return ((x > 0) ? x : -x);} public static long abs(long x) {return ((x > 0) ? x : -x);} public static int max(int a, int b) {return Math.max(a, b);} public static long max(long a, long b) {return Math.max(a, b);} public static int min(int a, int b) {return Math.min(a, b);} public static long min(long a, long b) {return Math.min(a, b);} static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static int modInverse(int a, int m) { int g = gcd(a, m); if (g != 1) return -1; else return power(a, m - 2, m); } // To compute x^y under modulo m 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[] primeGenerator(int num) { int length=0, arr[]=new int[num], a=num, factor=1; if(num%2==0) { while(num%2==0) { num/=2; factor*=2; } arr[length++]=factor; } for(int i=3; i*i<=a; i++) { factor=1; if(num%i==0) { while(num%i==0) { num/=i; factor*=i; } arr[length++]=factor; } } if(num>1) arr[length++]=num; return Arrays.copyOfRange(arr, 0, length); } 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 class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } static void sort(int[] a) { shuffle(a); Arrays.sort(a); } static void shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } } } class Pair{ int x; int y; Pair(int a, int b){ x=a; y=b; } void print() { System.out.println(this.x+" "+this.y); } }
Java
["3 3 4", "3 3 1000000000", "3 3 8", "4 4 9", "3 4 16"]
1 second
["YES\n2\n2 R\n2 L", "NO", "YES\n3\n2 R\n2 D\n1 LLRR", "YES\n1\n3 RLD", "YES\n8\n3 R\n3 L\n1 D\n3 R\n1 D\n1 U\n3 L\n1 D"]
NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run $$$1000000000$$$ kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
Java 11
standard input
[ "constructive algorithms", "implementation", "graphs" ]
a8c5ecf78a5442758441cd7c075b3d7e
The only line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \leq n, m \leq 500$$$, $$$1 \leq k \leq 10 ^{9}$$$), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
2,000
If there is no possible way to run $$$k$$$ kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line. If the answer is "YES", on the second line print an integer $$$a$$$ ($$$1 \leq a \leq 3000$$$)Β β€” the number of steps, then print $$$a$$$ lines describing the steps. To describe a step, print an integer $$$f$$$ ($$$1 \leq f \leq 10^{9}$$$) and a string of moves $$$s$$$ of length at most $$$4$$$. Every character in $$$s$$$ should be 'U', 'D', 'L' or 'R'. Bashar will start from the top-left cell. Make sure to move exactly $$$k$$$ moves without visiting the same road twice and without going outside the grid. He can finish at any cell. We can show that if it is possible to run exactly $$$k$$$ kilometers, then it is possible to describe the path under such output constraints.
standard output
PASSED
157975bdb7806160601d450ad03729db
train_004.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
import java.io.*; import java.util.*; public class SherlockAndHisGirlfriend { 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 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(); } public void flush() { writer.flush(); } } static boolean prime[]; static int sieveOfEratosthenes(int n) { prime=new boolean[n+1]; Arrays.fill(prime,true); int count=0; for(int i=2;i*i<=n;i++) { if(prime[i]==true) { for(int j=i*i;j<=n;j+=i) prime[j]=false; } } for(int i=2;i<=n;i++) { if(prime[i]==true) count++; } return count; } public static void main(String args[]) { FastReader sc=new FastReader(); OutputWriter out=new OutputWriter(System.out); int n=sc.nextInt(); int count=sieveOfEratosthenes(n+1); if(n==count) { out.printLine(1); for(int i=0;i<n;i++) out.print(1+" "); out.printLine(); } else { out.printLine(2); for(int i=2;i<=n+1;i++) { if(prime[i]==true) out.print(1+" "); else out.print(2+" "); } out.printLine(); } out.flush(); } }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≀ n ≀ 100000)Β β€” the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
06808aa9dcd146c12f1f39f109798290
train_004.jsonl
1487861100
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry.He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1.Watson gave Sherlock a challenge to color these jewelry pieces such that two pieces don't have the same color if the price of one piece is a prime divisor of the price of the other piece. Also, Watson asked him to minimize the number of different colors used.Help Sherlock complete this trivial task.
256 megabytes
//package src; import java.util.Scanner; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Stack; import java.util.TreeMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.lang.StringBuilder; public class idk { static Scanner scn = new Scanner(System.in); static boolean prime[] = new boolean[100000+10]; public static void main(String[] args) { // TODO Auto-generated method stub int n=scn.nextInt(),count=0; int arr[]=new int[n+1]; for(int i=1;i<n+1;i++) arr[i]=i+1; if(n==1) { System.out.println("1"); System.out.println("1"); return; } else if(n==2) { System.out.println("1"); System.out.print("1 "+"1"); System.out.println();return; } String s=""; sieveOfEratosthenes(n+1); System.out.println("2"); for(int i=2;i<n+2;i++) { if(prime[i]) System.out.print("1 "); else System.out.print("2 "); } System.out.println(); } public static void sieveOfEratosthenes(int n) { for(int i=2;i<n+2;i++) prime[i] = true; for(int p = 2; p*p <=n; p++) { if(prime[p] == true) { for(int i = p*p; i <= n; i += p) prime[i] = false; } } } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } public static String rev(String str) { int n = str.length(); char ch[] = str.toCharArray(); char temp = ' '; for (int i = 0; i < n / 2; i++) { temp = ch[i]; ch[i] = ch[n - i - 1]; ch[n - i - 1] = temp; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) sb.append(ch[i]); return sb.toString(); } }
Java
["3", "4"]
1 second
["2\n1 1 2", "2\n2 1 1 2"]
NoteIn the first input, the colors for first, second and third pieces of jewelry having respective prices 2, 3 and 4 are 1, 1 and 2 respectively.In this case, as 2 is a prime divisor of 4, colors of jewelry having prices 2 and 4 must be distinct.
Java 11
standard input
[ "constructive algorithms", "number theory" ]
a99f5e08f3f560488ff979a3e9746e7f
The only line contains single integer n (1 ≀ n ≀ 100000)Β β€” the number of jewelry pieces.
1,200
The first line of output should contain a single integer k, the minimum number of colors that can be used to color the pieces of jewelry with the given constraints. The next line should consist of n space-separated integers (between 1 and k) that specify the color of each piece in the order of increasing price. If there are multiple ways to color the pieces using k colors, you can output any of them.
standard output
PASSED
0f9592331ed64f42651a9b5efa32bb90
train_004.jsonl
1529166900
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$-100$$$, while the second group is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$100$$$.Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with $$$x=0$$$ (with not necessarily integer $$$y$$$-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
256 megabytes
import java.io.*; import java.util.*; public class A { FastScanner in; PrintWriter out; class O implements Comparable<O> { int i; int j, sum; public O(int i, int j, int sum) { this.i = i; this.j = j; this.sum = sum; } @Override public int compareTo(O o) { return Integer.compare(sum, o.sum); } } void solve() { int n = in.nextInt(); int m = in.nextInt(); int[] y1 = new int[n]; int[] y2 = new int[m]; for (int i = 0; i < n; i++) { y1[i] = in.nextInt(); } for (int i = 0; i < m; i++) { y2[i] = in.nextInt(); } O[] o = new O[n * m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { o[i * m + j] = new O(i, j, y1[i] + y2[j]); } } Arrays.sort(o); List<Long> m1 = new ArrayList<>(); List<Long> m2 = new ArrayList<>(); for (int i = 0; i < o.length; ) { int j = i; long xx = 0, yy = 0; while (j != o.length && o[i].sum == o[j].sum) { xx |= 1L << o[j].i; yy |= 1L << o[j].j; j++; } m1.add(xx); m2.add(yy); i = j; } int ans = 0; for (int i = 0; i < m1.size(); i++) { for (int j = i; j < m1.size(); j++) { int res = Long.bitCount(m1.get(i) | m1.get(j)) + Long.bitCount(m2.get(i) | m2.get(j)); ans = Math.max(ans, res); } } out.println(ans); } void run() { try { in = new FastScanner(new File("A.in")); out = new PrintWriter(new File("A.out")); solve(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } 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 A().runIO(); } }
Java
["3 9\n1 2 3\n1 2 3 7 8 9 11 12 13", "5 5\n1 2 3 4 5\n1 2 3 4 5"]
2 seconds
["9", "10"]
NoteIn the first example the first spaceship can be positioned at $$$(0, 2)$$$, and the second – at $$$(0, 7)$$$. This way all the enemy spaceships in the first group and $$$6$$$ out of $$$9$$$ spaceships in the second group will be destroyed.In the second example the first spaceship can be positioned at $$$(0, 3)$$$, and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships.
Java 8
standard input
[ "geometry", "bitmasks", "brute force" ]
7dd891cef0aa40cc1522ca4b37963b92
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 60$$$), the number of enemy spaceships with $$$x = -100$$$ and the number of enemy spaceships with $$$x = 100$$$, respectively. The second line contains $$$n$$$ integers $$$y_{1,1}, y_{1,2}, \ldots, y_{1,n}$$$ ($$$|y_{1,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the first group. The third line contains $$$m$$$ integers $$$y_{2,1}, y_{2,2}, \ldots, y_{2,m}$$$ ($$$|y_{2,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the second group. The $$$y$$$ coordinates are not guaranteed to be unique, even within a group.
2,100
Print a single integer – the largest number of enemy spaceships that can be destroyed.
standard output
PASSED
b96396904169756f683411d59ff4c36a
train_004.jsonl
1529166900
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$-100$$$, while the second group is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$100$$$.Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with $$$x=0$$$ (with not necessarily integer $$$y$$$-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
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); CCarefulManeuvering solver = new CCarefulManeuvering(); solver.solve(1, in, out); out.close(); } } static class CCarefulManeuvering { public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); int m = in.readInt(); int fix = 20000; int[] left = new int[n]; int[] right = new int[m]; long[] leftKill = new long[20001 + fix]; long[] rightKill = new long[20001 + fix]; for (int i = 0; i < n; i++) { left[i] = in.readInt() * 2 + fix; } for (int i = 0; i < m; i++) { right[i] = in.readInt() * 2 + fix; } for (int i = 0; i < leftKill.length; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { if (left[j] - i == i - right[k]) { leftKill[i] = Bits.setBit(leftKill[i], j, true); rightKill[i] = Bits.setBit(rightKill[i], k, true); } } } } IntegerList nonZero = new IntegerList(leftKill.length); for (int i = 0; i < leftKill.length; i++) { if (leftKill[i] != 0) { nonZero.add(i); } } int[] indice = nonZero.toArray(); int ans = 0; for (int i : indice) { if (leftKill[i] == 0) { continue; } for (int j : indice) { int cnt = CachedBitCount.bitCount(leftKill[i] | leftKill[j]) + CachedBitCount.bitCount(rightKill[i] | rightKill[j]); ans = Math.max(ans, cnt); } } out.println(ans); } } static class Bits { private Bits() { } public static long setBit(long x, int i, boolean v) { if (v) { x |= 1L << i; } else { x &= ~(1L << i); } return x; } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 20]; 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 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; } } static class SequenceUtils { public static boolean equal(int[] a, int al, int ar, int[] b, int bl, int br) { if ((ar - al) != (br - bl)) { return false; } for (int i = al, j = bl; i <= ar; i++, j++) { if (a[i] != b[j]) { return false; } } return true; } } static class CachedBitCount { private static final int BITS = 16; private static final int LIMIT = 1 << BITS; private static final int MASK = LIMIT - 1; private static final byte[] CACHE = new byte[LIMIT]; static { for (int i = 1; i < LIMIT; i++) { CACHE[i] = (byte) (CACHE[i - (i & -i)] + 1); } } public static int bitCount(long x) { return CACHE[(int) (x & MASK)] + CACHE[(int) ((x >>> 16) & MASK)] + CACHE[(int) ((x >>> 32) & MASK)] + CACHE[(int) ((x >>> 48) & MASK)]; } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(int c) { cache.append(c); return this; } public FastOutput println(int c) { return append(c).println(); } public FastOutput println() { cache.append(System.lineSeparator()); 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(); } } static class IntegerList implements Cloneable { private int size; private int cap; private int[] data; private static final int[] EMPTY = new int[0]; public IntegerList(int cap) { this.cap = cap; if (cap == 0) { data = EMPTY; } else { data = new int[cap]; } } public IntegerList(IntegerList list) { this.size = list.size; this.cap = list.cap; this.data = Arrays.copyOf(list.data, size); } public IntegerList() { this(0); } public void ensureSpace(int req) { if (req > cap) { while (cap < req) { cap = Math.max(cap + 10, 2 * cap); } data = Arrays.copyOf(data, cap); } } public void add(int x) { ensureSpace(size + 1); data[size++] = x; } public void addAll(int[] x, int offset, int len) { ensureSpace(size + len); System.arraycopy(x, offset, data, size, len); size += len; } public void addAll(IntegerList list) { addAll(list.data, 0, list.size); } public int[] toArray() { return Arrays.copyOf(data, size); } public String toString() { return Arrays.toString(toArray()); } public boolean equals(Object obj) { if (!(obj instanceof IntegerList)) { return false; } IntegerList other = (IntegerList) obj; return SequenceUtils.equal(data, 0, size - 1, other.data, 0, other.size - 1); } public int hashCode() { int h = 1; for (int i = 0; i < size; i++) { h = h * 31 + Integer.hashCode(data[i]); } return h; } public IntegerList clone() { IntegerList ans = new IntegerList(); ans.addAll(this); return ans; } } }
Java
["3 9\n1 2 3\n1 2 3 7 8 9 11 12 13", "5 5\n1 2 3 4 5\n1 2 3 4 5"]
2 seconds
["9", "10"]
NoteIn the first example the first spaceship can be positioned at $$$(0, 2)$$$, and the second – at $$$(0, 7)$$$. This way all the enemy spaceships in the first group and $$$6$$$ out of $$$9$$$ spaceships in the second group will be destroyed.In the second example the first spaceship can be positioned at $$$(0, 3)$$$, and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships.
Java 8
standard input
[ "geometry", "bitmasks", "brute force" ]
7dd891cef0aa40cc1522ca4b37963b92
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 60$$$), the number of enemy spaceships with $$$x = -100$$$ and the number of enemy spaceships with $$$x = 100$$$, respectively. The second line contains $$$n$$$ integers $$$y_{1,1}, y_{1,2}, \ldots, y_{1,n}$$$ ($$$|y_{1,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the first group. The third line contains $$$m$$$ integers $$$y_{2,1}, y_{2,2}, \ldots, y_{2,m}$$$ ($$$|y_{2,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the second group. The $$$y$$$ coordinates are not guaranteed to be unique, even within a group.
2,100
Print a single integer – the largest number of enemy spaceships that can be destroyed.
standard output
PASSED
f831ffa40dd9ef1f459e9f763385712c
train_004.jsonl
1529166900
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$-100$$$, while the second group is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$100$$$.Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with $$$x=0$$$ (with not necessarily integer $$$y$$$-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
256 megabytes
import sun.rmi.transport.DGCImpl_Stub; import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws FileNotFoundException { ConsoleIO io = new ConsoleIO(new InputStreamReader(System.in), new PrintWriter(System.out)); // String fileName = "C-large"; // ConsoleIO io = new ConsoleIO(new FileReader("D:\\Dropbox\\code\\practice\\jb\\src\\" + fileName + ".in"), new PrintWriter(new File("D:\\Dropbox\\code\\practice\\jb\\src\\" + fileName + ".out"))); new Main(io).solve(); // new Main(io).solveLocal(); io.close(); } ConsoleIO io; Main(ConsoleIO io) { this.io = io; } ConsoleIO opt; Main(ConsoleIO io, ConsoleIO opt) { this.io = io; this.opt = opt; } List<List<Integer>> gr = new ArrayList<>(); long MOD = 1_000_000_007; public void solve() { // int n= io.ri(); // int x = io.ri(); // int[] all = new int[n]; // for(int i= 0;i<n;i++) // all[i] = io.ri(); // long[] res = new long[n+1]; // // int cur = 0; // int zeros = 0; // int[] plus = new int[n+1]; // for(int i = 0;i<n;i++){ // if(all[i]<x){ // cur++; // zeros = 0; // }else{ // //cur = 0; // zeros++; // res[0]+=zeros; // } // plus[cur]++; // } // long v = 0; // for(int i = n;i>0;i--){ // v+=plus[i]; // res[i] = v; // } // // StringBuilder sb = new StringBuilder(); // for(int i = 0;i<=n;i++){ // if(i>0)sb.append(' '); // sb.append(res[i]); // } // io.writeLine(sb.toString()); int n = io.ri(); int m = io.ri(); int[] left = new int[n]; int[] right = new int[m]; for (int i = 0; i < n; i++) { int x = io.ri() + 10000; x *= 2; left[i] = x; } for (int i = 0; i < m; i++) { int x = io.ri() + 10000; x *= 2; right[i] = x; } long[] cl = new long[40004]; long[] cr = new long[40004]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { int v = (left[i] + right[j]) / 2; cl[v] |= 1L<<i; cr[v] |= 1L<<j; } List<Long> ll = new ArrayList<>(); List<Long> rr = new ArrayList<>(); for (int i = 0; i < cl.length; i++) if (cl[i] > 0) { ll.add(cl[i]); rr.add(cr[i]); } int res= 0; for (int i = 0; i < ll.size(); i++) { long al = ll.get(i); long ar = rr.get(i); res = Math.max(res, Long.bitCount(al) + Long.bitCount(ar)); for (int j = i + 1; j < ll.size(); j++) { long bl = ll.get(j) | al; long br = rr.get(j) | ar; int k = Long.bitCount(bl) + Long.bitCount(br); res = Math.max(res, k); } } io.writeLine(res+""); } } class ConsoleIO { BufferedReader br; PrintWriter out; public ConsoleIO(Reader reader, PrintWriter writer){br = new BufferedReader(reader);out = writer;} public void flush(){this.out.flush();} public void close(){this.out.close();} public void writeLine(String s) {this.out.println(s);} public void writeInt(int a) {this.out.print(a);this.out.print(' ');} public void writeWord(String s){ this.out.print(s); } public void writeIntArray(int[] a, int k, String separator) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < k; i++) { if (i > 0) sb.append(separator); sb.append(a[i]); } this.writeLine(sb.toString()); } public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }} public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}} public long[] readLongArray() { String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length]; for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]); return r; } public int[] readIntArray() { String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length]; for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]); return r; } public int[] readIntArray(int n) { int[] res = new int[n]; char[] all = this.readLine().toCharArray(); int cur = 0;boolean have = false; int k = 0; boolean neg = false; for(int i = 0;i<all.length;i++){ if(all[i]>='0' && all[i]<='9'){ cur = cur*10+all[i]-'0'; have = true; }else if(all[i]=='-') { neg = true; } else if(have){ res[k++] = neg?-cur:cur; cur = 0; have = false; neg = false; } } if(have)res[k++] = neg?-cur:cur; return res; } public int ri() { try { int r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public long readLong() { try { long r = 0; boolean start = false; boolean neg = false; while (true) { int c = br.read(); if (c >= '0' && c <= '9') { r = r * 10 + c - '0'; start = true; } else if (!start && c == '-') { start = true; neg = true; } else if (start || c == -1) return neg ? -r : r; } } catch (Exception ex) { return -1; } } public String readWord() { try { boolean start = false; StringBuilder sb = new StringBuilder(); while (true) { int c = br.read(); if (c!= ' ' && c!= '\r' && c!='\n' && c!='\t') { sb.append((char)c); start = true; } else if (start || c == -1) return sb.toString(); } } catch (Exception ex) { return ""; } } public char readSymbol() { try { while (true) { int c = br.read(); if (c != ' ' && c != '\r' && c != '\n' && c != '\t') { return (char) c; } } } catch (Exception ex) { return 0; } } //public char readChar(){try {return (char)br.read();}catch (Exception ex){ return 0; }} } class Pair { public Pair(int a, int b) {this.a = a;this.b = b;} public int a; public int b; } class PairLL { public PairLL(long a, long b) {this.a = a;this.b = b;} public long a; public long b; } class Triple { public Triple(int a, int b, int c) {this.a = a;this.b = b;this.c = c;} public int a; public int b; public int c; }
Java
["3 9\n1 2 3\n1 2 3 7 8 9 11 12 13", "5 5\n1 2 3 4 5\n1 2 3 4 5"]
2 seconds
["9", "10"]
NoteIn the first example the first spaceship can be positioned at $$$(0, 2)$$$, and the second – at $$$(0, 7)$$$. This way all the enemy spaceships in the first group and $$$6$$$ out of $$$9$$$ spaceships in the second group will be destroyed.In the second example the first spaceship can be positioned at $$$(0, 3)$$$, and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships.
Java 8
standard input
[ "geometry", "bitmasks", "brute force" ]
7dd891cef0aa40cc1522ca4b37963b92
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 60$$$), the number of enemy spaceships with $$$x = -100$$$ and the number of enemy spaceships with $$$x = 100$$$, respectively. The second line contains $$$n$$$ integers $$$y_{1,1}, y_{1,2}, \ldots, y_{1,n}$$$ ($$$|y_{1,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the first group. The third line contains $$$m$$$ integers $$$y_{2,1}, y_{2,2}, \ldots, y_{2,m}$$$ ($$$|y_{2,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the second group. The $$$y$$$ coordinates are not guaranteed to be unique, even within a group.
2,100
Print a single integer – the largest number of enemy spaceships that can be destroyed.
standard output
PASSED
a1cbce26d25f0e457bf34f9b39110252
train_004.jsonl
1529166900
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$-100$$$, while the second group is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$100$$$.Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with $$$x=0$$$ (with not necessarily integer $$$y$$$-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.stream.IntStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.util.Set; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author prakharjain */ 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); _993C solver = new _993C(); solver.solve(1, in, out); out.close(); } static class _993C { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int m = in.nextInt(); int[] x1 = new int[n]; int[] y1 = new int[40001]; int[] cy1 = new int[40001]; for (int i = 0; i < n; i++) { x1[i] = 2 * in.nextInt() + 20000; y1[x1[i]]++; cy1[x1[i]]++; } x1 = Arrays.stream(x1).sorted().distinct().toArray(); n = x1.length; int[] x2 = new int[m]; int[] y2 = new int[40001]; int[] cy2 = new int[40001]; for (int i = 0; i < m; i++) { x2[i] = 2 * in.nextInt() + 20000; y2[x2[i]]++; cy2[x2[i]]++; } x2 = Arrays.stream(x2).sorted().distinct().toArray(); m = x2.length; Set<Integer> ip = new HashSet<>(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ip.add((x1[i] + x2[j]) / 2); } } List<Integer> lip = new ArrayList<>(); lip.addAll(ip); int ans = 0; for (int i = 0; i < lip.size(); i++) { int lipi = lip.get(i); boolean[] d1 = new boolean[n]; boolean[] d2 = new boolean[m]; int ca = 0; for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { if ((x1[j] + x2[k]) / 2 == lipi) { ca += y1[x1[j]]; d1[j] = true; ca += y2[x2[k]]; d2[k] = true; } } } Map<Integer, Integer> mp = new HashMap<>(); int max = 0; for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { int mid = (x1[j] + x2[k]) / 2; if (!d1[j]) { mp.merge(mid, y1[x1[j]], (x, y) -> x + y); //d1[j] = true; } if (!d2[k]) { mp.merge(mid, y2[x2[k]], (x, y) -> x + y); // d2[k] = true; } if (mp.getOrDefault(mid, 0) > max) { max = mp.get(mid); } } } ans = Math.max(ans, ca + max); } // for (int i = 0; i < lip.size(); i++) { // int lipi = lip.get(i); // for (int j = i + 1; j < lip.size(); j++) { // int lipj = lip.get(j); // // int ca = 0; // for (int k = 0; k < n; k++) { // int d = lipi - x1[k]; // int np = (lipi + d); // if (isv(np)) { // ca += y2[np]; // y2[np] = 0; // } // // d = lipj - x1[k]; // np = (lipj + d); // if (isv(np)) { // ca += y2[np]; // y2[np] = 0; // } // } // // for (int k = 0; k < m; k++) { // int d = lipi - x2[k]; // int np = (lipi + d); // if (isv(np)) { // ca += y1[np]; // y1[np] = 0; // } // // d = lipj - x2[k]; // np = (lipj + d); // if (isv(np)) { // ca += y1[np]; // y1[np] = 0; // } // } // // ans = Math.max(ans, ca); // //// for (int k = 0; k < n; k++) { //// y1[x1[k]] = cy1[x1[k]]; //// } //// //// for (int k = 0; k < m; k++) { //// y2[x2[k]] = cy2[x2[k]]; //// } // //// for (int k = 0; k <= 40000; k++) { //// y1[k] = cy1[k]; //// } //// //// for (int k = 0; k <= 40000; k++) { //// y2[k] = cy2[k]; //// } // } // } out.println(ans); } } 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 close() { writer.close(); } public void println(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } 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 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) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3 9\n1 2 3\n1 2 3 7 8 9 11 12 13", "5 5\n1 2 3 4 5\n1 2 3 4 5"]
2 seconds
["9", "10"]
NoteIn the first example the first spaceship can be positioned at $$$(0, 2)$$$, and the second – at $$$(0, 7)$$$. This way all the enemy spaceships in the first group and $$$6$$$ out of $$$9$$$ spaceships in the second group will be destroyed.In the second example the first spaceship can be positioned at $$$(0, 3)$$$, and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships.
Java 8
standard input
[ "geometry", "bitmasks", "brute force" ]
7dd891cef0aa40cc1522ca4b37963b92
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 60$$$), the number of enemy spaceships with $$$x = -100$$$ and the number of enemy spaceships with $$$x = 100$$$, respectively. The second line contains $$$n$$$ integers $$$y_{1,1}, y_{1,2}, \ldots, y_{1,n}$$$ ($$$|y_{1,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the first group. The third line contains $$$m$$$ integers $$$y_{2,1}, y_{2,2}, \ldots, y_{2,m}$$$ ($$$|y_{2,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the second group. The $$$y$$$ coordinates are not guaranteed to be unique, even within a group.
2,100
Print a single integer – the largest number of enemy spaceships that can be destroyed.
standard output
PASSED
bf999fa744fa029ca2a11b09fc51e70a
train_004.jsonl
1529166900
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$-100$$$, while the second group is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$100$$$.Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with $$$x=0$$$ (with not necessarily integer $$$y$$$-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
256 megabytes
//package round488; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class C { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), m = ni(); int[] a = na(n); int[] b = na(m); int[] can = new int[n*m]; int p = 0; for(int i = 0;i < n;i++){ for(int j = 0;j < m;j++){ can[p++] = a[i] + b[j]; } } Arrays.sort(can); can = uniq(can); int u = can.length; long[] da = new long[u]; long[] db = new long[u]; for(int j = 0;j < n;j++){ for(int k = 0;k < m;k++){ int ind = Arrays.binarySearch(can, a[j] + b[k]); da[ind] |= 1L<<j; db[ind] |= 1L<<k; } } long max = 0; for(int i = 0;i < u;i++){ for(int j = i;j < u;j++){ max = Math.max(max, Long.bitCount(da[i]|da[j]) + Long.bitCount(db[i]|db[j]) ); } } out.println(max); } public static int[] uniq(int[] a) { int n = a.length; int p = 0; for(int i = 0;i < n;i++) { if(i == 0 || a[i] != a[i-1])a[p++] = a[i]; } return Arrays.copyOf(a, p); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new C().run(); } 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 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 char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); 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 * 10 + (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(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["3 9\n1 2 3\n1 2 3 7 8 9 11 12 13", "5 5\n1 2 3 4 5\n1 2 3 4 5"]
2 seconds
["9", "10"]
NoteIn the first example the first spaceship can be positioned at $$$(0, 2)$$$, and the second – at $$$(0, 7)$$$. This way all the enemy spaceships in the first group and $$$6$$$ out of $$$9$$$ spaceships in the second group will be destroyed.In the second example the first spaceship can be positioned at $$$(0, 3)$$$, and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships.
Java 8
standard input
[ "geometry", "bitmasks", "brute force" ]
7dd891cef0aa40cc1522ca4b37963b92
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 60$$$), the number of enemy spaceships with $$$x = -100$$$ and the number of enemy spaceships with $$$x = 100$$$, respectively. The second line contains $$$n$$$ integers $$$y_{1,1}, y_{1,2}, \ldots, y_{1,n}$$$ ($$$|y_{1,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the first group. The third line contains $$$m$$$ integers $$$y_{2,1}, y_{2,2}, \ldots, y_{2,m}$$$ ($$$|y_{2,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the second group. The $$$y$$$ coordinates are not guaranteed to be unique, even within a group.
2,100
Print a single integer – the largest number of enemy spaceships that can be destroyed.
standard output
PASSED
fbfb536e8048fcc53e4867c4a1128b4d
train_004.jsonl
1529166900
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$-100$$$, while the second group is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$100$$$.Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with $$$x=0$$$ (with not necessarily integer $$$y$$$-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
256 megabytes
import java.io.*; import java.util.*; public class CFC { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; private static final long MOD = 1000L * 1000L * 1000L + 9; private static final int[] dx = {0, -1, 0, 1}; private static final int[] dy = {1, 0, -1, 0}; private static final String yes = "Yes"; private static final String no = "No"; int n; int m; int[] arr1; int[] arr2; class Pair implements Comparable<Pair> { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { if(x != o.x) { return Integer.compare(x, o.x); } else { return Integer.compare(y, o.y); } } @Override public int hashCode() { int res = 13; res = 37 * res + x; res = 37 * res + y; return res; } @Override public boolean equals(Object obj) { if(obj == null) { return false; } if(!(obj instanceof Pair)) { return false; } Pair o = (Pair) obj; return this.x == o.x && this.y == o.y; } @Override public String toString() { return "x: " + x + "; y: " + y; } } void solve() throws IOException { n = nextInt(); m = nextInt(); arr1 = nextIntArr(n); arr2 = nextIntArr(m); int mid = 20000 + 10; List<List<Pair>> pre = new ArrayList<>(); for (int i = 0; i < 3 * mid; i++) { pre.add(new ArrayList<>()); } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int sum = arr1[i] + arr2[j]; pre.get(sum + mid).add(new Pair(i, j)); } } List<List<Pair>> cand = new ArrayList<>(); for (List<Pair> pairs : pre) { if (!pairs.isEmpty()) { cand.add(pairs); } } int res = 0; int[] vis1 = new int[n]; int[] vis2 = new int[m]; for (List<Pair> l1 : cand) { int tmp = 0; for (Pair p : l1) { if (vis1[p.x] == 0) { tmp++; } vis1[p.x]++; if (vis2[p.y] == 0) { tmp++; } vis2[p.y]++; } for (List<Pair> l2 : cand) { for (Pair p : l2) { if (vis1[p.x] == 0) { tmp++; } vis1[p.x]++; if (vis2[p.y] == 0) { tmp++; } vis2[p.y]++; } res = Math.max(res, tmp); for (Pair p : l2) { if (vis1[p.x] == 1) { tmp--; } vis1[p.x]--; if (vis2[p.y] == 1) { tmp--; } vis2[p.y]--; } } Arrays.fill(vis1, 0); Arrays.fill(vis2, 0); } outln(res); } void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } int gcd(int a, int b) { while(a != 0 && b != 0) { int c = b; b = a % b; a = c; } return a + b; } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } private void formatPrint(double val) { System.out.format("%.9f%n", val); } public CFC() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFC(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["3 9\n1 2 3\n1 2 3 7 8 9 11 12 13", "5 5\n1 2 3 4 5\n1 2 3 4 5"]
2 seconds
["9", "10"]
NoteIn the first example the first spaceship can be positioned at $$$(0, 2)$$$, and the second – at $$$(0, 7)$$$. This way all the enemy spaceships in the first group and $$$6$$$ out of $$$9$$$ spaceships in the second group will be destroyed.In the second example the first spaceship can be positioned at $$$(0, 3)$$$, and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships.
Java 8
standard input
[ "geometry", "bitmasks", "brute force" ]
7dd891cef0aa40cc1522ca4b37963b92
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 60$$$), the number of enemy spaceships with $$$x = -100$$$ and the number of enemy spaceships with $$$x = 100$$$, respectively. The second line contains $$$n$$$ integers $$$y_{1,1}, y_{1,2}, \ldots, y_{1,n}$$$ ($$$|y_{1,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the first group. The third line contains $$$m$$$ integers $$$y_{2,1}, y_{2,2}, \ldots, y_{2,m}$$$ ($$$|y_{2,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the second group. The $$$y$$$ coordinates are not guaranteed to be unique, even within a group.
2,100
Print a single integer – the largest number of enemy spaceships that can be destroyed.
standard output
PASSED
6fa759e04cacf7e5e7a92189d1eae149
train_004.jsonl
1529166900
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$-100$$$, while the second group is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$100$$$.Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with $$$x=0$$$ (with not necessarily integer $$$y$$$-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Div1_488C { static int nA; static int nB; public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); StringTokenizer inputData = new StringTokenizer(reader.readLine()); nA = Integer.parseInt(inputData.nextToken()); nB = Integer.parseInt(inputData.nextToken()); Integer[] a = new Integer[nA]; Integer[] b = new Integer[nB]; inputData = new StringTokenizer(reader.readLine()); for (int i = 0; i < nA; i++) { a[i] = 2 * (10_000 + Integer.parseInt(inputData.nextToken())); } inputData = new StringTokenizer(reader.readLine()); for (int i = 0; i < nB; i++) { b[i] = 2 * (10_000 + Integer.parseInt(inputData.nextToken())); } Arrays.sort(a); Arrays.sort(b); Integer[] aT = new Integer[nA]; int[] aW = new int[nA]; int aC = 0; for (int i = 0; i < nA; i++) { if (i == 0 || !a[i].equals(a[i - 1])) { aW[aC] = 1; aT[aC++] = a[i]; } else { aW[aC - 1]++; } } nA = aC; a = aT; Integer[] bT = new Integer[nB]; int[] bW = new int[nB]; int bC = 0; for (int i = 0; i < nB; i++) { if (i == 0 || !b[i].equals(b[i - 1])) { bW[bC] = 1; bT[bC++] = b[i]; } else { bW[bC - 1]++; } } nB = bC; b = bT; boolean[] aMark = new boolean[nA]; boolean[] bMark = new boolean[nB]; int[] cnt = new int[40_001]; int ans = 0; for (int aP = 0; aP < nA; aP++) { for (int bP = 0; bP < nB; bP++) { Arrays.fill(aMark, false); Arrays.fill(bMark, false); Arrays.fill(cnt, 0); int nMark = 0; int center = (a[aP] + b[bP]) / 2; for (int aI = 0; aI < nA; aI++) { for (int bI = 0; bI < nB; bI++) { if (center + (center - a[aI]) == b[bI]) { if (!aMark[aI]) { nMark += aW[aI]; aMark[aI] = true; } if (!bMark[bI]) { nMark += bW[bI]; bMark[bI] = true; } } } } for (int aI = 0; aI < nA; aI++) { for (int bI = 0; bI < nB; bI++) { int mid = (a[aI] + b[bI]) / 2; if (!aMark[aI]) { cnt[mid] += aW[aI]; } if (!bMark[bI]) { cnt[mid] += bW[bI]; } } } int max = 0; for (int i = 0; i < 40_001; i++) { max = Math.max(max, cnt[i]); } ans = Math.max(ans, max + nMark); } } printer.println(ans); printer.close(); } }
Java
["3 9\n1 2 3\n1 2 3 7 8 9 11 12 13", "5 5\n1 2 3 4 5\n1 2 3 4 5"]
2 seconds
["9", "10"]
NoteIn the first example the first spaceship can be positioned at $$$(0, 2)$$$, and the second – at $$$(0, 7)$$$. This way all the enemy spaceships in the first group and $$$6$$$ out of $$$9$$$ spaceships in the second group will be destroyed.In the second example the first spaceship can be positioned at $$$(0, 3)$$$, and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships.
Java 8
standard input
[ "geometry", "bitmasks", "brute force" ]
7dd891cef0aa40cc1522ca4b37963b92
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 60$$$), the number of enemy spaceships with $$$x = -100$$$ and the number of enemy spaceships with $$$x = 100$$$, respectively. The second line contains $$$n$$$ integers $$$y_{1,1}, y_{1,2}, \ldots, y_{1,n}$$$ ($$$|y_{1,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the first group. The third line contains $$$m$$$ integers $$$y_{2,1}, y_{2,2}, \ldots, y_{2,m}$$$ ($$$|y_{2,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the second group. The $$$y$$$ coordinates are not guaranteed to be unique, even within a group.
2,100
Print a single integer – the largest number of enemy spaceships that can be destroyed.
standard output
PASSED
e7498716ad004ce169380cc51bb6acc9
train_004.jsonl
1529166900
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$-100$$$, while the second group is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$100$$$.Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with $$$x=0$$$ (with not necessarily integer $$$y$$$-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; public class Main { private void solve() throws IOException { int n = ni(); int m = ni(); int[] a = nia(n); int[] b = nia(m); Map<Integer, List<Integer>> mp = new HashMap<Integer, List<Integer>>(); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { List<Integer> l = mp.getOrDefault(a[i] + b[j], new ArrayList<Integer>()); l.add(i); l.add(n + j); mp.put(a[i] + b[j], l); } List<Integer>[] ar = mp.values().toArray(new List[0]); int ans = new HashSet<Integer>(ar[0]).size(); for (int i = 0; i < ar.length - 1; i++) for (int j = i + 1; j < ar.length; j++) { Set<Integer> s = new HashSet<Integer>(ar[i]); s.addAll(ar[j]); ans = Math.max(ans, s.size()); } out.println(ans); out.close(); } static BufferedReader in; static PrintWriter out; static StringTokenizer tok; private int[][] na(int n) throws IOException { int[][] a = new int[n][2]; for (int i = 0; i < n; i++) { a[i][0] = ni(); a[i][1] = i; } return a; } String ns() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine(), " "); } return tok.nextToken(); } int ni() throws IOException { return Integer.parseInt(ns()); } long nl() throws IOException { return Long.parseLong(ns()); } double nd() throws IOException { return Double.parseDouble(ns()); } String[] nsa(int n) throws IOException { String[] res = new String[n]; for (int i = 0; i < n; i++) { res[i] = ns(); } return res; } int[] nia(int n) throws IOException { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = ni(); } return res; } long[] nla(int n) throws IOException { long[] res = new long[n]; for (int i = 0; i < n; i++) { res[i] = nl(); } return res; } public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); tok = new StringTokenizer(""); Main main = new Main(); main.solve(); out.close(); } }
Java
["3 9\n1 2 3\n1 2 3 7 8 9 11 12 13", "5 5\n1 2 3 4 5\n1 2 3 4 5"]
2 seconds
["9", "10"]
NoteIn the first example the first spaceship can be positioned at $$$(0, 2)$$$, and the second – at $$$(0, 7)$$$. This way all the enemy spaceships in the first group and $$$6$$$ out of $$$9$$$ spaceships in the second group will be destroyed.In the second example the first spaceship can be positioned at $$$(0, 3)$$$, and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships.
Java 8
standard input
[ "geometry", "bitmasks", "brute force" ]
7dd891cef0aa40cc1522ca4b37963b92
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 60$$$), the number of enemy spaceships with $$$x = -100$$$ and the number of enemy spaceships with $$$x = 100$$$, respectively. The second line contains $$$n$$$ integers $$$y_{1,1}, y_{1,2}, \ldots, y_{1,n}$$$ ($$$|y_{1,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the first group. The third line contains $$$m$$$ integers $$$y_{2,1}, y_{2,2}, \ldots, y_{2,m}$$$ ($$$|y_{2,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the second group. The $$$y$$$ coordinates are not guaranteed to be unique, even within a group.
2,100
Print a single integer – the largest number of enemy spaceships that can be destroyed.
standard output
PASSED
aa367072ef3df680122ded1244eeb67a
train_004.jsonl
1529166900
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$-100$$$, while the second group is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$100$$$.Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with $$$x=0$$$ (with not necessarily integer $$$y$$$-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; import java.lang.StringBuilder; import java.util.Arrays; import java.util.Stack; //maintain: array on vertices //a[i]: public class Test10 { public static void main(String[] Args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[] cnt = new int[3600]; int[] code = new int[40001]; int[][] union = new int[3600][3600]; int[] a = new int[n]; int[] b = new int[m]; for (int i = 0; i < 40001; i++) code[i] = -1; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); for (int i = 0; i < m; i++) b[i] = sc.nextInt(); Arrays.sort(a); Arrays.sort(b); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) { if (code[a[i] + b[j] + 20000] == -1) code[a[i] + b[j] + 20000] = i * 60 + j; if (j == 0 || b[j] > b[j - 1]) cnt[code[a[i] + b[j] + 20000]]++; } for (int j = 0; j < m; j++) for (int i = 0; i < n; i++) { if (i == 0 || a[i] > a[i - 1]) cnt[code[a[i] + b[j] + 20000]]++; } for (int i = 0; i < n; i++) for (int j1 = 0; j1 < m; j1++) for (int j2 = 0; j2 < m; j2++) if ((j1 == 0 || b[j1] > b[j1 - 1]) && (j2 == 0 || b[j2] > b[j2 - 1])) union[code[a[i] + b[j1] + 20000]][code[a[i] + b[j2] + 20000]] ++; for (int i = 0; i < m; i++) for (int j1 = 0; j1 < n; j1++) for (int j2 = 0; j2 < n; j2++) if ((j1 == 0 || a[j1] > a[j1 - 1]) && (j2 == 0 || a[j2] > a[j2 - 1])) union[code[b[i] + a[j1] + 20000]][code[b[i] + a[j2] + 20000]] ++; int mx = 0; for (int c1 = 0; c1 < 3600; c1++) for (int c2 = c1; c2 < 3600; c2++) if (cnt[c1] + cnt[c2] - union[c1][c2] > mx) mx = cnt[c1] + cnt[c2] - union[c1][c2]; System.out.println(mx); } }
Java
["3 9\n1 2 3\n1 2 3 7 8 9 11 12 13", "5 5\n1 2 3 4 5\n1 2 3 4 5"]
2 seconds
["9", "10"]
NoteIn the first example the first spaceship can be positioned at $$$(0, 2)$$$, and the second – at $$$(0, 7)$$$. This way all the enemy spaceships in the first group and $$$6$$$ out of $$$9$$$ spaceships in the second group will be destroyed.In the second example the first spaceship can be positioned at $$$(0, 3)$$$, and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships.
Java 8
standard input
[ "geometry", "bitmasks", "brute force" ]
7dd891cef0aa40cc1522ca4b37963b92
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 60$$$), the number of enemy spaceships with $$$x = -100$$$ and the number of enemy spaceships with $$$x = 100$$$, respectively. The second line contains $$$n$$$ integers $$$y_{1,1}, y_{1,2}, \ldots, y_{1,n}$$$ ($$$|y_{1,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the first group. The third line contains $$$m$$$ integers $$$y_{2,1}, y_{2,2}, \ldots, y_{2,m}$$$ ($$$|y_{2,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the second group. The $$$y$$$ coordinates are not guaranteed to be unique, even within a group.
2,100
Print a single integer – the largest number of enemy spaceships that can be destroyed.
standard output
PASSED
8107504e5a2c2fefaf0b30b3233d1c37
train_004.jsonl
1529166900
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$-100$$$, while the second group is positioned in such a way that they all have integer $$$y$$$-coordinates, and their $$$x$$$-coordinate is equal to $$$100$$$.Each spaceship in both groups will simultaneously shoot two laser shots (infinite ray that destroys any spaceship it touches), one towards each of the small spaceships, all at the same time. The small spaceships will be able to avoid all the laser shots, and now want to position themselves at some locations with $$$x=0$$$ (with not necessarily integer $$$y$$$-coordinates), such that the rays shot at them would destroy as many of the enemy spaceships as possible. Find the largest numbers of spaceships that can be destroyed this way, assuming that the enemy spaceships can't avoid laser shots.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class C { static int MAX = 40001; static int delta = 20000; public static void main(String[] args) throws IOException { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int m = sc.nextInt(); int[] valsF = new int[n], valsS = new int[m]; for (int i = 0; i < n; i++) { valsF[i] = sc.nextInt(); } for (int i = 0; i < m; i++) { valsS[i] = sc.nextInt(); } long[] first = new long[MAX], second = new long[MAX]; int total = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int index = valsF[i] + valsS[j] + delta; if (first[index] == 0) total++; first[index] |= (1L<<i); second[index] |= (1L<<j); } } long[] ff = new long[total], ss = new long[total]; int idx = 0; for (int i = 0; i < first.length; i++) { if (first[i] != 0) { ff[idx] = first[i]; ss[idx] = second[i]; idx++; } } int ans = 0; for (int i = 0; i < total; i++) { ans = Math.max(ans, Long.bitCount(ff[i]) + Long.bitCount(ss[i])); for (int j = 0; j < i; j++) { ans = Math.max(ans, Long.bitCount(ff[i]|ff[j]) + Long.bitCount(ss[i]|ss[j])); } } out.println(ans); out.flush(); } static class MyScanner { private BufferedReader br; private StringTokenizer tokenizer; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3 9\n1 2 3\n1 2 3 7 8 9 11 12 13", "5 5\n1 2 3 4 5\n1 2 3 4 5"]
2 seconds
["9", "10"]
NoteIn the first example the first spaceship can be positioned at $$$(0, 2)$$$, and the second – at $$$(0, 7)$$$. This way all the enemy spaceships in the first group and $$$6$$$ out of $$$9$$$ spaceships in the second group will be destroyed.In the second example the first spaceship can be positioned at $$$(0, 3)$$$, and the second can be positioned anywhere, it will be sufficient to destroy all the enemy spaceships.
Java 8
standard input
[ "geometry", "bitmasks", "brute force" ]
7dd891cef0aa40cc1522ca4b37963b92
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 60$$$), the number of enemy spaceships with $$$x = -100$$$ and the number of enemy spaceships with $$$x = 100$$$, respectively. The second line contains $$$n$$$ integers $$$y_{1,1}, y_{1,2}, \ldots, y_{1,n}$$$ ($$$|y_{1,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the first group. The third line contains $$$m$$$ integers $$$y_{2,1}, y_{2,2}, \ldots, y_{2,m}$$$ ($$$|y_{2,i}| \le 10\,000$$$) β€” the $$$y$$$-coordinates of the spaceships in the second group. The $$$y$$$ coordinates are not guaranteed to be unique, even within a group.
2,100
Print a single integer – the largest number of enemy spaceships that can be destroyed.
standard output
PASSED
8e83ec4c99a5b9f4810252a4f051ec30
train_004.jsonl
1521300900
There are n points on a straight line, and the i-th point among them is located at xi. All these coordinates are distinct.Determine the number m β€” the smallest number of points you should add on the line to make the distances between all neighboring points equal.
256 megabytes
import java.util.*; public class Main { public static Long gcd(Long a, Long b) { return b == 0 ? a : gcd(b, a % b); } public static void main (String[] args) { Scanner reader = new Scanner(System.in); int n = reader.nextInt(); Long[] a = new Long[n]; for (int i = 0; i < n; i++) { a[i] = reader.nextLong(); } Arrays.sort(a); Long g = a[1] - a[0]; for (int i = 2; i < n; i++) { g = gcd(g, a[i] - a[i - 1]); } Long z = new Long(0); for (int i = 1; i < n; i++) { z += (a[i] - a[i - 1]) / g - 1; } System.out.println(z); } }
Java
["3\n-5 10 5", "6\n100 200 400 300 600 500", "4\n10 9 0 -1"]
1 second
["1", "0", "8"]
NoteIn the first example you can add one point with coordinate 0.In the second example the distances between all neighboring points are already equal, so you shouldn't add anything.
Java 8
standard input
[]
805d82c407c1b34f217f8836454f7e09
The first line contains a single integer n (3 ≀ n ≀ 100 000) β€” the number of points. The second line contains a sequence of integers x1, x2, ..., xn ( - 109 ≀ xi ≀ 109) β€” the coordinates of the points. All these coordinates are distinct. The points can be given in an arbitrary order.
1,800
Print a single integer m β€” the smallest number of points you should add on the line to make the distances between all neighboring points equal.
standard output
PASSED
53e2c1b073a3a0be962c8bf5b20b995e
train_004.jsonl
1521300900
There are n points on a straight line, and the i-th point among them is located at xi. All these coordinates are distinct.Determine the number m β€” the smallest number of points you should add on the line to make the distances between all neighboring points equal.
256 megabytes
import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; import java.util.Stack; public class VKCUP { public static Long gcd(Long a,Long b) { if(b==0)return a; else return gcd(b,a%b); } public static void main(String[] args) { Scanner cin = new Scanner(System.in); int n=cin.nextInt(); Long A[]=new Long[n+10]; Long dif[]=new Long[n+10]; for(int i=1;i<=n;i++) A[i]=cin.nextLong(); Arrays.sort(A,1,n+1); for(int i=1;i<n;i++) dif[i]=A[i+1]-A[i]; long GCD=0; for(int i=1;i<n;i++) { GCD=gcd(GCD,dif[i]); } int ans=0; for(int i=1;i<n;i++) ans+=dif[i]/GCD-1; System.out.println(ans); } }
Java
["3\n-5 10 5", "6\n100 200 400 300 600 500", "4\n10 9 0 -1"]
1 second
["1", "0", "8"]
NoteIn the first example you can add one point with coordinate 0.In the second example the distances between all neighboring points are already equal, so you shouldn't add anything.
Java 8
standard input
[]
805d82c407c1b34f217f8836454f7e09
The first line contains a single integer n (3 ≀ n ≀ 100 000) β€” the number of points. The second line contains a sequence of integers x1, x2, ..., xn ( - 109 ≀ xi ≀ 109) β€” the coordinates of the points. All these coordinates are distinct. The points can be given in an arbitrary order.
1,800
Print a single integer m β€” the smallest number of points you should add on the line to make the distances between all neighboring points equal.
standard output
PASSED
3678bc559f9c80205cca5f3c2b77bdc8
train_004.jsonl
1521300900
There are n points on a straight line, and the i-th point among them is located at xi. All these coordinates are distinct.Determine the number m β€” the smallest number of points you should add on the line to make the distances between all neighboring points equal.
256 megabytes
import java.util.*; public class Sol{ public static Long GCD(Long a, Long b) { return b==0 ? a : GCD(b, a%b); } public static void main(String[] argc){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); Long [] a = new Long[n]; for(int i=0;i<n;i++){ a[i] = sc.nextLong(); } Arrays.sort( a ); Long x=a[1]-a[0]; for(int i=1;i<n;i++){ a[i]-=a[0]; if(i>1){x=GCD(x,a[i]);} } Long ans=a[n-1]/x-n+1; System.out.println(ans); } }
Java
["3\n-5 10 5", "6\n100 200 400 300 600 500", "4\n10 9 0 -1"]
1 second
["1", "0", "8"]
NoteIn the first example you can add one point with coordinate 0.In the second example the distances between all neighboring points are already equal, so you shouldn't add anything.
Java 8
standard input
[]
805d82c407c1b34f217f8836454f7e09
The first line contains a single integer n (3 ≀ n ≀ 100 000) β€” the number of points. The second line contains a sequence of integers x1, x2, ..., xn ( - 109 ≀ xi ≀ 109) β€” the coordinates of the points. All these coordinates are distinct. The points can be given in an arbitrary order.
1,800
Print a single integer m β€” the smallest number of points you should add on the line to make the distances between all neighboring points equal.
standard output
PASSED
98200b70229e296e4375ef2e62a7886f
train_004.jsonl
1521300900
There are n points on a straight line, and the i-th point among them is located at xi. All these coordinates are distinct.Determine the number m β€” the smallest number of points you should add on the line to make the distances between all neighboring points equal.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.util.Collections; import java.io.InputStreamReader; import java.util.ArrayList; 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); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { private int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); List<Integer> a = new ArrayList<>(); for (int i = 0; i < n; ++i) a.add(in.nextInt()); Collections.shuffle(a); Collections.sort(a); int min = a.get(0), max = a.get(n - 1); int g = a.get(1) - a.get(0); for (int i = 1; i < n; ++i) { g = gcd(g, a.get(i) - a.get(i - 1)); } int dif = (max - min) / g; out.println(dif + 1 - n); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n-5 10 5", "6\n100 200 400 300 600 500", "4\n10 9 0 -1"]
1 second
["1", "0", "8"]
NoteIn the first example you can add one point with coordinate 0.In the second example the distances between all neighboring points are already equal, so you shouldn't add anything.
Java 8
standard input
[]
805d82c407c1b34f217f8836454f7e09
The first line contains a single integer n (3 ≀ n ≀ 100 000) β€” the number of points. The second line contains a sequence of integers x1, x2, ..., xn ( - 109 ≀ xi ≀ 109) β€” the coordinates of the points. All these coordinates are distinct. The points can be given in an arbitrary order.
1,800
Print a single integer m β€” the smallest number of points you should add on the line to make the distances between all neighboring points equal.
standard output
PASSED
8e550586e4332eb85240f2db4331ffef
train_004.jsonl
1521300900
There are n points on a straight line, and the i-th point among them is located at xi. All these coordinates are distinct.Determine the number m β€” the smallest number of points you should add on the line to make the distances between all neighboring points equal.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * # * @author pttrung */ public class B_VK2018_WildCard1 { public static long MOD = 1000000007; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); int[]data = new int[n]; PriorityQueue<Integer> q = new PriorityQueue(); for(int i = 0; i < n; i++){ data[i] = in.nextInt(); q.add(data[i]); } int index = 0; while(!q.isEmpty()){ data[index++] = q.poll(); } //out.println(Arrays.toString(data)); HashSet<Integer> set = new HashSet(); int gcd = 0; for(int i = 1; i < n; i++){ set.add(data[i] - data[i - 1]); gcd = data[i] - data[i - 1]; } for(int i : set){ gcd = (int)gcd(gcd, i); } int re = 0; for(int i = 1; i < n; i++){ re += ((data[i] - data[i - 1])/gcd) - 1; } out.println(re); out.close(); } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return Integer.compare(x, o.x); } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b, long MOD) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2, MOD); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["3\n-5 10 5", "6\n100 200 400 300 600 500", "4\n10 9 0 -1"]
1 second
["1", "0", "8"]
NoteIn the first example you can add one point with coordinate 0.In the second example the distances between all neighboring points are already equal, so you shouldn't add anything.
Java 8
standard input
[]
805d82c407c1b34f217f8836454f7e09
The first line contains a single integer n (3 ≀ n ≀ 100 000) β€” the number of points. The second line contains a sequence of integers x1, x2, ..., xn ( - 109 ≀ xi ≀ 109) β€” the coordinates of the points. All these coordinates are distinct. The points can be given in an arbitrary order.
1,800
Print a single integer m β€” the smallest number of points you should add on the line to make the distances between all neighboring points equal.
standard output
PASSED
3f79eb819af2d1f802c725c161edb359
train_004.jsonl
1521300900
There are n points on a straight line, and the i-th point among them is located at xi. All these coordinates are distinct.Determine the number m β€” the smallest number of points you should add on the line to make the distances between all neighboring points equal.
256 megabytes
import java.util.*; import java.io.*; public class Main{ public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(System.in); int n=sc.nextInt(); ArrayList <Long> arr=new ArrayList(); for(int i=0;i<n;i++){ arr.add(sc.nextLong()); } Collections.sort(arr); Long[] a=arr.toArray(new Long[n]); long g=a[1]-a[0]; for(int i=1;i<n;i++){ g=gcd(g,a[i]-a[i-1]); } long ans=0; for(int i=1;i<n;i++){ long d=a[i]-a[i-1]; ans+=d/g-1; } System.out.println(ans); } public static long gcd(long c,long b){ if(c%b==0)return b; return gcd(b,c%b); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream i) { br = new BufferedReader(new InputStreamReader(i)); st = new StringTokenizer(""); } public String next() throws IOException { if (st.hasMoreTokens()) { return st.nextToken(); } else { st = new StringTokenizer(br.readLine()); } return next(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
Java
["3\n-5 10 5", "6\n100 200 400 300 600 500", "4\n10 9 0 -1"]
1 second
["1", "0", "8"]
NoteIn the first example you can add one point with coordinate 0.In the second example the distances between all neighboring points are already equal, so you shouldn't add anything.
Java 8
standard input
[]
805d82c407c1b34f217f8836454f7e09
The first line contains a single integer n (3 ≀ n ≀ 100 000) β€” the number of points. The second line contains a sequence of integers x1, x2, ..., xn ( - 109 ≀ xi ≀ 109) β€” the coordinates of the points. All these coordinates are distinct. The points can be given in an arbitrary order.
1,800
Print a single integer m β€” the smallest number of points you should add on the line to make the distances between all neighboring points equal.
standard output
PASSED
7e6fc47cde86755ae6bf6582d3c3f3ba
train_004.jsonl
1521300900
There are n points on a straight line, and the i-th point among them is located at xi. All these coordinates are distinct.Determine the number m β€” the smallest number of points you should add on the line to make the distances between all neighboring points equal.
256 megabytes
import java.util.*; import java.util.concurrent.ThreadLocalRandom; public class Main { public static void main(String[] args) { Main main = new Main(); main.begin(); } int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } int max(int a, int b) { return a > b ? a : b; } int min(int a, int b) { return a < b ? a : b; } static void shuffleArray(int[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } void begin() { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } shuffleArray(a); Arrays.sort(a); int[] diff = new int[n - 1]; for (int i = 1; i < n; i++) { diff[i - 1] = a[i] - a[i - 1]; } int gcdNow = gcd(max(diff[0], diff[1]), min(diff[0], diff[1])); for (int i = 2; i < n - 1; i++) { gcdNow = gcd(max(gcdNow, diff[i]), min(gcdNow, diff[i])); } int ans = 0; for (int i = 0; i < n - 1; i++) { ans += diff[i] / gcdNow; ans--; } System.out.println(ans); sc.close(); } }
Java
["3\n-5 10 5", "6\n100 200 400 300 600 500", "4\n10 9 0 -1"]
1 second
["1", "0", "8"]
NoteIn the first example you can add one point with coordinate 0.In the second example the distances between all neighboring points are already equal, so you shouldn't add anything.
Java 8
standard input
[]
805d82c407c1b34f217f8836454f7e09
The first line contains a single integer n (3 ≀ n ≀ 100 000) β€” the number of points. The second line contains a sequence of integers x1, x2, ..., xn ( - 109 ≀ xi ≀ 109) β€” the coordinates of the points. All these coordinates are distinct. The points can be given in an arbitrary order.
1,800
Print a single integer m β€” the smallest number of points you should add on the line to make the distances between all neighboring points equal.
standard output