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
fe9673c7403cf30af249fda92bc32c27
train_001.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai & x, where & denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.io.PrintWriter; import java.util.Scanner; /** * Created by Minology on 07:42 SA */ public class B { public static void main(String[] args){ Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); out.print(solver.solve(in, out)); out.close(); } static class Task{ public int solve(Scanner in, PrintWriter out){ int n, x; int[] a = new int[100001]; int[] cnt = new int[100001]; n = in.nextInt(); x = in.nextInt(); for(int i = 1; i <= n; ++i) a[i] = in.nextInt(); for(int i = 1; i <= n; ++i) ++cnt[a[i]]; for(int i = 1; i <= n; ++i) if (cnt[a[i]] > 1) return 0; for(int i = 1; i <= n; ++i){ --cnt[a[i]]; if (cnt[a[i] & x] > 0) return 1; ++cnt[a[i]]; } for(int i = 1; i <= n; ++i) --cnt[a[i]]; for(int i = 1; i <= n; ++i) ++cnt[a[i] & x]; for(int i = 1; i <= n; ++i) if (cnt[a[i] & x] > 1) return 2; return -1; } } }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
ac7a202955843db38109b1e71e4a377a
train_001.jsonl
1532938500
There is an array with n elements a1, a2, ..., an and the number x.In one operation you can select some i (1 ≀ i ≀ n) and replace element ai with ai &amp; x, where &amp; denotes the bitwise and operation.You want the array to have at least two equal elements after applying some operations (possibly, none). In other words, there should be at least two distinct indices i ≠ j such that ai = aj. Determine whether it is possible to achieve and, if possible, the minimal number of operations to apply.
256 megabytes
import java.io.*; import java.util.NoSuchElementException; public class Main_1013B { private static Scanner sc; private static Printer pr; private static void solve() { int n = sc.nextInt(); int x = sc.nextInt(); int[] a = sc.nextIntArray(n); int[] cnt = new int[100_000 + 1]; for (int e : a) { cnt[e]++; } for (int i = 0; i < 100_000; i++) { if (cnt[i] > 1) { pr.println(0); return; } } int[] aa = new int[n]; for (int i = 0; i < n; i++) { aa[i] = a[i] & x; } int[] cnt2 = new int[100_000 + 1]; for (int e : aa) { cnt2[e]++; } int min = Integer.MAX_VALUE; for (int i = 0; i < 100_000; i++) { if (cnt2[i] > 1) { if (cnt[i] == 1) { min = Math.min(min, 1); } else { min = Math.min(min, 2); } } } if (min == Integer.MAX_VALUE) { pr.println(-1); } else { pr.println(min); } } // --------------------------------------------------- public static void main(String[] args) { sc = new Scanner(System.in); pr = new Printer(System.out); solve(); pr.close(); sc.close(); } static class Scanner { BufferedReader br; Scanner (InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } private boolean isPrintable(int ch) { return ch >= '!' && ch <= '~'; } private boolean isCRLF(int ch) { return ch == '\n' || ch == '\r' || ch == -1; } private int nextPrintable() { try { int ch; while (!isPrintable(ch = br.read())) { if (ch == -1) { throw new NoSuchElementException(); } } return ch; } catch (IOException e) { throw new NoSuchElementException(); } } String next() { try { int ch = nextPrintable(); StringBuilder sb = new StringBuilder(); do { sb.appendCodePoint(ch); } while (isPrintable(ch = br.read())); return sb.toString(); } catch (IOException e) { throw new NoSuchElementException(); } } int nextInt() { try { // parseInt from Integer.parseInt() boolean negative = false; int res = 0; int limit = -Integer.MAX_VALUE; int radix = 10; int fc = nextPrintable(); if (fc < '0') { if (fc == '-') { negative = true; limit = Integer.MIN_VALUE; } else if (fc != '+') { throw new NumberFormatException(); } fc = br.read(); } int multmin = limit / radix; int ch = fc; do { int digit = ch - '0'; if (digit < 0 || digit >= radix) { throw new NumberFormatException(); } if (res < multmin) { throw new NumberFormatException(); } res *= radix; if (res < limit + digit) { throw new NumberFormatException(); } res -= digit; } while (isPrintable(ch = br.read())); return negative ? res : -res; } catch (IOException e) { throw new NoSuchElementException(); } } long nextLong() { try { // parseLong from Long.parseLong() boolean negative = false; long res = 0; long limit = -Long.MAX_VALUE; int radix = 10; int fc = nextPrintable(); if (fc < '0') { if (fc == '-') { negative = true; limit = Long.MIN_VALUE; } else if (fc != '+') { throw new NumberFormatException(); } fc = br.read(); } long multmin = limit / radix; int ch = fc; do { int digit = ch - '0'; if (digit < 0 || digit >= radix) { throw new NumberFormatException(); } if (res < multmin) { throw new NumberFormatException(); } res *= radix; if (res < limit + digit) { throw new NumberFormatException(); } res -= digit; } while (isPrintable(ch = br.read())); return negative ? res : -res; } catch (IOException e) { throw new NoSuchElementException(); } } float nextFloat() { return Float.parseFloat(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { int ch; while (isCRLF(ch = br.read())) { if (ch == -1) { throw new NoSuchElementException(); } } StringBuilder sb = new StringBuilder(); do { sb.appendCodePoint(ch); } while (!isCRLF(ch = br.read())); return sb.toString(); } catch (IOException e) { throw new NoSuchElementException(); } } int[] nextIntArray(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = sc.nextInt(); } return ret; } long[] nextLongArray(int n) { long[] ret = new long[n]; for (int i = 0; i < n; i++) { ret[i] = sc.nextLong(); } return ret; } int[][] nextIntArrays(int n, int m) { int[][] ret = new int[m][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ret[j][i] = sc.nextInt(); } } return ret; } void close() { try { br.close(); } catch (IOException e) { // throw new NoSuchElementException(); } } } static class Printer extends PrintWriter { Printer(OutputStream out) { super(out); } void printInts(int... a) { StringBuilder sb = new StringBuilder(32); for (int i = 0, size = a.length; i < size; i++) { if (i > 0) { sb.append(' '); } sb.append(a[i]); } println(sb); } void printLongs(long... a) { StringBuilder sb = new StringBuilder(64); for (int i = 0, size = a.length; i < size; i++) { if (i > 0) { sb.append(' '); } sb.append(a[i]); } println(sb); } void printStrings(String... a) { StringBuilder sb = new StringBuilder(32); for (int i = 0, size = a.length; i < size; i++) { if (i > 0) { sb.append(' '); } sb.append(a[i]); } println(sb); } } }
Java
["4 3\n1 2 3 7", "2 228\n1 1", "3 7\n1 2 3"]
1 second
["1", "0", "-1"]
NoteIn the first example one can apply the operation to the last element of the array. That replaces 7 with 3, so we achieve the goal in one move.In the second example the array already has two equal elements.In the third example applying the operation won't change the array at all, so it is impossible to make some pair of elements equal.
Java 8
standard input
[ "greedy" ]
f4bb0b8f285b0c8cbaf469964505cc56
The first line contains integers n and x (2 ≀ n ≀ 100 000, 1 ≀ x ≀ 100 000), number of elements in the array and the number to and with. The second line contains n integers ai (1 ≀ ai ≀ 100 000), the elements of the array.
1,200
Print a single integer denoting the minimal number of operations to do, or -1, if it is impossible.
standard output
PASSED
445e660204167410c1fd227aa048db94
train_001.jsonl
1490803500
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i &gt; 1 the respective term satisfies the condition bi = bi - 1Β·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a1, a2, ..., am, and an integer l.Masha writes all progression terms one by one onto the board (including repetitive) while condition |bi| ≀ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
256 megabytes
import java.io.*; import java.util.*; public class ProblemB { 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 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(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[50000]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public 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(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[5000]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static int gcd(int p,int q){ while(q!=0){ int temp=q; q=p%q; p=temp; } return p; } public static void main(String[] args)throws IOException{ Reader in=new Reader(); OutputWriter out=new OutputWriter(System.out); long b1=in.nextLong(); long q=in.nextLong(); long l=in.nextLong(); long m=in.nextLong(); HashSet<Long> H=new HashSet<Long>(); for(int i=0;i<m;i++){ H.add(in.nextLong()); } if(Math.abs(b1)>l){ System.out.print(0); } else if(b1==0){ if(H.contains(0L)){ System.out.println(0); } else{ System.out.println("inf"); } } else if(q==1 || q==-1){ if(H.contains(b1) && H.contains(q*b1)){ System.out.print(0); } else{ System.out.print("inf"); } } else if(q==0){ if(!H.contains(0L)){ System.out.print("inf"); } else if(H.contains(b1)){ System.out.print(0); } else{ System.out.print(1); } } else{ long current = b1; int count=0; while(Math.abs(current)<=l){ if(H.contains(current)){ current*=q; } else{ count++; current*=q; } } System.out.print(count); } } }
Java
["3 2 30 4\n6 14 25 48", "123 1 2143435 4\n123 11 -5453 141245", "123 1 2143435 4\n54343 -13 6 124"]
1 second
["3", "0", "inf"]
NoteIn the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value.In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.In the third case, Masha will write infinitely integers 123.
Java 8
standard input
[ "implementation", "brute force", "math" ]
749c290c48272a53e2e79730dab0538e
The first line of input contains four integers b1, q, l, m (-109 ≀ b1, q ≀ 109, 1 ≀ l ≀ 109, 1 ≀ m ≀ 105)Β β€” the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively. The second line contains m distinct integers a1, a2, ..., am (-109 ≀ ai ≀ 109)Β β€” numbers that will never be written on the board.
1,700
Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.
standard output
PASSED
9211f5c7a6be9e6919c8fe2ff26889f4
train_001.jsonl
1490803500
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i &gt; 1 the respective term satisfies the condition bi = bi - 1Β·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a1, a2, ..., am, and an integer l.Masha writes all progression terms one by one onto the board (including repetitive) while condition |bi| ≀ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; public class Main{ public static void main(String[] args) throws IOException { //String IN = "C:\\Users\\ugochukwu.okeke\\Desktop\\in.file"; //String OUT = "C:\\Users\\ugochukwu.okeke\\Desktop\\out.file"; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); String[] in = br.readLine().split(" "); long b = Long.parseLong(in[0]); long q = Long.parseLong(in[1]); long l = Long.parseLong(in[2]); int m = Integer.parseInt(in[3]); HashSet<Long> H = new HashSet<>(); in = br.readLine().split(" "); for(int i=0;i<m;i++) { H.add(Long.parseLong(in[i])); } if(Math.abs(b) > l) bw.append("0\n"); else{ if(b == 0 || q==1) { bw.append((H.contains(b)?0:"inf")+"\n"); } else if(q==-1){ bw.append((H.contains(b)&&H.contains(-b)?0:"inf")+"\n"); } else if(q==0){ if(!H.contains(1l*0)) bw.append("inf\n"); else{ bw.append((H.contains(b)?0:"1")+"\n"); } } else{ int cnt = 0; int p = 0; while(true) { b = b*(cnt==0?1:q); if(H.contains(b)) { cnt++; continue; } else{ if(Math.abs(b) <= l) { p++; cnt++; } else { break; } } } bw.append(p+"\n");} } bw.close(); } }
Java
["3 2 30 4\n6 14 25 48", "123 1 2143435 4\n123 11 -5453 141245", "123 1 2143435 4\n54343 -13 6 124"]
1 second
["3", "0", "inf"]
NoteIn the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value.In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.In the third case, Masha will write infinitely integers 123.
Java 8
standard input
[ "implementation", "brute force", "math" ]
749c290c48272a53e2e79730dab0538e
The first line of input contains four integers b1, q, l, m (-109 ≀ b1, q ≀ 109, 1 ≀ l ≀ 109, 1 ≀ m ≀ 105)Β β€” the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively. The second line contains m distinct integers a1, a2, ..., am (-109 ≀ ai ≀ 109)Β β€” numbers that will never be written on the board.
1,700
Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.
standard output
PASSED
a8611be365a6b2a77cc1d1ab814a20ef
train_001.jsonl
1490803500
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i &gt; 1 the respective term satisfies the condition bi = bi - 1Β·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a1, a2, ..., am, and an integer l.Masha writes all progression terms one by one onto the board (including repetitive) while condition |bi| ≀ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
256 megabytes
import java.util.HashSet; import java.util.Scanner; import java.io.PrintWriter; /* * Examples input 3 2 30 4 6 14 25 48 output 3 input 123 1 2143435 4 123 11 -5453 141245 output 0 input 123 1 2143435 4 54343 -13 6 124 output inf */ public class P789B_Masha_and_geometric_depression { private static PrintWriter pw; public static void main(String[] args) { Scanner in = new Scanner(System.in); pw = new PrintWriter(System.out); int b1 = in.nextInt(); int q = in.nextInt(); long l = in.nextLong(); int m = in.nextInt(); int i, answer = 0; long b = b1; HashSet<Integer> a = new HashSet<Integer>(); HashSet<Integer> B = new HashSet<Integer>(); B.add(b1); for (i = 0; i < m; i++) { a.add(in.nextInt()); } boolean[] isBanned = new boolean[2]; int nRepeat = 0; while (Math.abs(b) <= l) { boolean toBan = a.contains((int)b); if (!toBan) { answer++; } b *= q; if (B.contains((int)b)) { isBanned[nRepeat] = toBan; if (++nRepeat > 1) break; } B.add((int)b); } if (answer > 0 && nRepeat > 1 && (!isBanned[0] || !isBanned[1])) { pw.printf("inf\n", answer); } else { pw.printf("%d\n", answer); } in.close(); pw.close(); } }
Java
["3 2 30 4\n6 14 25 48", "123 1 2143435 4\n123 11 -5453 141245", "123 1 2143435 4\n54343 -13 6 124"]
1 second
["3", "0", "inf"]
NoteIn the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value.In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.In the third case, Masha will write infinitely integers 123.
Java 8
standard input
[ "implementation", "brute force", "math" ]
749c290c48272a53e2e79730dab0538e
The first line of input contains four integers b1, q, l, m (-109 ≀ b1, q ≀ 109, 1 ≀ l ≀ 109, 1 ≀ m ≀ 105)Β β€” the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively. The second line contains m distinct integers a1, a2, ..., am (-109 ≀ ai ≀ 109)Β β€” numbers that will never be written on the board.
1,700
Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.
standard output
PASSED
7579ff2347e0f4da266ec573de68f8c0
train_001.jsonl
1490803500
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i &gt; 1 the respective term satisfies the condition bi = bi - 1Β·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a1, a2, ..., am, and an integer l.Masha writes all progression terms one by one onto the board (including repetitive) while condition |bi| ≀ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
256 megabytes
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; /** * Created by n1k1t4 on 07.04.17. */ public class CF407_2 { private static int firstElement; private static int multiplier; private static int maxSequenceValue; private static List<Integer> badElements; public static void main(String[] args) throws IOException { readInputParams(); if (Math.abs(firstElement) > maxSequenceValue) { System.out.println(0); return; } if (multiplier == 0 || firstElement == 0) { if (badElements.contains(0)) { if (badElements.contains(firstElement)) { System.out.println(0); } else { System.out.println(1); } } else { System.out.println("inf"); } return; } if (multiplier == 1) { if (badElements.contains(firstElement)) { System.out.println(0); } else { System.out.println("inf"); } return; } if (multiplier == -1) { if (badElements.contains(firstElement) && badElements.contains(-firstElement)) { System.out.println(0); } else { System.out.println("inf"); } return; } long sequenceValue = firstElement; int elementsCount = 0; while (Math.abs(sequenceValue) <= maxSequenceValue) { if (!badElements.contains((int)sequenceValue)) { elementsCount++; } sequenceValue *= multiplier; } System.out.println(elementsCount); } private static void readInputParams() throws IOException { try (Scanner scanner = new Scanner(System.in)) { firstElement = scanner.nextInt(); multiplier = scanner.nextInt(); maxSequenceValue = scanner.nextInt(); int badElementsCount = scanner.nextInt(); badElements = new ArrayList<>(badElementsCount); for (int i = 0; i < badElementsCount; i++) { badElements.add(scanner.nextInt()); } } } }
Java
["3 2 30 4\n6 14 25 48", "123 1 2143435 4\n123 11 -5453 141245", "123 1 2143435 4\n54343 -13 6 124"]
1 second
["3", "0", "inf"]
NoteIn the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value.In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.In the third case, Masha will write infinitely integers 123.
Java 8
standard input
[ "implementation", "brute force", "math" ]
749c290c48272a53e2e79730dab0538e
The first line of input contains four integers b1, q, l, m (-109 ≀ b1, q ≀ 109, 1 ≀ l ≀ 109, 1 ≀ m ≀ 105)Β β€” the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively. The second line contains m distinct integers a1, a2, ..., am (-109 ≀ ai ≀ 109)Β β€” numbers that will never be written on the board.
1,700
Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.
standard output
PASSED
0082707ed62636b4ca4fc7f22050e7ba
train_001.jsonl
1490803500
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i &gt; 1 the respective term satisfies the condition bi = bi - 1Β·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a1, a2, ..., am, and an integer l.Masha writes all progression terms one by one onto the board (including repetitive) while condition |bi| ≀ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; public class B { public static void main(String[] args) throws IOException{ Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int b1 = sc.nextInt(), q = sc.nextInt(), l = sc.nextInt(), n = sc.nextInt(); HashSet<Long> set = new HashSet<>(); for(int i = 0; i < n; i++) { int x = sc.nextInt(); set.add((long)x); } if(q == 1 && set.contains((long)b1) || Math.abs(b1) > l) out.println(0); else if( q == -1 && set.contains((long)b1) && set.contains((long)-b1)) out.println(0); else if(q == 0 && set.contains((long)0) && set.contains((long) b1)) out.println(0); else if(q == 0 && set.contains((long)0)) out.println(1); else if(b1 == 0 && set.contains((long) 0)) out.println(0); else if(Math.abs(q) == 1 || q == 0 || b1 == 0) out.println("inf"); else { int ans = set.contains((long)b1)? 0 : 1; long cur = 1l * b1 * q; while(Math.abs(cur) <= l) { if(!set.contains(cur)) ans++; cur *= q; } out.println(ans); } out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream System){ br = new BufferedReader(new InputStreamReader(System)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } 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(){for(long i = 0; i < 3e9; i++);} } }
Java
["3 2 30 4\n6 14 25 48", "123 1 2143435 4\n123 11 -5453 141245", "123 1 2143435 4\n54343 -13 6 124"]
1 second
["3", "0", "inf"]
NoteIn the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value.In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.In the third case, Masha will write infinitely integers 123.
Java 8
standard input
[ "implementation", "brute force", "math" ]
749c290c48272a53e2e79730dab0538e
The first line of input contains four integers b1, q, l, m (-109 ≀ b1, q ≀ 109, 1 ≀ l ≀ 109, 1 ≀ m ≀ 105)Β β€” the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively. The second line contains m distinct integers a1, a2, ..., am (-109 ≀ ai ≀ 109)Β β€” numbers that will never be written on the board.
1,700
Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.
standard output
PASSED
3c7efde5fdb03325f8557a8e8b3f1e1b
train_001.jsonl
1490803500
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i &gt; 1 the respective term satisfies the condition bi = bi - 1Β·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a1, a2, ..., am, and an integer l.Masha writes all progression terms one by one onto the board (including repetitive) while condition |bi| ≀ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.TreeSet; public class B { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); long b = sc.nextLong(); long q = sc.nextLong(); long l = sc.nextLong(); int m = sc.nextInt(); TreeSet<Long> map = new TreeSet<>(); for (int i = 0; i < m; i++) map.add(sc.nextLong()); if(Math.abs(b) > l){ System.out.println(0); return; } if(b == 0 || q == 0){ if(map.contains((long)0)) if(map.contains(b)) System.out.println(0); else System.out.println(1); else System.out.println("inf"); return; } if(q == 1){ if(map.contains(b)) System.out.println(0); else System.out.println("inf"); return; } if(q == -1){ if(map.contains(b) && map.contains(-b)) System.out.println(0); else System.out.println("inf"); return; } int count = 0; while(Math.abs(b) <= l){ if(!map.contains(b)) count++; b = b*q; } System.out.println(count); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream System) { br = new BufferedReader(new InputStreamReader(System)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } 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() { for (long i = 0; i < 3e9; i++) ; } } }
Java
["3 2 30 4\n6 14 25 48", "123 1 2143435 4\n123 11 -5453 141245", "123 1 2143435 4\n54343 -13 6 124"]
1 second
["3", "0", "inf"]
NoteIn the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value.In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.In the third case, Masha will write infinitely integers 123.
Java 8
standard input
[ "implementation", "brute force", "math" ]
749c290c48272a53e2e79730dab0538e
The first line of input contains four integers b1, q, l, m (-109 ≀ b1, q ≀ 109, 1 ≀ l ≀ 109, 1 ≀ m ≀ 105)Β β€” the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively. The second line contains m distinct integers a1, a2, ..., am (-109 ≀ ai ≀ 109)Β β€” numbers that will never be written on the board.
1,700
Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.
standard output
PASSED
2a823be59eb762e47f2f630b13a358ef
train_001.jsonl
1490803500
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i &gt; 1 the respective term satisfies the condition bi = bi - 1Β·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a1, a2, ..., am, and an integer l.Masha writes all progression terms one by one onto the board (including repetitive) while condition |bi| ≀ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashSet; import java.util.Scanner; import java.util.StringTokenizer; public class b { public static void main(String[] args) { Scanner in = new Scanner(System.in); long b1 = in.nextLong(); long q = in.nextLong(); long l = in.nextLong(); int m = in.nextInt(); HashSet<Long> bads = new HashSet<Long>(); for(int i = 0; i < m; i++) bads.add(in.nextLong()); long ans = 0; if(Math.abs(b1) > l) { System.out.println(0); return; } long loops = 0; do { loops++; if(!bads.contains(b1)) ans++; b1 *= q; } while(Math.abs(b1) <= l && loops < 1000); if(ans >= 300) ans = -1; if(ans == -1) System.out.println("inf"); else System.out.println(ans); /* if(Math.abs(b1) > l) { System.out.println(0); return; } if(q == 0) { long ans = 0; if(!bads.contains(b1)) ans++; if(!bads.contains(0)) ans = -1; if(ans == -1) System.out.println("inf"); else System.out.println(ans); } else if(q == 1) { long ans = 0; if(!bads.contains(b1)) ans = -1; if(ans == -1) System.out.println("inf"); else System.out.println(ans); } else if(q == -1) { long ans = 0; if(!bads.contains(b1)) ans = -1; if(!bads.contains(-b1)) ans = -1; if(ans == -1) System.out.println("inf"); else System.out.println(ans); } else if(b1 == 0) { long ans = 0; if(!bads.contains(0)) ans = -1; if(ans == -1) System.out.println("inf"); else System.out.println(ans); } else { long ans = 0; do { if(!bads.contains(b1)) ans++; b1 *= q; } while(Math.abs(b1) <= l); System.out.println(ans); } */ } //@ 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 2 30 4\n6 14 25 48", "123 1 2143435 4\n123 11 -5453 141245", "123 1 2143435 4\n54343 -13 6 124"]
1 second
["3", "0", "inf"]
NoteIn the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value.In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.In the third case, Masha will write infinitely integers 123.
Java 8
standard input
[ "implementation", "brute force", "math" ]
749c290c48272a53e2e79730dab0538e
The first line of input contains four integers b1, q, l, m (-109 ≀ b1, q ≀ 109, 1 ≀ l ≀ 109, 1 ≀ m ≀ 105)Β β€” the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively. The second line contains m distinct integers a1, a2, ..., am (-109 ≀ ai ≀ 109)Β β€” numbers that will never be written on the board.
1,700
Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.
standard output
PASSED
9b259119d366a760442cb1ac2800f7d5
train_001.jsonl
1490803500
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i &gt; 1 the respective term satisfies the condition bi = bi - 1Β·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a1, a2, ..., am, and an integer l.Masha writes all progression terms one by one onto the board (including repetitive) while condition |bi| ≀ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Pradyumn Agrawal coderbond007 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public static FastReader check; public void solve(int testNumber, FastReader in, PrintWriter out) { check = in; long b1 = nl(); long q = nl(); long l = nl(); int m = ni(); HashMap<Long, Integer> map = new HashMap<>(); for (int i = 0; i < m; i++) { map.put(nl(), 1); } if (Math.abs(b1) > l) { out.println(0); return; } if (b1 == 0) { if (map.containsKey(b1)) { out.println(0); } else { out.println("inf"); } } else { if (q == 0) { if (!map.containsKey(0L)) { out.println("inf"); } else { if (map.containsKey(b1)) { out.println(0); } else { out.println(1); } } } else if (q == 1) { if (map.containsKey(b1)) { out.println(0); } else { out.println("inf"); } } else if (q == -1) { if (map.containsKey(b1) && map.containsKey(-b1)) { out.println(0); } else { out.println("inf"); } } else { long temp = b1; int ct = 0; while (Math.abs(temp) <= l) { if (!map.containsKey(temp)) { ct++; } temp *= q; } out.println(ct); } } } private static int ni() { return check.nextInt(); } private static long nl() { return check.nextLong(); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(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 == ',') { c = read(); } 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
["3 2 30 4\n6 14 25 48", "123 1 2143435 4\n123 11 -5453 141245", "123 1 2143435 4\n54343 -13 6 124"]
1 second
["3", "0", "inf"]
NoteIn the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value.In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.In the third case, Masha will write infinitely integers 123.
Java 8
standard input
[ "implementation", "brute force", "math" ]
749c290c48272a53e2e79730dab0538e
The first line of input contains four integers b1, q, l, m (-109 ≀ b1, q ≀ 109, 1 ≀ l ≀ 109, 1 ≀ m ≀ 105)Β β€” the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively. The second line contains m distinct integers a1, a2, ..., am (-109 ≀ ai ≀ 109)Β β€” numbers that will never be written on the board.
1,700
Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.
standard output
PASSED
98328e924f48a9233b445b212fe8b210
train_001.jsonl
1490803500
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i &gt; 1 the respective term satisfies the condition bi = bi - 1Β·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a1, a2, ..., am, and an integer l.Masha writes all progression terms one by one onto the board (including repetitive) while condition |bi| ≀ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
256 megabytes
import java.io.InputStream; import java.io.BufferedReader; import java.io.PrintWriter; import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedWriter; import java.io.OutputStreamWriter; import java.math.BigInteger; import java.math.BigDecimal; import java.util.*; import java.util.stream.Stream; /** * * @author Pradyumn Agrawal coderbond007 */ public class B{ public static InputStream inputStream = System.in; public static StringTokenizer tok = null; public static BufferedReader br = new BufferedReader(new InputStreamReader(inputStream), 32768); public static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public static void main(String[] args) throws java.lang.Exception{ new Thread(null, new Runnable() { public void run() { try { new B().run(); out.close(); } catch(IOException e){ } } }, "1", 1 << 26).start(); } public void run() throws IOException { long b1 = nl(); long q = nl(); long l = nl(); int m = ni(); HashMap<Long,Integer> map = new HashMap<>(); for(int i = 0;i < m; i++){ map.put(nl(),1); } if(Math.abs(b1) > l){ out.println(0); return; } if(b1 == 0){ if(map.containsKey(b1)){ out.println(0); } else { out.println("inf"); } } else { if(q == 0){ if(!map.containsKey(0L)){ out.println("inf"); } else { if(map.containsKey(b1)){ out.println(0); } else { out.println(1); } } } else if(q == 1){ if(map.containsKey(b1)){ out.println(0); } else { out.println("inf"); } } else if(q == -1){ if(map.containsKey(b1) && map.containsKey(-b1)){ out.println(0); } else { out.println("inf"); } } else { long temp = b1; int ct = 0; while(Math.abs(temp) <= l){ if(!map.containsKey(temp)){ ct++; } temp *= q; } out.println(ct); } } } private void debug(Object... objects){ if(objects.length > 0){ out.println(Arrays.deepToString(objects)); } } public static int ni() throws IOException { return Integer.parseInt(ns()); } public static long nl() throws IOException { return Long.parseLong(ns()); } public static double nd() throws IOException { return Double.parseDouble(ns()); } public static char nc() throws IOException { return ns().charAt(0); } public static BigInteger nextBigInteger() throws IOException { return new BigInteger(ns()); } public static String ns() throws IOException { while(tok == null || !tok.hasMoreTokens()){ try { tok = new StringTokenizer(br.readLine()); } catch (IOException e){ throw new RuntimeException(e); } } return tok.nextToken(); } public static int[] na(int n) throws IOException { int[] a = new int[n]; for(int i = 0;i < n; i++){ a[i] = ni(); } return a; } public static long[] nal(int n) throws IOException { long[] a = new long[n]; for(int i = 0;i < n; i++){ a[i] = nl(); } return a; } public static char[] ns(int n) throws IOException { return ns().substring(0,n).toCharArray(); } public static char[][] nm(int n, int m) throws IOException{ char[][] map = new char[n][]; for(int i = 0;i < n; i++){ map[i] = ns(m); } return map; } public static String readLine() { try { return br.readLine(); } catch(IOException e){ throw new RuntimeException(e); } } }
Java
["3 2 30 4\n6 14 25 48", "123 1 2143435 4\n123 11 -5453 141245", "123 1 2143435 4\n54343 -13 6 124"]
1 second
["3", "0", "inf"]
NoteIn the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value.In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.In the third case, Masha will write infinitely integers 123.
Java 8
standard input
[ "implementation", "brute force", "math" ]
749c290c48272a53e2e79730dab0538e
The first line of input contains four integers b1, q, l, m (-109 ≀ b1, q ≀ 109, 1 ≀ l ≀ 109, 1 ≀ m ≀ 105)Β β€” the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively. The second line contains m distinct integers a1, a2, ..., am (-109 ≀ ai ≀ 109)Β β€” numbers that will never be written on the board.
1,700
Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.
standard output
PASSED
d305b0033513d0ddd4e70ce2c63729ac
train_001.jsonl
1490803500
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i &gt; 1 the respective term satisfies the condition bi = bi - 1Β·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a1, a2, ..., am, and an integer l.Masha writes all progression terms one by one onto the board (including repetitive) while condition |bi| ≀ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
256 megabytes
import java.util.Arrays; import java.util.HashMap; import java.util.PriorityQueue; import java.util.Scanner; public class Problem2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long b1 = sc.nextLong(); long q = sc.nextLong(); long l = sc.nextLong(); int m = sc.nextInt(); long a[] = new long[m]; HashMap<Long, Boolean> hm = new HashMap<Long, Boolean>(); for(int i = 0; i < m; i++){ a[i] = sc.nextLong(); hm.put(a[i], true); } if(Math.abs(q) == 0 && hm.get(b1) == null){ if(Math.abs(b1) <= l && hm.get(q) != null) System.out.println(1); else if(Math.abs(b1) > l) System.out.println(0); else if(Math.abs(b1) <= l && hm.get(0) == null) System.out.println("inf"); } else if(Math.abs(q) <= 1 || b1 == 0){ int f = 0; if(hm.get(b1) != null && hm.get(b1*q) != null){ System.out.println(0); f = 1; } if(f == 0){ if(Math.abs(b1) <= l) System.out.println("inf"); else System.out.println(0); } } else{ //double lim = Math.ceil((Math.log((double)l))/(Math.log(2))); long s = b1; int c = 0; while(Math.abs(s) <= l){ if(hm.get(s)== null){ c++; } s = s*q; } System.out.println(c); } } }
Java
["3 2 30 4\n6 14 25 48", "123 1 2143435 4\n123 11 -5453 141245", "123 1 2143435 4\n54343 -13 6 124"]
1 second
["3", "0", "inf"]
NoteIn the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value.In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.In the third case, Masha will write infinitely integers 123.
Java 8
standard input
[ "implementation", "brute force", "math" ]
749c290c48272a53e2e79730dab0538e
The first line of input contains four integers b1, q, l, m (-109 ≀ b1, q ≀ 109, 1 ≀ l ≀ 109, 1 ≀ m ≀ 105)Β β€” the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively. The second line contains m distinct integers a1, a2, ..., am (-109 ≀ ai ≀ 109)Β β€” numbers that will never be written on the board.
1,700
Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.
standard output
PASSED
c4f12964e6e2ba67b45e07f972bd2949
train_001.jsonl
1490803500
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i &gt; 1 the respective term satisfies the condition bi = bi - 1Β·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a1, a2, ..., am, and an integer l.Masha writes all progression terms one by one onto the board (including repetitive) while condition |bi| ≀ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Balajiganapathi */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, Scanner in, PrintWriter out) { int b1, q, l, m; b1 = in.nextInt(); q = in.nextInt(); l = in.nextInt(); m = in.nextInt(); int a[] = new int[m]; for(int i = 0; i < m; ++i) a[i] = in.nextInt(); Arrays.sort(a); int cnt = 0, iters = 0; for(long i = b1; Math.abs(i) <= l && iters++ < 200; i *= q) if(Arrays.binarySearch(a, (int) i) < 0) { ++cnt; } if(cnt >= 50) { out.println("inf"); } else { out.print(cnt); } } } }
Java
["3 2 30 4\n6 14 25 48", "123 1 2143435 4\n123 11 -5453 141245", "123 1 2143435 4\n54343 -13 6 124"]
1 second
["3", "0", "inf"]
NoteIn the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value.In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.In the third case, Masha will write infinitely integers 123.
Java 8
standard input
[ "implementation", "brute force", "math" ]
749c290c48272a53e2e79730dab0538e
The first line of input contains four integers b1, q, l, m (-109 ≀ b1, q ≀ 109, 1 ≀ l ≀ 109, 1 ≀ m ≀ 105)Β β€” the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively. The second line contains m distinct integers a1, a2, ..., am (-109 ≀ ai ≀ 109)Β β€” numbers that will never be written on the board.
1,700
Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.
standard output
PASSED
ac7e95d7145ddccad25177acd057d841
train_001.jsonl
1490803500
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i &gt; 1 the respective term satisfies the condition bi = bi - 1Β·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a1, a2, ..., am, and an integer l.Masha writes all progression terms one by one onto the board (including repetitive) while condition |bi| ≀ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; /** */ public class Main789B { public static void main(String[] args) { FastScanner in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); run(in, System.out); } public static void runTest(InputStream is, PrintStream out) { FastScanner in = new FastScanner(new BufferedReader(new InputStreamReader(is))); run(in, out); } public static void run(FastScanner in, PrintStream out) { int b1 = in.nextInt(); int q = in.nextInt(); int l = in.nextInt(); int m = in.nextInt(); Set<Integer> bad = new HashSet<Integer>(m); for (int i = 0; i < m; i++) { int v = in.nextInt(); if (abs(v) <= l) bad.add(v); } if (abs(b1) > l) { out.print(0); return; } else if (b1 == 0) { if (bad.contains(0)) { out.print(0); return; } out.print("inf"); return; } else if (q == 0) { int res = 1; if (bad.contains(b1)) { res = 0; } if (bad.contains(0)) { out.print(res); return; } out.print("inf"); return; } else if (q == 1) { if (bad.contains(b1)) { out.print(0); return; } out.print("inf"); return; } else if (q == -1) { if (bad.contains(b1) && bad.contains(-b1)) { out.print(0); return; } out.print("inf"); return; }else { long val = b1; int res = 0; while (abs(val) <= l) { if (!bad.contains((int) val)) { res++; } val = val * q; } out.print(res); } } static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } public static long abs(long a) { if (a < 0) return -a; else return a; } public static int abs(int a) { if (a < 0) return -a; else return a; } }
Java
["3 2 30 4\n6 14 25 48", "123 1 2143435 4\n123 11 -5453 141245", "123 1 2143435 4\n54343 -13 6 124"]
1 second
["3", "0", "inf"]
NoteIn the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value.In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.In the third case, Masha will write infinitely integers 123.
Java 8
standard input
[ "implementation", "brute force", "math" ]
749c290c48272a53e2e79730dab0538e
The first line of input contains four integers b1, q, l, m (-109 ≀ b1, q ≀ 109, 1 ≀ l ≀ 109, 1 ≀ m ≀ 105)Β β€” the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively. The second line contains m distinct integers a1, a2, ..., am (-109 ≀ ai ≀ 109)Β β€” numbers that will never be written on the board.
1,700
Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.
standard output
PASSED
d7118f4bda06d065df27f421abe14104
train_001.jsonl
1490803500
Masha really loves algebra. On the last lesson, her strict teacher Dvastan gave she new exercise.You are given geometric progression b defined by two integers b1 and q. Remind that a geometric progression is a sequence of integers b1, b2, b3, ..., where for each i &gt; 1 the respective term satisfies the condition bi = bi - 1Β·q, where q is called the common ratio of the progression. Progressions in Uzhlyandia are unusual: both b1 and q can equal 0. Also, Dvastan gave Masha m "bad" integers a1, a2, ..., am, and an integer l.Masha writes all progression terms one by one onto the board (including repetitive) while condition |bi| ≀ l is satisfied (|x| means absolute value of x). There is an exception: if a term equals one of the "bad" integers, Masha skips it (doesn't write onto the board) and moves forward to the next term.But the lesson is going to end soon, so Masha has to calculate how many integers will be written on the board. In order not to get into depression, Masha asked you for help: help her calculate how many numbers she will write, or print "inf" in case she needs to write infinitely many integers.
256 megabytes
import java.io.*; import java.util.*; import java.util.Map.Entry; import static java.lang.Math.*; public class Main { // :( public static void solve(FastScanner in, BufferedWriter out) throws IOException { long b = in.nextInt(), q = in.nextInt(), l = abs(in.nextInt()), m = in.nextInt(); HashSet<Long> bad = new HashSet<>(); for (int i = 0; i< m; i++) bad.add(Long.valueOf(in.nextInt())); long prog = b; long prev = -b; boolean isInfy = false; int ans = 0; while(abs(prog) <= l) { if(!bad.contains(prog)) { ans++; } if(prog == prog * q || prog * q == prev ) { if(!bad.contains(prog * q)) isInfy = true; else if(q == -1 && !bad.contains(-1 * prog * q) ) isInfy = true; break; } prev = prog; prog *= q; } if(isInfy) out.append("inf"); else out.append(String.valueOf(ans)); } /**************** ENTER HERE ********************/ public static void main(String[] args) throws Exception { FastScanner fscan = new FastScanner(System.in); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); solve(fscan,bw); bw.close(); } } class FastScanner { StringTokenizer st; BufferedReader br; public FastScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } }
Java
["3 2 30 4\n6 14 25 48", "123 1 2143435 4\n123 11 -5453 141245", "123 1 2143435 4\n54343 -13 6 124"]
1 second
["3", "0", "inf"]
NoteIn the first sample case, Masha will write integers 3, 12, 24. Progression term 6 will be skipped because it is a "bad" integer. Terms bigger than 24 won't be written because they exceed l by absolute value.In the second case, Masha won't write any number because all terms are equal 123 and this is a "bad" integer.In the third case, Masha will write infinitely integers 123.
Java 8
standard input
[ "implementation", "brute force", "math" ]
749c290c48272a53e2e79730dab0538e
The first line of input contains four integers b1, q, l, m (-109 ≀ b1, q ≀ 109, 1 ≀ l ≀ 109, 1 ≀ m ≀ 105)Β β€” the initial term and the common ratio of progression, absolute value of maximal number that can be written on the board and the number of "bad" integers, respectively. The second line contains m distinct integers a1, a2, ..., am (-109 ≀ ai ≀ 109)Β β€” numbers that will never be written on the board.
1,700
Print the only integer, meaning the number of progression terms that will be written on the board if it is finite, or "inf" (without quotes) otherwise.
standard output
PASSED
b275fabbfc322a0a9545b6cc2d590647
train_001.jsonl
1302609600
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; /** * @author Alexey Safronov (safronov.aa@gmail.com) */ public class E { private InputReader in; private PrintWriter out; private void solve() { int n = in.readInt(); long[] xg = new long[10001]; long[] xl = new long[10001]; long[] yg = new long[10001]; long[] yl = new long[10001]; long xgc = 0; long xlc = 0; long ygc = 0; long ylc = 0; long xgc_sum = 0; long xlc_sum = 0; long ygc_sum = 0; long ylc_sum = 0; long xgc_square = 0; long xlc_square = 0; long ygc_square = 0; long ylc_square = 0; long result = 0; for(int i = 0; i < n; i++) { int x = in.readInt(); int y = in.readInt(); if(x >= 0) { ++xgc; xg[x]++; xgc_sum += x; xgc_square += x * x; } else if(x < 0) { ++xlc; x = -x; xl[x]++; xlc_sum += x; xlc_square += x * x; } if(y >= 0) { ++ygc; yg[y]++; ygc_sum += y; ygc_square += y * y; } else if(y < 0) { ++ylc; y = -y; yl[y]++; ylc_sum += y; ylc_square += y * y; } } for(int i = 0; i <= 10000; i++) { if(xg[i] > 0) { if(xgc > 0) { long c = xgc * (i * i) - (2 * i * xgc_sum) + xgc_square; result += xg[i] * c; } if(xlc > 0) { long c = xlc * (i * i) + (2 * i * xlc_sum) + xlc_square; result += xg[i] * c; } } if(xl[i] > 0) { if(xlc > 0) { long c = xlc * (i * i) - (2 * i * xlc_sum) + xlc_square; result += xl[i] * c; } if(xgc > 0) { long c = xgc * (i * i) + (2 * i * xgc_sum) + xgc_square; result += xl[i] * c; } } if(yg[i] > 0) { if(ygc > 0) { long c = ygc * (i * i) - (2 * i * ygc_sum) + ygc_square; result += yg[i] * c; } if(ylc > 0) { long c = ylc * (i * i) + (2 * i * ylc_sum) + ylc_square; result += yg[i] * c; } } if(yl[i] > 0) { if(ylc > 0) { long c = ylc * (i * i) - (2 * i * ylc_sum) + ylc_square; result += yl[i] * c; } if(ygc > 0) { long c = ygc * (i * i) + (2 * i * ygc_sum) + ygc_square; result += yl[i] * c; } } } result /= 2; out.println(result); } public static void main(String[] args) { new E().run(); } private E() { try { // System.setIn(new FileInputStream("input.txt")); // System.setOut(new PrintStream(new FileOutputStream("output.txt"))); } catch (Exception e) { throw new RuntimeException(e); } in = new InputReader(System.in); out = new PrintWriter(System.out); } private void run() { //int tests = in.readInt(); //for(int test = 1; test <= tests; ++test) solve(); exit(); } private void exit() { out.close(); System.exit(0); } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; 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 long readLong() { 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 String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); 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 String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) return readLine(); else return readLine0(); } public BigInteger readBigInteger() { try { return new BigInteger(readString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { 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, readInt()); 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, readInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } } }
Java
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
1 second
["32"]
null
Java 6
standard input
[ "implementation", "math" ]
9bd6fea892857d7c94ebce4d4cd46d30
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
1,700
The only line of output should contain the required sum of squares of distances between all pairs of points.
standard output
PASSED
c7172b85bbd88fae5385253804453c4d
train_001.jsonl
1302609600
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
256 megabytes
import java.util.*; import java.math.*; public class E { public static void main(String[] args) { new E(); } public E() { int N = nextInt(); BigInteger sumx = BigInteger.ZERO; BigInteger sumy = BigInteger.ZERO; vect[] vs = new vect[N]; for (int i=0; i<N; i++) { vs[i] = new vect(nextInt(), nextInt()); sumx = sumx.add(vs[i].x); sumy = sumy.add(vs[i].y); } //double cx = (sumx*1.0)/N; //double cy = (sumy*1.0)/N; BigInteger BIN = new BigInteger(N+""); BigInteger res = BigInteger.ZERO; for (int i=0; i<N; i++) { BigInteger NX = BIN.multiply(vs[i].x); BigInteger NY = BIN.multiply(vs[i].y); BigInteger xx = sumx.subtract(NX); BigInteger yy = sumy.subtract(NY); BigInteger vv = (xx.pow(2)).add(yy.pow(2)); res = res.add(vv); } res = res.divide(BIN); System.out.printf("%s%n", res.toString()); } class vect { BigInteger x; BigInteger y; public vect(int i, int j) { x = new BigInteger(i+""); y = new BigInteger(j+""); } } int nextInt(){ try{ int c=System.in.read(); if(c==-1) return c; while(c!='-'&&(c<'0'||'9'<c)){ c=System.in.read(); if(c==-1) return c; } if(c=='-') return -nextInt(); int res=0; do{ res*=10; res+=c-'0'; c=System.in.read(); }while('0'<=c&&c<='9'); return res; }catch(Exception e){ return -1; } } long nextLong(){ try{ int c=System.in.read(); if(c==-1) return -1; while(c!='-'&&(c<'0'||'9'<c)){ c=System.in.read(); if(c==-1) return -1; } if(c=='-') return -nextLong(); long res=0; do{ res*=10; res+=c-'0'; c=System.in.read(); }while('0'<=c&&c<='9'); return res; }catch(Exception e){ return -1; } } double nextDouble(){ return Double.parseDouble(next()); } String next(){ try{ StringBuilder res=new StringBuilder(""); int c=System.in.read(); while(Character.isWhitespace(c)) c=System.in.read(); do{ res.append((char)c); }while(!Character.isWhitespace(c=System.in.read())); return res.toString(); }catch(Exception e){ return null; } } String nextLine(){ try{ StringBuilder res=new StringBuilder(""); int c=System.in.read(); while(c=='\r'||c=='\n') c=System.in.read(); do{ res.append((char)c); c=System.in.read(); }while(c!='\r'&&c!='\n'); return res.toString(); }catch(Exception e){ return null; } } }
Java
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
1 second
["32"]
null
Java 6
standard input
[ "implementation", "math" ]
9bd6fea892857d7c94ebce4d4cd46d30
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
1,700
The only line of output should contain the required sum of squares of distances between all pairs of points.
standard output
PASSED
98a281e71273bf186a22560fa37c2f15
train_001.jsonl
1302609600
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
256 megabytes
import java.util.Scanner; public class E { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); long ans = 0; long X = 0; long Y = 0; for (int i = 0; i < n; i++) { long x = in.nextLong(); long y = in.nextLong(); ans += x * x * (n - 1); ans += y * y * (n - 1); ans -= 2 * x * X; ans -= 2 * y * Y; X += x; Y += y; } System.out.println(ans); } }
Java
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
1 second
["32"]
null
Java 6
standard input
[ "implementation", "math" ]
9bd6fea892857d7c94ebce4d4cd46d30
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
1,700
The only line of output should contain the required sum of squares of distances between all pairs of points.
standard output
PASSED
ce3e1a315aef486cc1ccb1eec8422707
train_001.jsonl
1302609600
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
256 megabytes
import java.util.Scanner; import java.math.BigInteger; public class Main { public static void main(String[] args) { new Main().start(); } private void start() { Scanner in = new Scanner(System.in); int n = in.nextInt(); int x[] = new int[n]; int y[] = new int[n]; long sx = 0; long sy = 0; BigInteger ans = BigInteger.ZERO; BigInteger nn = BigInteger.valueOf(n - 1); for (int i = 0; i < n; i++) { x[i] = in.nextInt(); y[i] = in.nextInt(); sx += x[i]; sy += y[i]; ans = ans.add(nn.multiply(BigInteger.valueOf(x[i] * x[i]))); ans = ans.add(nn.multiply(BigInteger.valueOf(y[i] * y[i]))); } BigInteger tmp = BigInteger.ZERO; for (int i = 0; i < n; i++) { tmp = tmp.add(BigInteger.valueOf(x[i] * 2).multiply(BigInteger.valueOf(sx - x[i]))); tmp = tmp.add(BigInteger.valueOf(y[i] * 2).multiply(BigInteger.valueOf(sy - y[i]))); } System.out.println(ans.subtract(tmp.divide(BigInteger.valueOf(2)))); } }
Java
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
1 second
["32"]
null
Java 6
standard input
[ "implementation", "math" ]
9bd6fea892857d7c94ebce4d4cd46d30
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
1,700
The only line of output should contain the required sum of squares of distances between all pairs of points.
standard output
PASSED
5dfeee134a72ffed32db9c54268f0abb
train_001.jsonl
1302609600
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
256 megabytes
import java.util.*; import java.lang.*; import java.math.*; public class anuj { public static void main(String args[]) { Scanner c=new Scanner(System.in); int n=c.nextInt(); int num[]=new int[20010]; Arrays.fill(num,0); int X[]=new int[n]; int Y[]=new int[n]; for(int i=0;i<n;i++) { X[i]=c.nextInt(); Y[i]=c.nextInt(); } long sum=0; long sum1=0; for(int i=0;i<n;i++) sum1+=X[i]*X[i]; sum1=sum1*n; for(int i=0;i<n;i++) sum+=X[i]; sum=sum1-sum*sum; sum1=0; for(int i=0;i<n;i++) sum1+=Y[i]*Y[i]; sum1=sum1*n; long sum2=0; for(int i=0;i<n;i++) sum2+=Y[i]; sum=sum+sum1-sum2*sum2; System.out.println(sum); } }
Java
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
1 second
["32"]
null
Java 6
standard input
[ "implementation", "math" ]
9bd6fea892857d7c94ebce4d4cd46d30
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
1,700
The only line of output should contain the required sum of squares of distances between all pairs of points.
standard output
PASSED
9e9ce612c98a59532600973bf3e8e852
train_001.jsonl
1302609600
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
256 megabytes
import java.util.*; import java.lang.*; import java.math.*; public class anuj { public static void main(String args[]) { Scanner c=new Scanner(System.in); int n=c.nextInt(); int num[]=new int[20010]; Arrays.fill(num,0); int X[]=new int[n]; int Y[]=new int[n]; for(int i=0;i<n;i++) { X[i]=c.nextInt(); Y[i]=c.nextInt(); } long sum=0; long sum1=0; for(int i=0;i<n;i++) sum1+=X[i]*X[i]; sum1=sum1*n; for(int i=0;i<n;i++) sum+=X[i]; sum=sum1-sum*sum; sum1=0; for(int i=0;i<n;i++) sum1+=Y[i]*Y[i]; sum1=sum1*n; long sum2=0; for(int i=0;i<n;i++) sum2+=Y[i]; sum=sum+sum1-sum2*sum2; System.out.println(sum); } }
Java
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
1 second
["32"]
null
Java 6
standard input
[ "implementation", "math" ]
9bd6fea892857d7c94ebce4d4cd46d30
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
1,700
The only line of output should contain the required sum of squares of distances between all pairs of points.
standard output
PASSED
fa5dd9cf0a26dbbf54bc44b84f3f2e5d
train_001.jsonl
1302609600
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.*; public class Points implements Runnable { private void solve() throws IOException { int n = nextInt(); long x = 0, x2 = 0, y = 0, y2 = 0; for(int i = 0 ; i < n; ++i) { long xx = nextLong(), yy = nextLong(); x += xx; y += yy; x2 += xx*xx; y2 += yy*yy; } writer.println(n*x2-x*x + n*y2-y*y); } public static void main(String[] args) { new Points().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
1 second
["32"]
null
Java 6
standard input
[ "implementation", "math" ]
9bd6fea892857d7c94ebce4d4cd46d30
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
1,700
The only line of output should contain the required sum of squares of distances between all pairs of points.
standard output
PASSED
cc26d433b9cbd71769b56052f50c62a6
train_001.jsonl
1302609600
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
256 megabytes
import java.io.*; import java.util.HashSet; public class Points { static class Parser { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Parser(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public char nextChar() throws Exception { byte c = read(); while (c <= ' ') c = read(); return (char) c; } public int nextLong() throws Exception { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; return ret; } private void fillBuffer() throws Exception { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws Exception { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } } public static void main(String[] args) throws Exception { Parser aa = new Parser(System.in); int N = aa.nextLong(); long res = 0L; long xSum = 0L; long ySum = 0L; long[] x = new long[N]; long[] y = new long[N]; long xx,yy; for (int i = 0; i < N; i++) { xx = aa.nextLong(); yy = aa.nextLong(); x[i]=xx; y[i]=yy; xSum += x[i]; ySum += y[i]; res+=((N-1)*(xx*xx)); res+=((N-1)*(yy*yy)); } for (int i = 0; i < N-1; i++) { res -= (2*x[i]*(xSum-x[i])); res -= (2*y[i]*(ySum-y[i])); xSum-=x[i]; ySum-=y[i]; } System.out.println(res); } }
Java
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
1 second
["32"]
null
Java 6
standard input
[ "implementation", "math" ]
9bd6fea892857d7c94ebce4d4cd46d30
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
1,700
The only line of output should contain the required sum of squares of distances between all pairs of points.
standard output
PASSED
4592f02cb6ef30d6de59aa8e3950d2e1
train_001.jsonl
1302609600
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
256 megabytes
//package ukr; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class E { static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static PrintWriter out = new PrintWriter(System.out); static String nextToken() throws IOException{ while (st==null || !st.hasMoreTokens()){ String s = bf.readLine(); if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } static int nextInt() throws IOException{ return Integer.parseInt(nextToken()); } static long nextLong() throws IOException{ return Long.parseLong(nextToken()); } static String nextStr() throws IOException{ return nextToken(); } static double nextDouble() throws IOException{ return Double.parseDouble(nextToken()); } public static void main(String[] args) throws IOException{ int n = nextInt(), x[] = new int[n], y[] = new int[n]; for (int i=0; i<n; i++){ x[i] = nextInt(); y[i] = nextInt(); } Arrays.sort(x); Arrays.sort(y); long res1 = 0; long sumSq = 0, sum = 0; for (int i=1; i<n; i++){ long d = x[i]-x[i-1]; sumSq = d*d*i + 2*d*sum + sumSq; res1 += sumSq; sum += d*i; } long res2 = 0; sum = 0; sumSq = 0; for (int i=1; i<n; i++){ long d = y[i]-y[i-1]; sumSq = d*d*i + 2*d*sum + sumSq; res2 += sumSq; sum += d*i; } out.println(res1+res2); out.flush(); } }
Java
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
1 second
["32"]
null
Java 6
standard input
[ "implementation", "math" ]
9bd6fea892857d7c94ebce4d4cd46d30
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
1,700
The only line of output should contain the required sum of squares of distances between all pairs of points.
standard output
PASSED
2342aa3616d679419713fa6233c955d7
train_001.jsonl
1302609600
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
256 megabytes
import java.awt.Point; import java.io.*; import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class ProblemE_UA { final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE")!=null; BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException{ if (ONLINE_JUDGE){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } } String readString() throws IOException{ while(!tok.hasMoreTokens()){ tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException{ return Integer.parseInt(readString()); } long readLong() throws IOException{ return Long.parseLong(readString()); } double readDouble() throws IOException{ return Double.parseDouble(readString()); } public static void main(String[] args){ new ProblemE_UA().run(); } public void run(){ try{ long t1 = System.currentTimeMillis(); init(); solve(); out.close(); long t2 = System.currentTimeMillis(); System.err.println("Time = "+(t2-t1)); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } void solve() throws IOException{ int n = readInt(); long s = 0; long sx = 0; long sy = 0; long[] x = new long[n]; long[] y = new long[n]; for (int i = 0; i < n; i++){ x[i] = readInt(); y[i] = readInt(); sx += x[i]; sy += y[i]; } for (int i = 0; i < n; i++){ s -= x[i] * (sx - x[i]); s -= y[i] * (sy - y[i]); s += (n - 1) * x[i] * x[i]; s += (n - 1) * y[i] * y[i]; } out.print(s); } static int[][] step8 = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, -1}, {-1, 1}, {1, 1}}; static int[][] stepKnight = {{-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}, {2, -1}, {2, 1}}; static long gcd(long a, long b){ if (a == 0) return b; return gcd(b % a, a); } static long lcm(long a, long b){ return a / gcd(a, b)*b; } static long[] gcdPlus(long a, long b){ long[] d = new long[3]; if (a == 0){ d[0] = b; d[1] = 0; d[2] = 1; }else{ d = gcdPlus(b % a, a); long r = d[1]; d[1] = d[2] - b/a*d[1]; d[2] = r; } return d; } static long binpow(long a, int n){ if (n == 0) return 1; if ((n & 1) == 0){ long b = binpow(a, n/2); return b*b; }else return binpow(a, n - 1)*a; } static long binpowmod(long a, int n, long m){ if (m == 1) return 0; if (n == 0) return 1; if ((n & 1) == 0){ long b = binpowmod(a, n/2, m); return (b*b) % m; }else return binpowmod(a, n - 1, m)*a % m; } static long phi(long n){ int[] p = Sieve((int)ceil(sqrt(n)) + 2); long phi = 1; for (int i = 0; i < p.length; i++){ long x = 1; while (n % p[i] == 0){ n /= p[i]; x *= p[i]; } phi *= x - x/p[i]; } if (n != 1) phi *= n - 1; return phi; } static long f(long n, int x, int k){ //οΏ½οΏ½οΏ½-οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½ (οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ 0), οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½ οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½ 0 οΏ½οΏ½ k-1 if (n == 0) return 1; long b = binpow(10, x - 1); long c = n / b; return (c < k? c: k)*binpow(k, x - 1) + (c < k? 1: 0)*f(n % b, x - 1, k); } static long fib(int n){ if (n == 0) return 0; if ((n & 1) == 0){ long f1 = fib(n/2 - 1); long f2 = fib(n/2 + 1); return f2*f2 - f1*f1; }else{ long f1 = fib(n/2); long f2 = fib(n/2 + 1); return f1*f1 + f2*f2; } } static BigInteger BigFib(int n){ if (n == 0) return BigInteger.ZERO; if ((n & 1) == 0){ BigInteger f1 = BigFib(n/2 - 1); f1 = f1.multiply(f1); BigInteger f2 = BigFib(n/2 + 1); f2 = f2.multiply(f2); return f2.subtract(f1); }else{ BigInteger f1 = BigFib(n/2); f1 = f1.multiply(f1); BigInteger f2 = BigFib(n/2 + 1); f2 = f2.multiply(f2); return f2.add(f1); } } static public class PointD{ double x, y; public PointD(double x, double y){ this.x = x; this.y = y; } } static double d(Point p1, Point p2){ return sqrt(d2(p1, p2)); } static public double d(PointD p1, PointD p2){ return sqrt(d2(p1, p2)); } static double d2(Point p1, Point p2){ return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y); } static public double d2(PointD p1, PointD p2){ return (p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y); } static boolean IsProbablyPrime(long n){ if (n == 1) return false; if ((n & 1) == 0) return false; for (int j = 3; j < sqrt(n) + 1; j += 2){ if (n % j == 0) return false; } return true; } static int[] Sieve(int n){ boolean[] b = new boolean[n+1]; Arrays.fill(b, true); b[0] = false; b[1] = false; long nLong = n; int j=0; for (int i = 1; i <= n; i++) { if (b[i]){ j++; if (((long)i)*i <= nLong) { for (int k = i*i; k <= n; k += i) { b[k] = false; } } } } int[] p = new int[j]; Arrays.fill(p, 0); j=0; for (int i = 2; i <= n; i++) { if (b[i]){ p[j]=i; j++; } } return p; } static int[][] Palindromes(String s){ char[] c = s.toCharArray(); int n = c.length; int[][] d = new int[2][n]; int l = 0, r = -1; for (int i = 0; i < n; i++){ int j = (i > r? 0: min(d[0][l+r-i+1], r-i+1)) + 1; for (; i - j >= 0 && i + j - 1< n && c[i-j] == c[i+j-1]; j++); d[0][i] = --j; if (i + d[0][i] - 1 > r){ r = i + d[0][i] - 1; l = i - d[0][i]; } } l = 0; r = -1; for (int i = 0; i < n; i++){ int j = (i > r? 0: min(d[1][l+r-i], r-i)) + 1; for (; i - j >= 0 && i + j < n && c[i-j] == c[i+j]; j++); d[1][i] = --j; if (i + d[1][i] > r){ r = i + d[1][i]; l = i - d[1][i]; } } return d; } static public class Permutation { int[] a; int n; public Permutation(int n){ this.n=n; a=new int[n]; for (int i=0; i<n; i++){ a[i]=i; } } public boolean nextPermutation(){ //οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ οΏ½ do{}while(nextPermutation(a)); int i=n-1; for (i=n-2; i>=0; i--){ if (a[i]<a[i+1]){ break; } } if (i==-1){ return false; } int jMin=i+1; for (int j=n-1; j>i; j--){ if (a[i]<a[j]&&a[j]<a[jMin]){ jMin=j; } } swap(i, jMin); for (int j=1; j<=(n-i)/2; j++){ swap(i+j, n-j); } return true; } public int get(int i){ return a[i]; } void swap(int i, int j){ int r=a[i]; a[i]=a[j]; a[j]=r; } } static public class Fraction implements Comparable<Fraction>, Cloneable{ public final Fraction FRACTION_ZERO = new Fraction(); public final Fraction FRACTION_ONE = new Fraction(1); public long numerator = 0; public long denominator = 1; public Fraction(){ numerator = 0; denominator = 1; } public Fraction(long numerator){ this.numerator = numerator; denominator = 1; } public Fraction(long numerator, long denominator){ this.numerator = numerator; this.denominator = denominator; Cancellation(); } public Fraction(double numerator, double denominator, int accuracy){ this.numerator = (long)(numerator*pow(10,accuracy)); this.denominator = (long)(denominator*pow(10,accuracy)); Cancellation(); } public Fraction(String s){ if (s.charAt(0) == '-'){ denominator = -1; s = s.substring(1); } if (s.indexOf("/") != -1){ denominator *= Integer.parseInt(s.substring(s.indexOf("/") + 1)); } if (s.indexOf(" ") != -1){ numerator = Integer.parseInt(s.substring(0, s.indexOf(" "))) * abs(denominator) + Integer.parseInt(s.substring(s.indexOf(" ") + 1, s.indexOf("/"))); }else{ if (s.indexOf("/") != -1){ numerator = Integer.parseInt(s.substring(0, s.indexOf("/"))); }else{ numerator = Integer.parseInt(s)*abs(denominator); } } this.Cancellation(); } void Cancellation(){ long g = gcd(abs(numerator), abs(denominator)); numerator /= g; denominator /= g; if (denominator < 0){ numerator *= -1; denominator *= -1; } } public String toString(){ String s = ""; if (numerator == 0){ return "0"; } if (numerator < 0){ s += "-"; } if (abs(numerator) >= denominator){ s += Long.toString(abs(numerator) / denominator) + " "; } if (abs(numerator) % denominator != 0){ s += Long.toString(abs(numerator) % denominator); }else{ s = s.substring(0, s.length()-1); } if (denominator != 1){ s += "/" + Long.toString(denominator); } return s; } public Fraction add(Fraction f){ Fraction fResult = new Fraction(); fResult.denominator = lcm(denominator, f.denominator); fResult.numerator = numerator * fResult.denominator / denominator + f.numerator * fResult.denominator / f.denominator; fResult.Cancellation(); return fResult; } public Fraction subtract(Fraction f){ Fraction fResult = new Fraction(); fResult.denominator = lcm(denominator, f.denominator); fResult.numerator = numerator * fResult.denominator / denominator - f.numerator * fResult.denominator / f.denominator; fResult.Cancellation(); return fResult; } public Fraction multiply(Fraction f){ Fraction fResult = new Fraction(); fResult.numerator = numerator * f.numerator; fResult.denominator = denominator * f.denominator; fResult.Cancellation(); return fResult; } public Fraction divide(Fraction f){ Fraction fResult = new Fraction(); fResult.numerator = numerator * f.denominator; fResult.denominator = denominator * f.numerator; fResult.Cancellation(); return fResult; } @Override public int compareTo(Fraction f){ long g = gcd(denominator, f.denominator); long res = numerator * (f.denominator / g) - f.numerator * (denominator / g); if (res < 0){ return -1; } if (res > 0){ return 1; } return 0; } public Fraction clone(){ Fraction fResult = new Fraction(numerator, denominator); return fResult; } public Fraction floor(){ Fraction fResult = this.clone(); fResult.numerator = (fResult.numerator / fResult.denominator) * fResult.denominator; return fResult; } public Fraction ceil(){ Fraction fResult = this.clone(); fResult.numerator = (fResult.numerator/fResult.denominator + 1) * fResult.denominator; return fResult; } public Fraction binpow(int n){ if (n==0) return FRACTION_ONE; if ((n&1)==0){ Fraction f=this.binpow(n/2); return f.multiply(f); }else return binpow(n-1).multiply(this); } } static public class FenwickTree_1{ //One-dimensional array int n; long[] t; public FenwickTree_1(int n){ this.n = n; t = new long[n]; } public long sum(int xl, int xr){ return sum(xr) - sum(xl); } public long sum(int x){ long result = 0; for (int i = x; i >= 0; i = (i & (i + 1)) - 1){ result += t[i]; } return result; } public void update(int x, long delta){ for (int i = x; i < n; i = (i | (i + 1))){ t[i] += delta; } } } static public class FenwickTree_2{ //Two-dimensional array int n, m; long[][] t; public FenwickTree_2(int n, int m){ this.n = n; this.m = m; t = new long[n][m]; } public long sum(int xl, int yl, int xr, int yr){ return sum(xr, yr) - sum(xl - 1, yr) - sum(xr, yl - 1) + sum(xl - 1, yl - 1); } public long sum(int x, int y){ long result = 0; for (int i = x; i >= 0; i = (i & (i + 1)) - 1){ for (int j = y; j >= 0; j = (j & (j + 1)) - 1){ result+=t[i][j]; } } return result; } public void update(int x, int y, long delta){ for (int i = x; i < n; i = (i | (i + 1))){ for (int j = y; j < m; j = (j | (j + 1))){ t[i][j] += delta; } } } } static public class FenwickTree_3{ //Three-dimensional array int n, m, l; long[][][] t; public FenwickTree_3(int n, int m, int l){ this.n = n; this.m = m; this.l = l; t = new long[n][m][l]; } public long sum(int xl, int yl, int zl, int xr, int yr, int zr){ return sum(xr, yr, zr) - sum(xl - 1, yr, zr) + sum(xl - 1, yr, zl - 1) - sum(xr, yr, zl - 1) - sum(xr, yl - 1, zr) + sum(xl - 1, yl - 1, zr) - sum(xl - 1, yl - 1, zl - 1) + sum(xr, yl - 1, zl - 1); } public long sum(int x, int y, int z){ long result = 0; for (int i = x; i >= 0; i = (i & (i + 1)) - 1){ for (int j = y; j >= 0; j = (j & (j + 1)) - 1){ for (int k = z; k >= 0; k = (k & (k + 1)) - 1){ result += t[i][j][k]; } } } return result; } public void update(int x, int y, int z, long delta){ for (int i = x; i < n; i = (i | (i + 1))){ for (int j = y; j < n; j = (j | (j + 1))){ for (int k = z; k < n; k = (k | (k + 1))){ t[i][j][k] += delta; } } } } } }
Java
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
1 second
["32"]
null
Java 6
standard input
[ "implementation", "math" ]
9bd6fea892857d7c94ebce4d4cd46d30
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
1,700
The only line of output should contain the required sum of squares of distances between all pairs of points.
standard output
PASSED
c665fa3af47b0311b21e39e561fc4988
train_001.jsonl
1302609600
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
256 megabytes
import java.io.*; /** * All-Ukrainian School Olympiad in Informatics, D * @author Roman Kosenko <madkite@gmail.com> */ public class Points { public static void main(String[] args) throws IOException { FastScanner scanner = new FastScanner(!Boolean.parseBoolean(System.getProperty("ONLINE_JUDGE")) ? new FileInputStream("input.txt") : System.in); int n = scanner.nextInt(); long sx = 0, sy = 0, s2 = 0; for(int i = n; i > 0; i--) { int x = scanner.nextInt(), y = scanner.nextInt(); sx += x; s2 += x * x; sy += y; s2 += y * y; } System.out.println(n * s2 - sx * sx - sy * sy); } static class FastScanner { private final InputStream is; private byte[] data = new byte[0x2000]; private int next, size; public FastScanner(InputStream is) { this.is = is; } private boolean read() throws IOException { size = is.read(data); if(size == 0) { int i = is.read(); if(i < 0) return false; data[0] = (byte)i; size = 1; } else if(size < 0) return false; next = 0; return true; } public int nextInt() throws IOException { int r; boolean negative = false; do { if(next >= size && !read()) throw new EOFException(); negative |= (r = data[next++]) == '-'; } while(r < '0' || r > '9'); r -= '0'; for(int d; (next < size || read()) && '0' <= (d = data[next++]) && d <= '9';) r = r * 10 + d - '0'; return negative ? -r : r; } } }
Java
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
1 second
["32"]
null
Java 6
standard input
[ "implementation", "math" ]
9bd6fea892857d7c94ebce4d4cd46d30
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
1,700
The only line of output should contain the required sum of squares of distances between all pairs of points.
standard output
PASSED
5d6335d08a8cab3b1ba1ec1a644fddb9
train_001.jsonl
1302609600
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
256 megabytes
import java.io.*; /** * All-Ukrainian School Olympiad in Informatics, D * @author Roman Kosenko <madkite@gmail.com> */ public class Points { public static void main(String[] args) throws IOException { if(!Boolean.parseBoolean(System.getProperty("ONLINE_JUDGE"))) System.setIn(new FileInputStream(new File("input.txt"))); FastScanner scanner = new FastScanner(System.in); long sx = 0, sx2 = 0, sy = 0, sy2 = 0, r = 0; for(int n = scanner.nextInt(), i = 0; i < n; i++) { int x = scanner.nextInt(), y = scanner.nextInt(); long x2 = x * x, y2 = y * y; r += i * x2 + sx2 - 2 * x * sx; sx += x; sx2 += x2; r += i * y2 + sy2 - 2 * y * sy; sy += y; sy2 += y2; } System.out.println(r); } static class FastScanner { private final InputStream is; private byte[] data = new byte[0x2000]; private int next, size; public FastScanner(InputStream is) { this.is = is; } private boolean read() throws IOException { size = is.read(data); if(size == 0) { int i = is.read(); if(i < 0) return false; data[0] = (byte)i; size = 1; } else if(size < 0) return false; next = 0; return true; } public int nextInt() throws IOException { int r; boolean negative = false; do { if(next >= size && !read()) throw new EOFException(); negative |= (r = data[next++]) == '-'; } while(r < '0' || r > '9'); r -= '0'; for(int d; (next < size || read()) && '0' <= (d = data[next++]) && d <= '9';) r = r * 10 + d - '0'; return negative ? -r : r; } } }
Java
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
1 second
["32"]
null
Java 6
standard input
[ "implementation", "math" ]
9bd6fea892857d7c94ebce4d4cd46d30
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
1,700
The only line of output should contain the required sum of squares of distances between all pairs of points.
standard output
PASSED
522cf047acefd9278fd3b71b18b136d2
train_001.jsonl
1302609600
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
256 megabytes
import java.io.*; /** * All-Ukrainian School Olympiad in Informatics, D * @author Roman Kosenko <madkite@gmail.com> */ public class Points { public static void main(String[] args) throws IOException { FastScanner scanner = new FastScanner(!Boolean.parseBoolean(System.getProperty("ONLINE_JUDGE")) ? new FileInputStream("input.txt") : System.in); int n = scanner.nextInt(); long sx = 0, sx2 = 0, sy = 0, sy2 = 0; for(int i = 0; i < n; i++) { int x = scanner.nextInt(), y = scanner.nextInt(); sx += x; sx2 += x * x; sy += y; sy2 += y * y; } System.out.println(n * sx2 - sx * sx + n * sy2 - sy * sy); } static class FastScanner { private final InputStream is; private byte[] data = new byte[0x2000]; private int next, size; public FastScanner(InputStream is) { this.is = is; } private boolean read() throws IOException { size = is.read(data); if(size == 0) { int i = is.read(); if(i < 0) return false; data[0] = (byte)i; size = 1; } else if(size < 0) return false; next = 0; return true; } public int nextInt() throws IOException { int r; boolean negative = false; do { if(next >= size && !read()) throw new EOFException(); negative |= (r = data[next++]) == '-'; } while(r < '0' || r > '9'); r -= '0'; for(int d; (next < size || read()) && '0' <= (d = data[next++]) && d <= '9';) r = r * 10 + d - '0'; return negative ? -r : r; } } }
Java
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
1 second
["32"]
null
Java 6
standard input
[ "implementation", "math" ]
9bd6fea892857d7c94ebce4d4cd46d30
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
1,700
The only line of output should contain the required sum of squares of distances between all pairs of points.
standard output
PASSED
19240bb5fde983d2c336db7911548c1f
train_001.jsonl
1302609600
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
256 megabytes
import java.io.*; import java.util.*; /** * All-Ukrainian School Olympiad in Informatics, E * @author Roman Kosenko <madkite@gmail.com> */ public class Points { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); long sx = 0, sy = 0, s2 = 0; for(int i = n; i > 0; i--) { StringTokenizer st = new StringTokenizer(br.readLine()); int x = Integer.parseInt(st.nextToken()), y = Integer.parseInt(st.nextToken()); sx += x; s2 += x * x; sy += y; s2 += y * y; } System.out.println(n * s2 - sx * sx - sy * sy); } }
Java
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
1 second
["32"]
null
Java 6
standard input
[ "implementation", "math" ]
9bd6fea892857d7c94ebce4d4cd46d30
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
1,700
The only line of output should contain the required sum of squares of distances between all pairs of points.
standard output
PASSED
44f027d6a4e9937e918f4d2379abc2e4
train_001.jsonl
1302609600
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
256 megabytes
import java.io.*; import java.util.*; /** * All-Ukrainian School Olympiad in Informatics, E * @author Roman Kosenko <madkite@gmail.com> */ public class Points { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); long sx = 0, sy = 0, s2 = 0; for(int i = n; i > 0; i--) { StringTokenizer st = new StringTokenizer(br.readLine()); int x = Integer.parseInt(st.nextToken()), y = Integer.parseInt(st.nextToken()); sx += x; s2 += x * x; sy += y; s2 += y * y; } System.out.println(n * s2 - sx * sx - sy * sy); } }
Java
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
1 second
["32"]
null
Java 6
standard input
[ "implementation", "math" ]
9bd6fea892857d7c94ebce4d4cd46d30
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
1,700
The only line of output should contain the required sum of squares of distances between all pairs of points.
standard output
PASSED
393d93747545826f8abf22b3020deed0
train_001.jsonl
1302609600
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
256 megabytes
import java.io.*; /** * All-Ukrainian School Olympiad in Informatics, E * @author Roman Kosenko <madkite@gmail.com> */ public class Points { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); long sx = 0, sy = 0, s2 = 0; for(int i = n; i > 0; i--) { String s = br.readLine(); int space = s.indexOf(' '); int x = Integer.parseInt(s.substring(0, space)), y = Integer.parseInt(s.substring(space + 1)); sx += x; s2 += x * x; sy += y; s2 += y * y; } System.out.println(n * s2 - sx * sx - sy * sy); } }
Java
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
1 second
["32"]
null
Java 6
standard input
[ "implementation", "math" ]
9bd6fea892857d7c94ebce4d4cd46d30
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
1,700
The only line of output should contain the required sum of squares of distances between all pairs of points.
standard output
PASSED
129bfde797a5a54093d3305739872216
train_001.jsonl
1302609600
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
256 megabytes
import java.util.*; /** * Created by IntelliJ IDEA. * User: piyushd * Date: 3/29/11 * Time: 7:56 PM * To change this template use File | Settings | File Templates. */ public class TaskE { void run(){ int N = nextInt(); long[] x = new long[N]; long[] y = new long[N]; for(int i = 0; i < N; i++){ x[i] = nextInt(); y[i] = nextInt(); } long sumx = 0, sumy = 0; long sumx2 = 0, sumy2 = 0; for(int i = 0; i < N; i++){ sumx += x[i]; sumy += y[i]; sumx2 += x[i] * x[i]; sumy2 += y[i] * y[i]; } System.out.println(N * sumx2 - sumx * sumx + N * sumy2 - sumy * sumy); } int nextInt(){ try{ int c = System.in.read(); if(c == -1) return c; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return c; } if(c == '-') return -nextInt(); int res = 0; do{ res *= 10; res += c - '0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } long nextLong(){ try{ int c = System.in.read(); if(c == -1) return -1; while(c != '-' && (c < '0' || '9' < c)){ c = System.in.read(); if(c == -1) return -1; } if(c == '-') return -nextLong(); long res = 0; do{ res *= 10; res += c-'0'; c = System.in.read(); }while('0' <= c && c <= '9'); return res; }catch(Exception e){ return -1; } } double nextDouble(){ return Double.parseDouble(next()); } String next(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(Character.isWhitespace(c)) c = System.in.read(); do{ res.append((char)c); }while(!Character.isWhitespace(c=System.in.read())); return res.toString(); }catch(Exception e){ return null; } } String nextLine(){ try{ StringBuilder res = new StringBuilder(""); int c = System.in.read(); while(c == '\r' || c == '\n') c = System.in.read(); do{ res.append((char)c); c = System.in.read(); }while(c != '\r' && c != '\n'); return res.toString(); }catch(Exception e){ return null; } } public static void main(String[] args){ new TaskE().run(); } }
Java
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
1 second
["32"]
null
Java 6
standard input
[ "implementation", "math" ]
9bd6fea892857d7c94ebce4d4cd46d30
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
1,700
The only line of output should contain the required sum of squares of distances between all pairs of points.
standard output
PASSED
68779ac18a4fb5d415161b8bc87ccace
train_001.jsonl
1302609600
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.fill; import static java.util.Arrays.binarySearch; import static java.util.Arrays.sort; public class Main { public static void main(String[] args) throws IOException { new Thread(null, new Runnable() { public void run() { try { try { if (new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) {} new Main().run(); } catch (IOException e) { e.printStackTrace(); } } }, "1", 1L << 24).start(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); int N; long[] xs; long[] ys; long Qx = 0L; long Qy = 0L; long Sx = 0L; long Sy = 0L; void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); N = nextInt(); xs = new long [N]; ys = new long [N]; for (int i = 0; i < N; i++) { xs[i] = nextLong(); ys[i] = nextLong(); } for (int i = 0; i < N; i++) { Sx += xs[i]; Sy += ys[i]; Qx += xs[i] * xs[i]; Qy += ys[i] * ys[i]; } long ans = N * (Qx + Qy) - Sx * Sx - Sy * Sy; out.println(ans); out.close(); } /*************************************************************** * Input **************************************************************/ String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } }
Java
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
1 second
["32"]
null
Java 6
standard input
[ "implementation", "math" ]
9bd6fea892857d7c94ebce4d4cd46d30
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
1,700
The only line of output should contain the required sum of squares of distances between all pairs of points.
standard output
PASSED
9de8f47060f04ca954cec6eacd01b60b
train_001.jsonl
1302609600
You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; public class Main { private static StreamTokenizer in; private static PrintWriter out; private static BufferedReader inB; private static int nextInt() throws Exception{ in.nextToken(); return (int)in.nval; } private static String nextString() throws Exception{ in.nextToken(); return in.sval; } static{ inB = new BufferedReader(new InputStreamReader(System.in)); in = new StreamTokenizer(inB); out = new PrintWriter(System.out); } public static void main(String[] args)throws Exception { int n = nextInt(); int[][] mas = new int[n][2]; long sumx = 0, sumy = 0; long sum2x = 0, sum2y = 0; for(int i = 0; i<n; i++) { mas[i][0] = nextInt(); mas[i][1] = nextInt(); sumx += mas[i][0]; sumy += mas[i][1]; sum2x += (long)mas[i][0]*mas[i][0]; sum2y += (long)mas[i][1]*mas[i][1]; } long sum = 0; sum += (n*sum2x - sumx*sumx); sum += (n*sum2y - sumy*sumy); println(sum); } ///////////////////////////////////////////////////////////////// private static void println(Object o) throws Exception { System.out.println(o); } private static void exit(Object o) throws Exception { println(o); System.exit(0); } private static void exit() { System.exit(0); } ////////////////////////////////////////////////////////////////// }
Java
["4\n1 1\n-1 -1\n1 -1\n-1 1"]
1 second
["32"]
null
Java 6
standard input
[ "implementation", "math" ]
9bd6fea892857d7c94ebce4d4cd46d30
The first line of input contains one integer number N (1 ≀ N ≀ 100 000) β€” the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≀ X, Y ≀ 10 000) β€” the coordinates of points. Two or more points may coincide.
1,700
The only line of output should contain the required sum of squares of distances between all pairs of points.
standard output
PASSED
ca85856313e085274a276ce850cc3711
train_001.jsonl
1481992500
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world.There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
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.Arrays; import java.util.Random; import java.util.StringTokenizer; import java.util.List; import java.util.Collections; public class A { private static FastScanner fs=new FastScanner(); private static List<Integer> graph[]; private static boolean [] isVisited; public static void main(String[] args) { int n = fs.nextInt(),m = fs.nextInt(),k = fs.nextInt(); int arr[] = fs.readArray(k); graph = new ArrayList[n]; for(int i=0;i<n;i++) graph[i] = new ArrayList<>(); for(int i=0;i<m;i++) { int From = fs.nextInt()-1; int To = fs.nextInt()-1; graph[From].add(To); graph[To].add(From); } isVisited = new boolean[n]; Arrays.fill(isVisited,false); List<Integer> nodes = new ArrayList<>(); for(int i=0;i<k;i++) { nodes.add(dfs(arr[i]-1)); } Collections.sort(nodes); for(int i=0;i<n;i++) { if(!isVisited[i]) { int a = nodes.get(nodes.size()-1); a+=1; int junk =nodes.remove(nodes.size()-1); nodes.add(a); } } long ans =0; for(int i: nodes) ans+=(i*(i-1)/2); ans-=m; System.out.println(ans); } private static int size =0; private static int dfs(int start) { isVisited[start] = true; int res =1; for(int i :graph[start]) { if(!isVisited[i]) { res +=dfs(i); } } return res; } private static int count =0; static final Random random=new Random(); static void ruffleSort(long[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); long temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } int [] sort(int [] arr) { List<Integer> list = new ArrayList<>(); for(int i : arr) list.add(i); Collections.sort(list); int res[] = new int[arr.length]; for(int i=0;i<arr.length;i++) res[i] = list.get(i); return res; } } }
Java
["4 1 2\n1 3\n1 2", "3 3 1\n2\n1 2\n1 3\n2 3"]
2 seconds
["2", "0"]
NoteFor the first sample test, the graph looks like this: Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.For the second sample test, the graph looks like this: We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
Java 11
standard input
[ "dfs and similar", "graphs" ]
6cf43241b14e4d41ad5b36572f3b3663
The first line of input will contain three integers n, m and k (1 ≀ n ≀ 1 000, 0 ≀ m ≀ 100 000, 1 ≀ k ≀ n)Β β€” the number of vertices and edges in the graph, and the number of vertices that are homes of the government. The next line of input will contain k integers c1, c2, ..., ck (1 ≀ ci ≀ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world. The following m lines of input will contain two integers ui and vi (1 ≀ ui, vi ≀ n). This denotes an undirected edge between nodes ui and vi. It is guaranteed that the graph described by the input is stable.
1,500
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
standard output
PASSED
81958f893e99a3de83fa3a865686c892
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class CO_519D { static int imax=Integer.MAX_VALUE,imin=Integer.MIN_VALUE; static long lmax=Long.MAX_VALUE,lmin=Long.MIN_VALUE; public static void main (String[] args) throws java.lang.Exception { // Scanner scan=new Scanner(System.in); InputReader in =new InputReader(System.in); PrintWriter out=new PrintWriter(System.out); // int t=in.nextInt(); int t=1; while(t-->0){ int i=0,j=0; // int n=in.nextInt(); int arr[]=new int[26]; LinkedList<Long> list[]=new LinkedList[26]; TreeMap<Long,Long> map[]=new TreeMap[26]; for(i=0;i<26;i++){ arr[i]=in.nextInt(); list[i]=new LinkedList<>(); map[i]=new TreeMap<>(); } String ss=in.next(); long sum=0; long ans=0; for(i=0;i<ss.length();i++){ char c=ss.charAt(i); sum+=arr[c-'a']; list[c-'a'].add(sum); if(map[c-'a'].get(sum)==null){ // System.out.println(c+" first "+sum); map[c-'a'].put(sum,1L); }else{ // System.out.println(c+" "+sum); map[c-'a'].put(sum,map[c-'a'].get(sum)+1); } if(map[c-'a'].get(sum-arr[c-'a'])==null|| (arr[c-'a']==0&&map[c-'a'].get(sum)==1)){ continue; }else{ ans+=map[c-'a'].get(sum-arr[c-'a']); if(arr[c-'a']==0)ans--; // System.out.println(c+" "+sum+" "+ans); } } out.println(ans); } out.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; 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 & 15; 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 & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); //while (c != '\n' && c != '\r' && c != '\t' && c != -1) //c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (c != '\n' && c != '\r' && c != '\t' && c != -1); return res.toString(); } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
b7893fb1543f7b6e47114b11e3782a92
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Pradyumn Agrawal coderbond007 PLEASE!! PLEASE!! HACK MY SOLUTION!! */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(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, FastReader in, PrintWriter out) { int[] a = in.nextIntArray(26); char[] s = in.nextString().toCharArray(); int n = s.length; long[] cum = new long[n + 1]; for (int i = 0; i < n; i++) { cum[i + 1] = cum[i] + a[s[i] - 'a']; } long num = 0; for (int i = 0; i < 26; i++) { TaskD.LongHashMap lhm = new TaskD.LongHashMap(); for (int j = 0; j < n; j++) { if (s[j] == 'a' + i) { { Object val = lhm.get(cum[j]); if (val != null) { num += (Integer) val; } } { Object val = lhm.get(cum[j + 1]); if (val != null) { int x = (Integer) val; lhm.put(cum[j + 1], x + 1); } else { lhm.put(cum[j + 1], 1); } } } } } out.println(num); } public static class LongHashMap { public long[] keys; public Object[] allocated; private int scale = 1 << 2; private int rscale = 1 << 1; private int mask = scale - 1; public int size = 0; public int itr = -1; private static int NG = Integer.MIN_VALUE; public LongHashMap() { allocated = new Object[scale]; keys = new long[scale]; } public Object get(long x) { int pos = h(x) & mask; while (allocated[pos] != null) { if (x == keys[pos]) return allocated[pos]; pos = pos + 1 & mask; } return null; } public Object put(long x, Object v) { int pos = h(x) & mask; while (allocated[pos] != null) { if (x == keys[pos]) { Object oldval = allocated[pos]; allocated[pos] = v; return oldval; } pos = pos + 1 & mask; } if (size == rscale) { resizeAndPut(x, v); } else { keys[pos] = x; allocated[pos] = v; } size++; return null; } private void resizeAndPut(long x, Object v) { int nscale = scale << 1; int nrscale = rscale << 1; int nmask = nscale - 1; Object[] nallocated = new Object[nscale]; long[] nkeys = new long[nscale]; itrreset(); while (true) { long y = next(); if (end()) break; int pos = h(y) & nmask; while (nallocated[pos] != null) pos = pos + 1 & nmask; nkeys[pos] = y; nallocated[pos] = allocated[itr]; } { int pos = h(x) & nmask; while (nallocated[pos] != null) pos = pos + 1 & nmask; nkeys[pos] = x; nallocated[pos] = v; } allocated = nallocated; keys = nkeys; scale = nscale; rscale = nrscale; mask = nmask; } public void itrreset() { itr = -1; } public boolean end() { return itr == -1; } public long next() { while (++itr < scale && allocated[itr] == null) ; if (itr == scale) { itr = -1; return NG; } return keys[itr]; } private int h(long x) { x ^= x >>> 33; x *= 0xff51afd7ed558ccdL; x ^= x >>> 33; x *= 0xc4ceb9fe1a85ec53L; x ^= x >>> 33; return (int) x; } public String toString() { itrreset(); long[] vals = new long[size]; int p = 0; while (true) { long y = next(); if (end()) break; vals[p++] = y; } return Arrays.toString(vals); } } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } public String nextString() { int c = pread(); while (isSpaceChar(c)) c = pread(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = pread(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
6f49ed099e639d821617e9a1341873b1
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Pradyumn Agrawal coderbond007 PLEASE!! PLEASE!! HACK MY SOLUTION!! */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(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, FastReader in, PrintWriter out) { HashMap<BasicUtils.PairGeneric<Integer, Long>, Integer> map = new HashMap<>(); int[] vals = in.nextIntArray(26); char[] s = in.nextString().toCharArray(); int n = s.length; long sum = 0; long ans = 0; for (int i = 0; i < n; ++i) { int c = s[i] - 'a'; BasicUtils.PairGeneric<Integer, Long> cur = new BasicUtils.PairGeneric<>(c, sum); Integer got = map.get(cur); if (got == null) got = 0; ans += got; sum += vals[c]; cur = new BasicUtils.PairGeneric<>(c, sum); got = map.get(cur); if (got == null) got = 0; map.put(cur, got + 1); } out.println(ans); // int[] a = in.nextIntArray(26); // char[] s = in.nextString().toCharArray(); // int n = s.length; // long[] cum = new long[n + 1]; // for (int i = 0; i < n; i++) { // cum[i + 1] = cum[i] + a[s[i] - 'a']; // } // long num = 0; // for (int i = 0; i < 26; i++) { // LongHashMap lhm = new LongHashMap(); // for (int j = 0; j < n; j++) { // if (s[j] == 'a' + i) { // { // Object val = lhm.get(cum[j]); // if (val != null) { // num += (Integer) val; // } // } // // { // Object val = lhm.get(cum[j + 1]); // if (val != null) { // int x = (Integer) val; // lhm.put(cum[j + 1], x + 1); // } else { // lhm.put(cum[j + 1], 1); // } // } // } // } // } // out.println(num); } } static class BasicUtils { public static class PairGeneric<K extends Comparable<K>, V extends Comparable<V>> implements Comparable<BasicUtils.PairGeneric<K, V>> { public K key; public V value; PairGeneric(K key, V value) { this.key = key; this.value = value; } K getKey() { return key; } V getValue() { return value; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BasicUtils.PairGeneric pair = (BasicUtils.PairGeneric) o; if (key != null ? !key.equals(pair.key) : pair.key != null) return false; if (value != null ? !value.equals(pair.value) : pair.value != null) return false; return true; } public int compareTo(BasicUtils.PairGeneric<K, V> o) { int cmp = this.getKey().compareTo(o.getKey()); if (cmp == 0) cmp = this.getValue().compareTo(o.getValue()); return cmp; } public int hashCode() { int result = key != null ? key.hashCode() : 0; result = 31 * result + (value != null ? value.hashCode() : 0); return result; } public String toString() { return "Pair{" + "key=" + key + ", value=" + value + '}'; } } } static class FastReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar; private int pnumChars; private FastReader.SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } private int pread() { if (pnumChars == -1) { throw new InputMismatchException(); } if (curChar >= pnumChars) { curChar = 0; try { pnumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (pnumChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = pread(); while (isSpaceChar(c)) c = pread(); int sgn = 1; if (c == '-') { sgn = -1; c = pread(); } int res = 0; do { if (c == ',') { c = pread(); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = pread(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } public String nextString() { int c = pread(); while (isSpaceChar(c)) c = pread(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = pread(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
8f1cea7f0a33416c9424db3bc4aae6bb
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class D { int[] waits = new int[26]; char[] s; int[] lengthsOfCharacters = new int[26]; long[][] mem = new long[26][100000]; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); D d = new D(); for (int i = 0; i < d.waits.length; i++) { d.waits[i] = scanner.nextInt(); } d.s = scanner.next().toCharArray(); long strong = 0; for (int i = 0; i < d.s.length; i++) { d.s[i] -= 'a'; strong += d.waits[d.s[i]]; d.mem[d.s[i]][d.lengthsOfCharacters[d.s[i]]] = strong; d.lengthsOfCharacters[d.s[i]]++; } long result = 0; long tempLength = 0; long tempCost = 0; HashMap<Long, Long> map = new HashMap(); for (int i = 0; i < d.mem.length; i++) { tempLength = d.lengthsOfCharacters[i]; tempCost = d.waits[i]; for (int j = 0; j < tempLength; j++) { result += map.getOrDefault(d.mem[i][j] - tempCost, 0l); map.put(d.mem[i][j], map.getOrDefault(d.mem[i][j], 0l) + 1); } map.clear(); // for (int j = 0; j < tempLength; j++) { // for (int j2 = j + 1; j2 < tempLength; j2++) { // if (d.mem[i][j2] - d.mem[i][j] - tempCost == 0) { // result++; // } // } // } } System.out.println(result); } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
bf21ade5c949a4c406eb701f373acd1b
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.*; import java.util.*; public class D { FastScanner in; PrintWriter out; int i = 0, j = 0; void solve() { /**************START**************/ int[] x = new int[26]; HashMap<Long, Integer>[] map = (HashMap<Long, Integer>[]) new HashMap[26]; for (i = 0; i < 26; i++) { x[i] = in.nextInt(); map[i] = new HashMap<Long, Integer>(); } long total = 0; String s = in.next(); int n = s.length(); long sum = 0; for (i = 0; i < n; i++) { int c = s.charAt(i) - 'a'; total += map[c].getOrDefault(sum, 0); sum += x[c]; int prev = map[c].getOrDefault(sum, 0); map[c].put(sum, prev+1); } out.println(total); /***************END***************/ } public static void main(String[] args) { new D().runIO(); } 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(); } //This will empty out the current line (if non-empty) and return the next line down. If the next line is empty, will return the empty string. String nextLine() { st = null; String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } 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()); } } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
6bd8617a59f774712f99272f7dd6e609
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; import java.util.StringTokenizer; public class A_And_B_And_Interesting_Substrings { public static void main(String [] args) { Scanner sc=new Scanner (System.in); int [] weights=new int [26]; HashMap<Long, Integer> [] arr=new HashMap [26]; StringTokenizer st=new StringTokenizer(sc.nextLine()); for(int i=0;i<26;i++) { weights[i]=Integer.parseInt(st.nextToken()); arr[i]=new HashMap<Long, Integer>(); } String s=sc.nextLine(); //System.out.println(s); long sum=0; long ans=0; for(int i=0;i<s.length();i++) { int val=arr[s.charAt(i)-'a'].getOrDefault(sum, 0); //System.out.println(val); ans+=val; sum+=weights[s.charAt(i)-'a']; val=arr[s.charAt(i)-'a'].getOrDefault(sum, 0); arr[s.charAt(i)-'a'].put(sum, val+1); } System.out.println(ans); } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
7da798a00f80f022bee577f9d12c8531
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.*; import java.util.*; public class Sol2{ public static HashMap<Long, Long> mp = new HashMap<>(); public static int dp[][] = new int[100001][26]; public static void main(String[] args) throws IOException{ FastScanner sc = new FastScanner(); int alph[] = new int[26]; for(int i=0; i<26; i++) { alph[i] = sc.nextInt(); } String k = sc.nextToken(); int str[] = new int[k.length()]; long psum[] = new long[k.length()]; long tot = 0; for(int i=0; i<k.length(); i++) { str[i] = k.charAt(i)-'a'; tot+=alph[str[i]]; psum[i] = tot; } long ans = 0; for(int i=0; i<26; i++) { mp.clear(); if(str[0]==i) mp.put(psum[0],(long)1); for(int j=1; j<k.length(); j++) { if(str[j]!=i) continue; else { Long idx = mp.get(psum[j-1]); if(idx!=null) { ans+=idx; } Long cnt = mp.get(psum[j]); if(cnt==null) { cnt = (long)0; } mp.put(psum[j],cnt+1); } } } System.out.println(ans); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
104703c05133e83ff684060831e0ba1f
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { InputReader in = new InputReader(); PrintWriter out = new PrintWriter(System.out); int t = 1; Solver s = new Solver(); for (int i = 1; i <= t; i++) { s.solve(i, in, out); } out.close(); } } class Solver { void solve(int test, InputReader in, PrintWriter out) { int[] a = new int[26]; for (int i = 0; i < a.length; i++) a[i] = in.nextInt(); char[] s = in.next().toCharArray(); char[] b = new char[s.length + 1]; System.arraycopy(s, 0, b, 1, s.length); ArrayList<Integer>[] pos = new ArrayList[26]; for (int i = 0; i < pos.length; i++) pos[i] = new ArrayList<>(); long[] prefix = new long[s.length + 1]; for (int i = 1; i <= s.length; i++) { prefix[i] = a[b[i] - 'a']; prefix[i] += prefix[i - 1]; pos[b[i] - 'a'].add(i); } long ans = 0; for (int i = 0; i < 26; i++) { Map<Long, Integer> map = new HashMap<>(); for (int j = 0; j < pos[i].size(); j++) { int p = pos[i].get(j); ans += map.getOrDefault(prefix[p - 1], 0); map.put(prefix[p], map.getOrDefault(prefix[p], 0) + 1); } } out.println(ans); } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader() { 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
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
85e40b8fc5efd897e097ec886c7d17a1
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) throws IOException { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int b[]=in.nextIntArray(26); String s=in.readString(); char a[]=s.toCharArray(); //long sum=0; long sum[]=new long[s.length()]; LinkedList<Integer> l[]=new LinkedList[26]; for(int i=0;i<26;i++) l[i]=new LinkedList<Integer>(); l[a[0]-'a'].add(0); sum[0]=b[a[0]-'a']; for(int i=1;i<s.length();i++) { sum[i]=b[a[i] - 'a']; sum[i] += sum[i - 1]; l[a[i]-'a'].add(i); } long ans=0; for(char cd='a';cd<='z';cd++) { HashMap<Long,Integer> hm=new HashMap<Long,Integer>(); for(int x:l[cd-'a']) { if(x>=1) { // System.out.println(sum[x-1]); if(hm.containsKey(sum[x-1])) { ans+=(long)hm.get(sum[x-1]); } } if(!hm.containsKey(sum[x])) hm.put(sum[x],1); else hm.put(sum[x],hm.get(sum[x])+1); } //System.out.println("---"); } System.out.println(ans); } public static long power(long a,long b) { long result=1; while(b>0) { if(b%2==1) result*=a; a=a*a; b/=2; } return result; } public static boolean isPrime(long 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; } public static long pow(long n,long p,long m) { long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } static class Pair implements Comparable<Pair>{ String name; int age; String add; String ht; Pair(String mr,int er,String ad,String hte){ name=mr;age=er; add=ad; ht=hte; } @Override public int compareTo(Pair o) { return 1; } } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a%b); } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { 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 = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } 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 interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
d7812a97ce18c2e1fa2b61673a97aa13
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; import java.util.HashMap; /** * Built using CHelper plug-in * Actual solution is at the top * * @author zodiacLeo */ 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 scores[] = new int[26]; HashMap<Long, Integer>[] count = new HashMap[26]; for (int i = 0; i < 26; i++) { scores[i] = in.nextInt(); count[i] = new HashMap<Long, Integer>(); } String s = in.next(); long result = 0; long sum = 0; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); result += get(count[ch - 'a'], sum); sum += scores[ch - 'a']; put(count[ch - 'a'], sum); } out.println(result); } public void put(HashMap<Long, Integer> map, long key) { map.put(key, get(map, key) + 1); } public int get(HashMap<Long, Integer> map, long key) { if (map.containsKey(key)) { return map.get(key); } return 0; } } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
475c7ad2d606055d32863cd1a65ea0e2
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main { public void solve() throws IOException{ int[] aa = new int[26]; for(int i = 0; i < 26; i++){ aa[i] = in.nextInt(); } char[] cc = in.next().toCharArray(); int n = cc.length; long[] cum = new long[n + 1]; for(int i = 1; i <= n; i++){ cum[i] = cum[i - 1] + aa[cc[i - 1] - 'a']; } HashMap<List<Long>, Long> map = new HashMap<>(); long res = 0L; for(int i = 0; i < n; i++){ long num = cc[i] - 'a'; long cumsum = cum[i]; List<Long> qkey = new ArrayList<>(); qkey.add(num); qkey.add(cumsum - aa[(int)num]); res += map.getOrDefault(qkey, 0L); qkey = new ArrayList<>(); qkey.add(num); qkey.add(cumsum); map.put(qkey, map.getOrDefault(qkey, 0L) + 1); } out.println(res); return; } FastScanner in; PrintWriter out; static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { if (st == null || !st.hasMoreTokens()) return br.readLine(); StringBuilder result = new StringBuilder(st.nextToken()); while (st.hasMoreTokens()) { result.append(" "); result.append(st.nextToken()); } return result.toString(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } void run() throws IOException { in = new FastScanner(System.in); out = new PrintWriter(System.out, false); solve(); out.close(); } public static void main(String[] args) throws IOException{ new Main().run(); } public void printArr(int[] arr){ for(int i = 0; i < arr.length; i++){ out.print(arr[i] + " "); } out.println(); } public long gcd(long a, long b){ if(a == 0) return b; return gcd(b % a, a); } public boolean isPrime(long num){ if(num == 0 || num == 1){ return false; } for(int i = 2; i * i <= num; i++){ if(num % i == 0){ return false; } } return true; } class Pair{ int x; int y; Pair(int ix, int iy){ x = ix; y = iy; } } class Tuple{ int x; int y; int z; Tuple(int ix, int iy, int iz){ x = ix; y = iy; z = iz; } } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
0bd359ab55efbb4836ab523d051e1225
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.IOException; import java.util.InputMismatchException; import java.util.HashMap; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Walker */ 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(); } } class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { long[] valMap = new long['z' + 1]; for(int i = 'a'; i <= 'z'; i++){ valMap[i] = in.readInt(); } long ret = 0; String s = in.readLine(); HashMap<Long, HashMap<Character, Long>> sumMap = new HashMap<Long, HashMap<Character, Long>>(); long[] sum = new long[s.length()]; sum[0] = valMap[s.charAt(0)]; HashMap<Character, Long> newMap = new HashMap<Character, Long>(); newMap.put(s.charAt(0), (long)1); sumMap.put(sum[0], newMap); for(int i = 1; i < s.length(); i++){ char c = s.charAt(i); sum[i] = sum[i - 1] + valMap[c]; long curr = sum[i]; long last = sum[i - 1]; if(sumMap.containsKey(last)){ if(sumMap.get(last).containsKey(c)){ ret += sumMap.get(last).get(c); } } if(sumMap.containsKey(curr)){ if(sumMap.get(curr).containsKey(c)){ long k = sumMap.get(curr).get(c); sumMap.get(curr).put(c, k + 1); } else{ sumMap.get(curr).put(c, (long)1); } } else{ newMap = new HashMap<Character, Long>(); newMap.put(c, (long)1); sumMap.put(curr, newMap); } } out.print(ret); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
3fbade6cd95c805605bbb84c98dc2dcd
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Washoum */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; inputClass in = new inputClass(inputStream); PrintWriter out = new PrintWriter(outputStream); DAAndBAndInterestingSubstrings solver = new DAAndBAndInterestingSubstrings(); solver.solve(1, in, out); out.close(); } static class DAAndBAndInterestingSubstrings { public void solve(int testNumber, inputClass sc, PrintWriter out) { int[] v = new int[26]; for (int i = 0; i < 26; i++) { v[i] = sc.nextInt(); } String s = sc.nextLine(); int n = s.length(); long[] pref = new long[n]; pref[0] = v[s.charAt(0) - 'a']; for (int i = 1; i < n; i++) { pref[i] = pref[i - 1] + v[s.charAt(i) - 'a']; } HashMap<DAAndBAndInterestingSubstrings.Pair, Integer> here = new HashMap<>(); long ans = 0; for (int i = 0; i < n - 1; i++) { DAAndBAndInterestingSubstrings.Pair a = new DAAndBAndInterestingSubstrings.Pair(pref[i], s.charAt(i)); here.putIfAbsent(a, 0); here.put(a, here.get(a) + 1); DAAndBAndInterestingSubstrings.Pair h = new DAAndBAndInterestingSubstrings.Pair(pref[i], s.charAt(i + 1)); if (here.get(h) != null) { ans += here.get(h); } } out.println(ans); } static class Pair { long x; char y; public Pair() { } public Pair(long x, char y) { this.x = x; this.y = y; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DAAndBAndInterestingSubstrings.Pair pair = (DAAndBAndInterestingSubstrings.Pair) o; return x == pair.x && y == pair.y; } public int hashCode() { int result = Long.hashCode(x); result = 31 * result + Character.hashCode(y); return result; } } } static class inputClass { BufferedReader br; StringTokenizer st; public inputClass(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
bade5adef8028fb4ed7422b373e74d85
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; public class AandBandInterestingSubstrings { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String line = in.readLine(); String[] part = line.split(" "); int[] scores = new int[26]; for (int i = 0; i < 26; i++) scores[i] = Integer.parseInt(part[i]); line = in.readLine(); int n = line.length(); long count = 0; long[] preSum = new long[n]; int index = line.charAt(0) - 'a'; preSum[0] = scores[index]; Map<Integer, Map<Long, Long>> maps = new HashMap<>(); for (int i = 0; i < 26; i++) maps.put(i, new HashMap<>()); maps.get(index).put(preSum[0], 1L); for (int i = 1; i < n; i++) { int key = line.charAt(i) - 'a'; preSum[i] = preSum[i - 1] + scores[key]; if (maps.get(key).containsKey(preSum[i - 1])) count += maps.get(key).get(preSum[i - 1]); if (maps.get(key).containsKey(preSum[i])) maps.get(key).put(preSum[i], maps.get(key).get(preSum[i]) + 1L); else maps.get(key).put(preSum[i], 1L); } out.println(count); out.close(); in.close(); } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
278933db8258a3382e85043fe3bbf1fe
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; 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); AandBandInterestingSubstrings solver = new AandBandInterestingSubstrings(); solver.solve(1, in, out); out.close(); } static class AandBandInterestingSubstrings { public void solve(int testNumber, InputReader in, PrintWriter out) { long[] preferences = new long['z' + 1]; for (int i = 0; i < 26; i++) preferences['a' + i] = in.nextInt(); String s = in.next(); char[] chars = new char[s.length() + 1]; for (int i = 1; i <= s.length(); i++) chars[i] = s.charAt(i - 1); long[] arr = new long[s.length() + 1]; long[] presum = new long[s.length() + 1]; for (int i = 1; i <= s.length(); i++) { arr[i] = preferences[chars[i]]; presum[i] = presum[i - 1] + arr[i]; } HashMap<Character, ArrayList<Integer>> positions = new HashMap<>(); for (int i = 1; i <= s.length(); i++) { ArrayList<Integer> l = positions.get(chars[i]); if (l == null) l = new ArrayList<>(); l.add(i); positions.put(chars[i], l); } long answer = 0; for (Character c : positions.keySet()) { if (positions.get(c).size() < 2) continue; long sum = arr[positions.get(c).get(0)]; Occurrences<Long> occurrences = new Occurrences<>(); occurrences.increment(sum); for (int i = 1; i < positions.get(c).size(); i++) { int l = positions.get(c).get(i - 1) + 1, r = positions.get(c).get(i) - 1; long _sum = presum[r] - presum[l - 1]; Integer occ = occurrences.get(sum + _sum); if (occ == null) occ = 0; answer += occ; sum += _sum + arr[positions.get(c).get(i)]; occurrences.increment(sum); } } out.println(answer); } } static class Occurrences<E> extends HashMap<E, Integer> { public void increment(E key) { Integer occ = get(key); if (occ == null) occ = 0; put(key, occ + 1); } } static class InputReader { private StringTokenizer tokenizer; private BufferedReader reader; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } private void fillTokenizer() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } } public String next() { fillTokenizer(); return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
6f93b72e76b235cbd0307d3e79a7f558
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.awt.*; import java.io.*; import java.util.*; public class Abc { public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); int arr[]=new int[26]; for (int i=0;i<26;i++)arr[i]=sc.nextInt(); String s=sc.next(); Map<Long,Integer> map[]=new HashMap[26]; for (int i=0;i<26;i++)map[i]=new HashMap<>(); long sum=0,ans=0; for (char c:s.toCharArray()){ ans+=map[c-'a'].getOrDefault(sum,0); sum+=arr[c-'a']; map[c-'a'].put(sum,map[c-'a'].getOrDefault(sum,0)+1); } System.out.println(ans); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
bbb84f41e7d9ffc5eaa14d702be6fe00
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.util.HashMap; import java.util.Scanner; public class A_and_B_and_Interesting_Strings { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int[] arr = new int[26]; for (int i = 0; i < 26; i++) { arr[i] = scn.nextInt(); } String s = scn.next(); long mod = 2651541199513L; long p = 100123456789L; HashMap<Long, Integer> st = new HashMap<>(); long sum = 0; long ans=0; for (int i = 0; i+1 < s.length(); i++) { if(s.charAt(i)==s.charAt(i+1)) { ans++; } sum = sum + arr[s.charAt(i) - 'a']; long hash=((sum*p)%mod + ((s.charAt(i+1) - 'a' + 1) * (p*p)%mod)%mod) % mod; if (st.containsKey(hash)) { ans+=st.get(hash); } hash=((sum*p)%mod + ((s.charAt(i) - 'a' + 1) * (p*p)%mod)%mod) % mod; st.put(hash,st.getOrDefault(hash,0)+1); } System.out.println(ans); } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
f2c8964b4014340b2cd789e375c0f809
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.util.HashMap; import java.util.Scanner; public class D519xx { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[] w = new int[26]; /*create an array of maps, each map denotes a character *<sum of the weights of all the previous letters, the number of occurrences> *that's why the key must be a long *the map action will only be triggered when we find that the same letter *has previously occurred with the same sum, which means that the weight *of all the letters between the two occurrences is zero *the syntax is kinda weird **/ HashMap<Long, Integer>[] m = (HashMap<Long, Integer>[]) new HashMap[26]; for (int i = 0; i < 26; i++) { w[i] = sc.nextInt(); // this array has the all the weights // use the for loop to instantiate all the maps in the array m[i] = new HashMap<Long, Integer>(); } /* storing the length of the string in a variable will *decrease the time of the for loop **/ String s = sc.next(); int n = s.length(); long sum = 0; long ans = 0; int c = 0; for (int i = 0; i < n; i++) { // convert a to zero b->1 z->25 c = s.charAt(i) - 'a'; /* getOrDefault returns the second parameter if the key wasn't found * we will make it zero so the ans doesn't increase which means * that this instance of this character has a unique sum **/ ans += m[c].getOrDefault(sum, 0); sum += w[c]; /*hash maps can't increment so instead of putting the old value * in a variable, we can replace the current element in place with the * following code **/ m[c].put(sum, m[c].getOrDefault(sum, 0) + 1); } System.out.println(ans); } } /* 1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1 xabcab 1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1 aaaaaaa 1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1 acaaca */
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
632147b0319e7e2c77b6866683afe1bf
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; import java.lang.*; import static java.lang.Math.*; public class Main implements Runnable { public static void main(String[] args) { new Thread(null, new Main(), "Check2", 1 << 28).start();// to increse stack size in java } void init(ArrayList <Integer> adj[], int n){ for(int i=0;i<=n;i++)adj[i]=new ArrayList<>(); } static long mod = (long) (1e9+7); public void run() { InputReader in=new InputReader(System.in); PrintWriter w=new PrintWriter(System.out); int f[]=new int[26]; for(int i=0;i<26;i++)f[i]=in.nextInt(); HashMap <Long,Integer> map[]=new HashMap[26]; for(int i=0;i<26;i++)map[i]=new HashMap<>(); long ans=0; char c[]=in.next().toCharArray(); long sum=0; for(int i=0;i<c.length;i++){ if(map[c[i]-97].containsKey(sum)){ ans=ans+map[c[i]-97].get(sum); } sum=sum+(long)f[c[i]-97]; if(map[c[i]-97].containsKey(sum)){ map[c[i]-97].put(sum,map[c[i]-97].get(sum)+1); } else map[c[i]-97].put(sum,1); } w.println(ans); w.close(); } class pair { int a; long b; pair(int a,long b){ this.a=a; this.b=b; } public boolean equals(Object obj) { // override equals method for object to remove tem from arraylist and sets etc....... if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; pair other = (pair) obj; if (b!= other.b||a!=other.a) return false; return true; } } static long modinv(long a,long b) { long p=power(b,mod-2); p=a%mod*p%mod; p%=mod; return p; } static long power(long x,long y){ if(y==0)return 1%mod; if(y==1)return x%mod; long res=1; x=x%mod; while(y>0){ if((y%2)!=0){ res=(res*x)%mod; } y=y/2; x=(x*x)%mod; } return res; } static long gcd(long a,long b){ if(b==0)return a; return gcd(b,a%b); } static void sev(int a[],int n){ for(int i=2;i<=n;i++)a[i]=i; for(int i=2;i<=n;i++){ if(a[i]!=0){ for(int j=2*i;j<=n;){ a[j]=0; j=j+i; } } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public 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
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
2889827ad5994a4e713e99086d520021
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.*; import java.util.*; public class practice519d { public static void main(String[] args) throws Exception { // BufferedReader f = new BufferedReader(new FileReader (new File("sample.txt"))); // PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("sample.txt"))); // StringTokenizer st = new StringTokenizer(f.readLine()); BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); StringTokenizer st = new StringTokenizer(f.readLine()); int[] value = new int[26]; for (int i = 0; i < 26; i++) { value[i] = Integer.parseInt(st.nextToken()); } String s = f.readLine(); long psum = value[s.charAt(0)-'a']; TreeMap<c519d, Integer> tm = new TreeMap<c519d, Integer>(); tm.put(new c519d(psum, s.charAt(0)), 1); long ans = 0; for (int i = 1; i < s.length(); i++) { c519d prev = new c519d(psum, s.charAt(i)); if (i > 0) { ans += tm.getOrDefault(prev, 0); } psum += value[s.charAt(i)-'a']; c519d curr = new c519d(psum, s.charAt(i)); tm.put(curr, tm.getOrDefault(curr, 0)+1); } // out.println(tm); out.println(ans); out.close(); } } class c519d implements Comparable { long sum; char c; public c519d(long a, char b) { sum = a; c = b; } @Override public int compareTo(Object o) { if (sum == ((c519d)o).sum) { return c - ((c519d)o).c; } else if (sum > ((c519d)o).sum) { return 1; } return -1; } @Override public boolean equals(Object o) { return sum == ((c519d)o).sum && c == ((c519d)o).c; } @Override public String toString() { return sum + " " + c; } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
d2023e0273bb09a3cf8e7df1ee8635cd
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; public class D_InterestingSubstrings { public static void main(String args[]) throws FileNotFoundException { InputReader in = new InputReader(System.in); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); StringBuilder sb = new StringBuilder(); // ----------My Code---------- int arr[] = new int[26]; arr = in.nextIntArray(26, 0); char[] x = in.nextLine().toCharArray(); int n = x.length; long val[] = new long[n]; val[0] = arr[x[0] - 'a']; HashMap<Long, Long> map = new HashMap<Long, Long>(); // int curr_sum = 0; // int find_Sum = 0; long ans = 0; for (int i = 1; i < n; i++) val[i] = arr[x[i] - 'a'] + val[i - 1]; for (char i = 'a'; i <= 'z'; i++) { boolean b = true; map.clear(); for (int j = 0; j < n; j++) { if (x[j] == i) { if (b) { map.put(val[j], 1L); b = false; } else { long xx = val[j] - arr[i - 'a']; if (map.containsKey(xx)) ans += map.get(xx); if (map.containsKey(val[j])) { map.put(val[j], map.get(val[j]) + 1); } else map.put(val[j], 1L); } } } } /* * for (int i = 0; i < x.length; i++) { curr_sum = curr_sum + arr[i]; * * if (curr_sum == find_Sum&&(x[i]==x[0])){ ans++; } * * if (map.containsKey(curr_sum - find_Sum)){ int * ptr=map.get(curr_sum-find_Sum); ans++; } if(x[ptr+1]==x[i]){ } * * map.put(curr_sum , i); } */ out.println(ans); // ---------------The End------------------ out.close(); } // n // ---------------Extra Methods------------------ public static long pow(long x, long n, long mod) { long res = 1; x %= mod; while (n > 0) { if (n % 2 == 1) { res = (res * x) % mod; } x = (x * x) % mod; n /= 2; } return res; } public static boolean isPal(String s) { for (int i = 0, j = s.length() - 1; i <= j; i++, j--) { if (s.charAt(i) != s.charAt(j)) return false; } return true; } public static String rev(String s) { StringBuilder sb = new StringBuilder(s); sb.reverse(); return sb.toString(); } public static long gcd(long x, long y) { if (x % y == 0) return y; else return gcd(y, x % y); } public static int gcd(int x, int y) { if (x % y == 0) return y; else return gcd(y, x % y); } public static long gcdExtended(long a, long b, long[] x) { if (a == 0) { x[0] = 0; x[1] = 1; return b; } long[] y = new long[2]; long gcd = gcdExtended(b % a, a, y); x[0] = y[1] - (b / a) * y[0]; x[1] = y[0]; return gcd; } public static int abs(int a, int b) { return (int) Math.abs(a - b); } public static long abs(long a, long b) { return (long) Math.abs(a - b); } public static int max(int a, int b) { if (a > b) return a; else return b; } public static int min(int a, int b) { if (a > b) return b; else return a; } public static long max(long a, long b) { if (a > b) return a; else return b; } public static long min(long a, long b) { if (a > b) return b; else return a; } // ---------------Extra Methods------------------ public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } 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 char nextChar() { return next().charAt(0); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n, int f) { if (f == 0) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } else { int[] arr = new int[n + 1]; for (int i = 1; i < n + 1; i++) { arr[i] = nextInt(); } return arr; } } public long[] nextLongArray(int n, int f) { if (f == 0) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } else { long[] arr = new long[n + 1]; for (int i = 1; i < n + 1; i++) { arr[i] = nextLong(); } return arr; } } public double[] nextDoubleArray(int n, int f) { if (f == 0) { double[] arr = new double[n]; for (int i = 0; i < n; i++) { arr[i] = nextDouble(); } return arr; } else { double[] arr = new double[n + 1]; for (int i = 1; i < n + 1; i++) { arr[i] = nextDouble(); } return arr; } } } static class Pair implements Comparable<Pair> { int a, b; Pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(Pair o) { // TODO Auto-generated method stub if (this.a != o.a) return Integer.compare(this.a, o.a); else return Integer.compare(this.b, o.b); } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair) o; return p.a == a && p.b == b; } return false; } public int hashCode() { return new Integer(a).hashCode() * 31 + new Integer(b).hashCode(); } } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
214c2ed225119046c90ca0c871ca0143
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.TreeMap; public class CF294D { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer strtok; strtok = new StringTokenizer(in.readLine()); int[] v = new int[26]; for (int i = 0; i < 26; i++) { v[i] = Integer.parseInt(strtok.nextToken()); } char[] str = in.readLine().toCharArray(); TreeMap<Long, Integer>[] mp = new TreeMap[26]; for (int i = 0; i < 26; i++) mp[i] = new TreeMap<Long, Integer>(); long sum = 0; long answer = 0; for (int i = 0; i < str.length; i++) { if (mp[str[i] - 'a'].get(sum) != null) answer += mp[str[i] - 'a'].get(sum); sum += v[str[i] - 'a']; if (!mp[str[i] - 'a'].containsKey(sum)) mp[str[i] - 'a'].put(sum, 0); mp[str[i] - 'a'].put(sum, mp[str[i] - 'a'].get(sum) + 1); } System.out.println(answer); } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
966c765075dfdc64875b25f006f1f5ba
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.*; import java.util.*; public class AB { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] inp = br.readLine().split(" "); int[] weight = new int[26]; HashMap<Long,Integer>[] hm = new HashMap[26]; for(int i=0;i<26;i++) { hm[i] = new HashMap<Long , Integer>(); weight[i] = Integer.parseInt(inp[i]); } String s = br.readLine(); Long[] prefix = new Long[s.length()]; prefix[0] = (long)weight[s.charAt(0)-'a']; hm[s.charAt(0)-'a'].put(prefix[0], 1); int n = s.length(); Long ans=0l; for(int i=1;i<n;i++) { prefix[i] = prefix[i-1]+weight[s.charAt(i)-'a']; if(hm[s.charAt(i)-'a'].containsKey(prefix[i-1])) ans+=hm[s.charAt(i)-'a'].get(prefix[i-1]); int d=0; if(hm[s.charAt(i)-'a'].containsKey(prefix[i])) d=hm[s.charAt(i)-'a'].get(prefix[i]); hm[s.charAt(i)-'a'].put(prefix[i], d+1); } System.out.println(ans); } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
fec9df1cbf44e8562915f88827a8459a
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; public class Powers2 { static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(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 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); } } public static void main(String []args) throws IOException { PrintWriter pw =new PrintWriter(System.out); Scanner sc=new Scanner(System.in); int ch[]=new int [26];long ans=0l; for(int i=0;i<26;i++)ch[i]=sc.nextInt(); String in =sc.next(); TreeMap<Long,Integer>arr[]=new TreeMap[26];TreeMap<Character,Integer>tm=new TreeMap<>();char f='a'; for(int i=0;i<26;i++) {arr[i]=new TreeMap<>();tm.put((char)f++, i);} long prefix[]=new long [in.length()];prefix[0]=ch[tm.get(in.charAt(0))]; for(int i=1;i<in.length();i++) {prefix[i]=prefix[i-1]+ch[tm.get(in.charAt(i))];} for(int i=0;i<in.length();i++) { if(arr[tm.get(in.charAt(i))].containsKey(prefix[i]-ch[tm.get(in.charAt(i))]))ans+=arr[tm.get(in.charAt(i))].get(prefix[i]-ch[tm.get(in.charAt(i))]); arr[tm.get(in.charAt(i))].put(prefix[i],arr[tm.get(in.charAt(i))].getOrDefault(prefix[i],0 )+1); } pw.println(ans);pw.flush(); }}
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
e50da62d780e3df6e636e459874df69f
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class Main { static 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(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[256]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public 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(); } } static class arr implements Comparable<arr>{ long x;int y; arr(long a,int b){ x=a; y=b; } public int compareTo(arr ob){ return (int)(this.x-ob.x); } } public static void main(String args[])throws IOException{ Scanner in = new Scanner(System.in); int[] c = new int[26]; for(int i=0;i<26;i++) c[i]=in.nextInt(); String k = in.nextLine(); String s = in.nextLine(); int n = s.length(); int[] a = new int[s.length()]; ArrayList<Long> adj[] = new ArrayList[26]; for(int i=0;i<26;i++) adj[i]=new ArrayList<>(); for(int i=0;i<s.length();i++) a[i]=c[s.charAt(i)-97]; long sum=0; for(int i=0;i<n;i++){ sum+=a[i]; adj[s.charAt(i)-97].add(sum); } long ans=0; HashMap<Long,Long> map = new HashMap<>(); for(int i=0;i<26;i++){ map.clear(); for(int j=0;j<adj[i].size();j++){ long x=0; if(map.get(adj[i].get(j)-c[i])!=null){ x = map.get(adj[i].get(j)-c[i]); ans+=x; } if(map.get(adj[i].get(j))==null) map.put(adj[i].get(j),(long) 1); else{ x=map.get(adj[i].get(j)); map.put(adj[i].get(j),x+1); } } } System.out.println(ans); } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
3278e489fc01471dabc1e6bb1efb37d4
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.util.function.BiFunction; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.util.NoSuchElementException; import java.math.BigInteger; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.io.OutputStreamWriter; /** * Built using CHelper plug-in * Actual solution is at the top * @author PloadyFree */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int[] a = IOUtils.readIntArray(in, 26); char[] s = in.next().toCharArray(); Map<Long, Integer>[] maps = new Map[26]; for (int i = 0; i < 26; i++) maps[i] = new HashMap<>(); long sum = 0; long ans = 0; for (int c : s) { c -= 'a'; sum += a[c]; Map<Long, Integer> m = maps[c]; int add = m.getOrDefault(sum - a[c], 0); ans += add; m.merge(sum, 1, (x,y) -> x+y); } out.print(ans); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { 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 String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void close() { writer.close(); } public void print(long i) { writer.print(i); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
d1150ea18457e5f5470b279e02aff105
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.util.function.BiFunction; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.util.NoSuchElementException; import java.util.stream.Stream; import java.math.BigInteger; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.stream.IntStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.io.OutputStreamWriter; import java.util.function.IntFunction; /** * Built using CHelper plug-in * Actual solution is at the top * @author PloadyFree */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int[] a = IOUtils.readIntArray(in, 26); char[] s = in.next().toCharArray(); Map<Long, Integer>[] maps = IntStream.range(0, 26).mapToObj(i -> new HashMap<>()).toArray(Map[]::new); long sum = 0; long ans = 0; for (int c : s) { c -= 'a'; sum += a[c]; Map<Long, Integer> m = maps[c]; int add = m.getOrDefault(sum - a[c], 0); ans += add; m.merge(sum, 1, (x,y) -> x+y); } out.print(ans); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { 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 String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void close() { writer.close(); } public void print(long i) { writer.print(i); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
538e19f74f6eaa404021916d4825f899
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
import java.io.*; import java.util.*; public class D519 { static FastReader in = null; static PrintWriter out = null; public static void solve() { int[] x = new int[26]; for(int i=0; i<26; i++) x[i] = in.nextInt(); char[] s = in.next().toCharArray(); int n = s.length; Map<Long, Integer>[] hm = new HashMap[26]; for(int i=0; i<26; i++) hm[i] = new HashMap<>(); long[] sum = new long[n]; sum[0] = x[s[0]-'a']; for(int i=1; i<n; i++){ sum[i] = sum[i-1] + x[s[i]-'a']; } long ans = 0; for(int i=0; i<n; i++){ long lookfor = sum[i] - x[s[i]-'a']; if(hm[s[i]-'a'].containsKey(lookfor)) ans += hm[s[i]-'a'].get(lookfor); hm[s[i]-'a'].put(sum[i], hm[s[i]-'a'].getOrDefault(sum[i], 0) + 1); } out.println(ans); } public static void main(String[] args) { in = new FastReader(System.in); out = new PrintWriter(System.out); solve(); out.flush(); out.close(); } static class FastReader { BufferedReader read; StringTokenizer tokenizer; public FastReader(InputStream in) { read = new BufferedReader(new InputStreamReader(in)); } public String next() { while(tokenizer == null || !tokenizer.hasMoreTokens()) { try{ tokenizer = new StringTokenizer(read.readLine()); }catch(Exception e){ throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextLine(){ try { return read.readLine(); } catch(Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArr(int n) { int[] a = new int[n]; for(int i=0; i<n; ++i) { a[i] = nextInt(); } return a; } public long[] nextLongArr(int n) { long[] a = new long[n]; for(int i=0; i<n; ++i) { a[i] = nextLong(); } return a; } } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
3500305f499c7c8a6950de5634aa2ff0
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
/** * Created by ankeet on 11/29/16. */ import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.StringTokenizer; public class D519 { static FastReader in = null; static PrintWriter out = null; public static void solve() { int[] x = new int[26]; for(int i=0; i<26; i++) x[i] = in.nextInt(); char[] s = in.next().toCharArray(); int n = s.length; int[] ss = new int[n]; for(int i=0; i<n; i++) ss[i] = (int)(s[i]-'a'); HashMap<Long, Integer>[] hm = new HashMap[26]; for(int i=0; i<26; i++) hm[i] = new HashMap<>(); long[] sum = new long[n]; sum[0] = x[ss[0]]; for(int i=1; i<n; i++) sum[i] = sum[i-1] + x[ss[i]]; long ct = 0; hm[ss[0]].put(sum[0], 1); for(int i=1; i<n; i++){ if(hm[ss[i]].containsKey(sum[i-1])){ int v = hm[ss[i]].get(sum[i-1]); ct+=v; } if(hm[ss[i]].containsKey(sum[i])){ int v = hm[ss[i]].get(sum[i]); hm[ss[i]].put(sum[i], v+1); } else{ hm[ss[i]].put(sum[i], 1); } } out.println(ct); } public static void main(String[] args) { in = new FastReader(System.in); out = new PrintWriter(System.out); solve(); out.flush(); out.close(); } static class FastReader { BufferedReader read; StringTokenizer tokenizer; public FastReader(InputStream in) { read = new BufferedReader(new InputStreamReader(in)); } public String next() { while(tokenizer == null || !tokenizer.hasMoreTokens()) { try{ tokenizer = new StringTokenizer(read.readLine()); }catch(Exception e){ throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextLine(){ try { return read.readLine(); } catch(Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArr(int n) { int[] a = new int[n]; for(int i=0; i<n; ++i) { a[i] = nextInt(); } return a; } public long[] nextLongArr(int n) { long[] a = new long[n]; for(int i=0; i<n; ++i) { a[i] = nextLong(); } return a; } } }
Java
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
44c10fda7c42a62bdf147e9b29478af5
train_001.jsonl
1425128400
A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?
256 megabytes
/** * DA-IICT * Author : Savaliya Sagar */ import java.io.*; import java.math.*; import java.util.*; public class D519 { InputStream is; PrintWriter out; int v[]; char c[]; long pre[]; HashMap<Long, Integer> h[] = new HashMap[26]; void solve() { v = na(26); c = ns().toCharArray(); int n = c.length; pre = new long[n + 1]; for (int i = 0; i < 26; i++) h[i] = new HashMap<>(); for (int i = 0; i < n; i++) { pre[i + 1] = pre[i] + v[c[i] - 'a']; } long ans = 0; for (int i = 1; i <= n; i++) { int k = c[i - 1] - 'a'; if(h[k].containsKey(pre[i-1])){ long l = h[k].get(pre[i-1]); ans += l; } int z = 0; if (h[k].containsKey(pre[i])) z = h[k].get(pre[i]); h[k].put(pre[i], z + 1); } out.println(ans); } void run() throws Exception { String INPUT = "/home/sagar407/Desktop/a.txt"; is = oj ? System.in : new FileInputStream(INPUT); 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 Thread(null, new Runnable() { public void run() { try { new D519().run(); } catch (Exception e) { e.printStackTrace(); } } }, "1", 1 << 26).start(); } 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
["1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\nxabcab", "1 1 -1 1 1 1 1 1 1 1 1 1 1 1 1 7 1 1 1 8 1 1 1 1 1 1\naaa"]
2 seconds
["2", "2"]
NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.
Java 8
standard input
[ "dp", "two pointers", "data structures" ]
0dd2758f432542fa82ff949d19496346
The first line contains 26 integers xa, xb, ..., xz ( - 105 ≀ xi ≀ 105) β€” the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase lettersβ€” the string for which you need to calculate the answer.
1,800
Print the answer to the problem.
standard output
PASSED
8da9fd930107c3b8c48e6d85f1b5bafc
train_001.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class DynamicProgramming { static int[] a,b,c; static int n; static int[][] dp; public static void main(String[] args) { Scanner sc=new Scanner(System.in); n=sc.nextInt(); a=new int[n+1]; b=new int[n+1]; c=new int[n+1]; for(int i=1;i<=n;i++) { a[i]=sc.nextInt(); } dp=new int[n+1][2]; for(int i=0;i<=n;i++) Arrays.fill(dp[i], -1); for(int i=1;i<=n;i++) { b[i]=sc.nextInt(); } for(int i=1;i<=n;i++) { c[i]=sc.nextInt(); } int answer=solve(1, false); System.out.println(answer); } public static int solve(int index, boolean previous) { if(index>n) return 0; int result1,result2; //previous will be true if previous hare is feed //previous will be false if previous hare is unfeed //we can feed this hare or can put it unfeed and feed the next hare if(previous==true) { if(dp[index][1]==-1) { result1=solve(index+1, true)+b[index]; result2=solve(index+1, false)+c[index]; if(index!=n) return dp[index][1]=Math.max(result1, result2); else return dp[index][1]=result1; } } else { if(dp[index][0]==-1) { result1=solve(index+1, true)+a[index]; result2=solve(index+1, false)+b[index]; if(index!=n) return dp[index][0]=Math.max(result1, result2); else return dp[index][0]=result1; } } if(previous==false) return dp[index][0]; else return dp[index][1]; } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 7
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≀ n ≀ 3000) β€” the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≀ ai, bi, ci ≀ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
aec8940bc3244fee069bcbe3bb7fe87b
train_001.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
//package round208; import java.io.*; import java.util.*; public class ProblemD { private static final boolean DEBUG = true; private static final String INPUT_FILE = "input.txt"; private static final String OUTPUT_FILE = "output.txt"; public static void main(String[] args) { try { InputStream inputStream = System.in; //InputStream inputStream = new FileInputStream(INPUT_FILE); OutputStream outputStream = System.out; //OutputStream outputStream = new FileOutputStrean(OUTPUT_FILE); InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); (new ProblemD()).solve(in, out); out.close(); } catch (Throwable ex) { ex.printStackTrace(); } } public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; int[] b = new int[n]; int[] c = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } for (int i = 0; i < n; i++) { b[i] = in.nextInt(); } for (int i = 0; i < n; i++) { c[i] = in.nextInt(); } int[] d0 = new int[n]; int[] d1 = new int[n]; d0[0] = a[0]; d1[0] = b[0]; for (int i = 1; i < n; i++) { d0[i] = Math.max(d0[i - 1] + b[i], d1[i - 1] + a[i]); d1[i] = Math.max(d0[i - 1] + c[i], d1[i - 1] + b[i]); } out.print(d0[n-1]); } private static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { 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 void close() { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } private static void debug(String str) { if (DEBUG) { System.out.println(str); } } private static void debug(int value) { if (DEBUG) { System.out.println("" + value); } } private static void debug(Object[] arr) { if (DEBUG) { System.out.println(Arrays.toString(arr)); } } private static void debug(Object obj) { if (DEBUG) { System.out.println(obj.toString()); } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 7
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≀ n ≀ 3000) β€” the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≀ ai, bi, ci ≀ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
d476f02f24ccc3fec96f2c8748d5e5fa
train_001.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collection; import java.util.Locale; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { new Thread(null, new Runnable() { public void run() { try { long prevTime = System.currentTimeMillis(); new Main().run(); System.err.println("Total time: " + (System.currentTimeMillis() - prevTime) + " ms"); System.err.println("Memory status: " + memoryStatus()); } catch (IOException e) { e.printStackTrace(); } } }, "1", 1L << 24).start(); } void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); Object o = solve(); if (o != null) out.println(o); out.close(); in.close(); } private Object solve() throws IOException { int n = ni(); int[][] hares = new int[3][]; for (int i = 0; i < 3; i++) hares[i] = nia(n); int[][] dp = new int[2][n]; for (int i = 0; i < 2; i++) Arrays.fill(dp[i], -1); dp[0][n - 1] = hares[0][n - 1]; dp[1][n - 1] = hares[1][n - 1]; return go(hares, dp, 0, 0); } private int go(int[][] hares, int[][] dp, int side, int index) { if (dp[side][index] != -1) return dp[side][index]; dp[side][index] = 0; for (int feed = 0; feed < 2; feed++) { dp[side][index] = Math.max(dp[side][index], hares[side + (feed + 1)% 2][index] + go(hares, dp, feed, index + 1)); } return dp[side][index]; } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int ni() throws IOException { return Integer.parseInt(nextToken()); } long nl() throws IOException { return Long.parseLong(nextToken()); } double nd() throws IOException { return Double.parseDouble(nextToken()); } int[] nia(int size) throws IOException { int[] ret = new int[size]; for (int i = 0; i < size; i++) ret[i] = ni(); return ret; } long[] nla(int size) throws IOException { long[] ret = new long[size]; for (int i = 0; i < size; i++) ret[i] = nl(); return ret; } double[] nda(int size) throws IOException { double[] ret = new double[size]; for (int i = 0; i < size; i++) ret[i] = nd(); return ret; } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } void printRepeat(String s, int count) { for (int i = 0; i < count; i++) out.print(s); } void printArray(int[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(long[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array, String spec) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.printf(Locale.US, spec, array[i]); } out.println(); } void printArray(Object[] array) { boolean blank = false; for (Object x : array) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } @SuppressWarnings("rawtypes") void printCollection(Collection collection) { boolean blank = false; for (Object x : collection) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } static String memoryStatus() { return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + "/" + (Runtime.getRuntime().totalMemory() >> 20) + " MB"; } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 7
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≀ n ≀ 3000) β€” the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≀ ai, bi, ci ≀ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
61e5aafb2fcacbc743c642bbb6b906c3
train_001.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.math.BigInteger; import java.util.*; import static java.util.Arrays.sort; public class Main{ public static int max(int a,int b){ return a>b?a:b; } public static void main(String args[]){ Scanner cin=new Scanner(System.in); int n; int maxn=3010; int a[]=new int[maxn]; int b[]=new int[maxn]; int c[]=new int[maxn]; int[][] dp=new int[maxn][2]; while(cin.hasNext()){ n=cin.nextInt(); for(int i=1;i<=n;i++) a[i]=cin.nextInt(); for(int i=1;i<=n;i++) b[i]=cin.nextInt(); for(int i=1;i<=n;i++) c[i]=cin.nextInt(); if(n==1){ System.out.println(a[1]); continue; } Arrays.fill(dp[1],0); Arrays.fill(dp[0],0); dp[1][0]=a[1]; dp[1][1]=b[1]; for(int i=2;i<n;i++){ dp[i][0]=max(dp[i-1][0]+b[i],dp[i-1][1]+a[i]); dp[i][1]=max(dp[i-1][0]+c[i],dp[i-1][1]+b[i]); } int ans=max(dp[n-1][0]+b[n],dp[n-1][1]+a[n]); System.out.println(ans); } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 7
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≀ n ≀ 3000) β€” the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≀ ai, bi, ci ≀ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
6133c9512098a7e5cfa89f754780de5a
train_001.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.PriorityQueue; import java.util.StringTokenizer; public class D { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); StringTokenizer stringTokenizer; String next() throws IOException { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } void solve() throws IOException { final int n = nextInt(); final int[][] a = new int[n][3]; for(int j = 0; j < 3; j++) { for(int i = 0; i < n; i++) { a[i][j] = nextInt(); } } // c[0] = b[0]; // b[0] = a[0]; // c[n - 1] = b[n - 1]; // b[n - 1] = a[n - 1]; class Utils { boolean[][] visited = new boolean[n][2]; int[][] dp = new int[n][2]; int feedRabbits(int r, int rn) { if(visited[r][rn]) { return dp[r][rn]; } visited[r][rn] = true; int l = 0; int ln = 0; if(l == r) { return dp[r][rn] = a[l][ln + rn]; } if(r - l == 1) { return dp[r][rn] = Math.max(a[l][ln] + a[r][rn + 1], a[l][ln + 1] + a[r][rn]); } for(int k = 0; k < 2; k++) { dp[r][rn] = Math.max(dp[r][rn], a[r][rn + k] + feedRabbits(r - 1, 1 - k)); dp[r][rn] = Math.max(dp[r][rn], a[r - 1][k] + a[r][1 + rn] + feedRabbits(r - 2, 1 - k)); } return dp[r][rn]; } } writer.println(new Utils().feedRabbits(n - 1, 0)); writer.flush(); writer.close(); } public static void main(String[] args) throws IOException { new D().solve(); } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 7
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≀ n ≀ 3000) β€” the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≀ ai, bi, ci ≀ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
f0f3603b731a370e14cc7b9df4d3ecfd
train_001.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; public class ProblemD { static final long MOD = 1000000007; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.valueOf(in.readLine()); String[] ai = in.readLine().split(" "); String[] bi = in.readLine().split(" "); String[] ci = in.readLine().split(" "); int[][] pt = new int[3][n]; for (int i = 0 ; i < n ; i++) { pt[0][i] = Integer.valueOf(ai[i]); pt[1][i] = Integer.valueOf(bi[i]); pt[2][i] = Integer.valueOf(ci[i]); } int[][][] dp = new int[n+1][4][4]; for (int i = 0 ; i <= n ; i++) { for (int j = 0 ; j <= 2 ; j++) { Arrays.fill(dp[i][j], -1); } } if (n == 1) { out.println(pt[0][0]); out.flush(); return; } dp[0][0][0] = pt[0][0]; dp[0][1][2] = pt[1][0]; for (int i = 0 ; i < n-1 ; i++) { for (int p = 0 ; p <= 2 ; p++) { for (int pp = 0 ; pp <= 2 ; pp++) { if (dp[i][p][pp] == -1) { continue; } for (int d = 0 ; d <= 2 ; d++) { int to = dp[i][p][pp] + pt[d][i+1]; if (p == 0 && d == 0) { continue; } if (p == 2 && d == 2) { continue; } if (p == 1) { if (pp == 2 && d == 2) { continue; } if (pp == 0 && d == 0) { continue; } } int tpp = (d == 1) ? pp : d; dp[i+1][d][tpp] = Math.max(dp[i+1][d][tpp], to); } } } } // // 10 // 01 // 0001112111111111111 // 0112111111110 // int ans = 0; for (int i = 0 ; i <= 1 ; i++) { for (int j = 0 ; j <= 2 ; j++) { if (j == 2 && i == 1) { continue; } ans = Math.max(ans, dp[n-1][i][j]); } } out.println(ans); out.flush(); } public static void debug(Object... o) { System.err.println(Arrays.deepToString(o)); } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 7
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≀ n ≀ 3000) β€” the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≀ ai, bi, ci ≀ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
6d690cf5448855203f5bf84a5c0289e0
train_001.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.*; import java.util.*; public class D { public static void main(String[] args) { new D().run(); } void solve() throws IOException { int n = ni(); long a[] = nla(n); long b[] = nla(n); long c[] = nla(n); long d[] = new long[n + 1]; long d2[] = new long[n + 1]; d[0] = d2[0] = 0; d[1] = a[0]; d2[1] = b[0]; for (int i = 2; i < n + 1; ++i) { d[i] = Math.max(d[i - 1] + b[i - 1], d2[i - 1] + a[i - 1]); d2[i] = Math.max(d[i - 1] + c[i - 1], d2[i - 1] + b[i - 1]); } prln(d[n]); } public void run() { try { if (isFileIO) { pw = new PrintWriter(new File("output.out")); br = new BufferedReader(new FileReader("input.in")); } else { pw = new PrintWriter(System.out); br = new BufferedReader(new InputStreamReader(System.in)); } solve(); pw.close(); br.close(); } catch (IOException e) { System.err.println("IO Error"); } } private int[] nia(int n) throws IOException { int arr[] = new int[n]; for (int i = 0; i < n; ++i) arr[i] = Integer.parseInt(nextToken()); return arr; } private int[] niam1(int n) throws IOException { int arr[] = new int[n]; for (int i = 0; i < n; ++i) arr[i] = Integer.parseInt(nextToken()) - 1; return arr; } private long[] nla(int n) throws IOException { long arr[] = new long[n]; for (int i = 0; i < n; ++i) arr[i] = Long.parseLong(nextToken()); return arr; } private void pr(Object o) { pw.print(o); } private void prln(Object o) { pw.println(o); } private void prln() { pw.println(); } int ni() throws IOException { return Integer.parseInt(nextToken()); } long nl() throws IOException { return Long.parseLong(nextToken()); } double nd() throws IOException { return Double.parseDouble(nextToken()); } private String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(br.readLine()); } return tokenizer.nextToken(); } private BufferedReader br; private StringTokenizer tokenizer; private PrintWriter pw; private final boolean isFileIO = false; }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 7
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≀ n ≀ 3000) β€” the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≀ ai, bi, ci ≀ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
3cd0fa62a07c069edbf184729b14afb0
train_001.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.*; import static java.math.BigInteger.*; import static java.util.Arrays.*; import java.math.*; import java.util.*; public class Solution { public static void main(String[] args) throws Exception{ new Sol().sol(); } } class Sol { BufferedReader in; PrintWriter out; StringTokenizer st; String next() { while (st==null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (Exception e) {} } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } Long nextLong() { return Long.parseLong(next()); } int[] a = new int[3010]; int[] b = new int[3010]; int[] c = new int[3010]; int[][] dp = new int[3010][4]; void sol() throws Exception{ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new FileWriter("output.txt")); int n = nextInt(); for(int i = 0 ; i < n ; ++i) { a[i] = nextInt(); } for(int i = 0 ; i < n ; ++i) { b[i] = nextInt(); } for(int i = 0 ; i < n ; ++i) { c[i] = nextInt(); } if(n == 1) { System.out.println(a[0]); return; } dp[0][0] = a[0];dp[0][1] = a[0];dp[0][2] = b[0];dp[0][3] = b[0]; for(int i = 1 ; i < n - 1; ++i) { dp[i][0] = Math.max(dp[i-1][2], dp[i-1][3]) + a[i]; dp[i][1] = Math.max(dp[i-1][0], dp[i-1][1]) + b[i]; dp[i][2] = Math.max(dp[i-1][2], dp[i-1][3]) + b[i]; dp[i][3] = Math.max(dp[i-1][0], dp[i-1][1]) + c[i]; } if(n > 1) { dp[n-1][0] = Math.max(dp[n-2][2],dp[n-2][3]) + a[n-1]; dp[n-1][1] = Math.max(dp[n-2][0],dp[n-2][1]) + b[n-1]; dp[n-1][2] = Math.max(dp[n-2][2] , dp[n-2][3]) + a[n-1]; dp[n-1][3] = Math.max(dp[n-2][0] , dp[n-2][1]) + b[n-1]; } int ans = 0; for(int i = 0 ; i < 4; ++i) ans = Math.max(ans , dp[n-1][i]); System.out.println(ans); } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 7
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≀ n ≀ 3000) β€” the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≀ ai, bi, ci ≀ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
b3977e8d051dff0f703c90e2ca4294f6
train_001.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.*; import static java.math.BigInteger.*; import static java.util.Arrays.*; import java.math.*; import java.util.*; public class Solution { public static void main(String[] args) throws Exception{ new Sol().sol(); } } class Sol { BufferedReader in; PrintWriter out; StringTokenizer st; String next() { while (st==null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (Exception e) {} } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } Long nextLong() { return Long.parseLong(next()); } int[] a = new int[3010]; int[] b = new int[3010]; int[] c = new int[3010]; int[][] dp = new int[3010][4]; void sol() throws Exception{ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new FileWriter("output.txt")); int n = nextInt(); for(int i = 0 ; i < n ; ++i) { a[i] = nextInt(); } for(int i = 0 ; i < n ; ++i) { b[i] = nextInt(); } for(int i = 0 ; i < n ; ++i) { c[i] = nextInt(); } if(n == 1) { System.out.println(a[0]); return; } dp[0][0] = a[0];dp[0][1] = a[0];dp[0][2] = b[0];dp[0][3] = b[0]; for(int i = 1 ; i < n ; ++i) { dp[i][0] = Math.max(dp[i-1][2], dp[i-1][3]) + a[i]; dp[i][1] = Math.max(dp[i-1][0], dp[i-1][1]) + b[i]; dp[i][2] = Math.max(dp[i-1][2], dp[i-1][3]) + ((i == n-1) ? a[i] : b[i]); dp[i][3] = Math.max(dp[i-1][0], dp[i-1][1]) + ((i == n-1 )? b[i] : c[i]); } int ans = 0; for(int i = 0 ; i < 4; ++i) ans = Math.max(ans , dp[n-1][i]); System.out.println(ans); } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 7
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≀ n ≀ 3000) β€” the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≀ ai, bi, ci ≀ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
da7da18668432dfcdcf1f27ad50cf5f5
train_001.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
//package round208; 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 D3 { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = na(n); int[] b = na(n); int[] c = na(n); int cum = 0; for(int i = 1;i <= n;i++){ cum += b[i-1]; } if(n == 1){ out.println(a[0]); return; } int I = Integer.MIN_VALUE/2; int[][] dp = new int[n][2]; for(int i = 0;i < n;i++){ if(i == 0){ dp[i][0] = a[0]-b[0]; dp[i][1] = I; }else if(i < n-1){ { int max = I; for(int j = 0;j < i;j++){ max = Math.max(max, dp[j][0]); } dp[i][1] = max + c[i]-b[i]; } { int max = 0; for(int j = 0;j < i;j++){ max = Math.max(max, dp[j][1]); } dp[i][0] = max + a[i]-b[i]; } }else{ { int max = 0; for(int j = 0;j < i;j++){ max = Math.max(max, dp[j][1]); } dp[i][0] = max + a[i]-b[i]; } dp[i][1] = I; } } int gmax = I; for(int i = 0;i < n;i++){ gmax = Math.max(gmax, dp[i][0]); } out.println(gmax+cum); } 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 D3().run(); } private byte[] inbuf = new byte[1024]; private 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
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 7
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≀ n ≀ 3000) β€” the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≀ ai, bi, ci ≀ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
2f5052ad3745541fb5e86acc05192050
train_001.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class D { static int[] bothHung, oneHung, noHung; static int[][] dp; // pState 0 = hungry, 1=full public static int solve(int idx, int pState) { if (idx == bothHung.length - 1) { if (pState == 0) return bothHung[idx]; else return oneHung[idx]; } if (dp[idx][pState] != -1) return dp[idx][pState]; if (pState == 0) { return dp[idx][pState] = Math.max(oneHung[idx] + solve(idx + 1, 0), bothHung[idx] + solve(idx + 1, 1)); } else { return dp[idx][pState] = Math.max(oneHung[idx] + solve(idx + 1, 1), noHung[idx] + solve(idx + 1, 0)); } } public static void main(String[] args) throws Exception { int n = nextInt(); bothHung=new int[n]; oneHung=new int[n]; noHung=new int[n]; for (int i = 0; i < n; i++) { bothHung[i] = nextInt(); } for (int i = 0; i < n; i++) { oneHung[i] = nextInt(); } for (int i = 0; i < n; i++) { noHung[i] = nextInt(); } dp = new int[n - 1][2]; for (int i = 0; i < dp.length; i++) Arrays.fill(dp[i], -1); System.out.println(solve(0, 0)); } static BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); static StringTokenizer tokenizer = new StringTokenizer(""); static int nextInt() throws Exception { return Integer.parseInt(next()); } static double nextDouble() throws Exception { return Double.parseDouble(next()); } static String next() throws Exception { while (true) { if (tokenizer.hasMoreTokens()) { return tokenizer.nextToken(); } String s = br.readLine(); if (s == null) { return null; } tokenizer = new StringTokenizer(s); } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 7
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≀ n ≀ 3000) β€” the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≀ ai, bi, ci ≀ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
53cdcb8e302b9d113be487b4311fe27d
train_001.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class D358 { static int n; static int[][] v, memo; public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); v = new int[3][n]; for (int j = 0; j < 3; j++) for (int i = 0; i < n; i++) v[j][i] = sc.nextInt(); memo = new int[2][n]; for (int[] x : memo) Arrays.fill(x, -1); System.out.println(go(0, 0)); } // choice: go before the one on the right of pos or after static int go(int pos, int leftTaken) { if (pos == n) return 0; if (memo[leftTaken][pos] != -1) return memo[leftTaken][pos]; int adj = 0, ans = 0; if (leftTaken == 1) { // go before the one to the right adj = 1; ans = Math.max(ans, v[adj][pos] + go(pos + 1, 1)); // go after the one to the right if (pos < n - 1) { adj = 2; ans = Math.max(ans, v[adj][pos] + go(pos + 1, 0)); } } else { // go before the one to the right adj = 0; ans = Math.max(ans, v[adj][pos] + go(pos + 1, 1)); // go after the one to the right if (pos < n - 1) { adj = 1; ans = Math.max(ans, v[adj][pos] + go(pos + 1, 0)); } } return memo[leftTaken][pos] = ans; } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 7
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≀ n ≀ 3000) β€” the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≀ ai, bi, ci ≀ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
b7352cccc7734997204a18f43ce73f64
train_001.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.util.Scanner; import static java.lang.Math.max; /** * @author artyom */ public class DimaAndHares { private static int n; private static int[] a, b, c; private static int[][] dp; public static void main(String args[]) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); a = new int[n]; b = new int[n]; c = new int[n]; dp = new int[n][2]; fill(dp, -1); for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } for (int i = 0; i < n; i++) { b[i] = sc.nextInt(); } for (int i = 0; i < n; i++) { c[i] = sc.nextInt(); } System.out.println(findMaxJoy(0, 0)); } private static void fill(int[][] dp, int val) { for (int i = 0; i < n; i++) { dp[i] = new int[]{val, val}; } } private static int findMaxJoy(int pos, int prevFed) { int res = dp[pos][prevFed]; if (res != -1) { return res; } int nextPos = pos + 1; res = (nextPos == n) ? (prevFed == 1 ? b[pos] : a[pos]) : prevFed == 1 ? max(findMaxJoy(nextPos, 1) + b[pos], findMaxJoy(nextPos, 0) + c[pos]) : max(findMaxJoy(nextPos, 1) + a[pos], findMaxJoy(nextPos, 0) + b[pos]); return (dp[pos][prevFed] = res); } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 7
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≀ n ≀ 3000) β€” the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≀ ai, bi, ci ≀ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
0417c111840fbdbc93cc6f4e611cf77e
train_001.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.util.*; import java.io.*; public class Main implements Runnable { int[] a, b, c; int N; int[][] dp; public void solve() throws IOException { N = nextInt(); a = new int[N]; b = new int[N]; c = new int[N]; dp = new int[N][2]; for (int i = 0; i < N; i++) {//both not feeded a[i] = nextInt(); } for (int j = 0; j < N; j++) {//one feeded b[j] = nextInt(); } for (int k = 0; k < N; k++) {//both feeded c[k] = nextInt(); } for (int i = 0; i < N; i++) { Arrays.fill(dp[i], -1); } //System.out.println(solve(0, false)); dp[0][0] = b[0];//a[0];//prev not feed... dp[0][1] = a[0];//b[0];//prev feed... //dp[0][0] = b[0]; //dp[0][1] = a[0]; for (int i = 1; i < N; i++) { //curr Not feeded...(feed curr now ,feed curr after) dp[i][0] = Math.max(dp[i - 1][0] + b[i], dp[i - 1][1] + c[i]);//b,c //curr feeded dp[i][1] = Math.max(dp[i - 1][0] + a[i], dp[i - 1][1] + b[i]); } System.out.println(Math.max(0, dp[N - 1][1])); //+ " " + Math.min(dp[N - 1][0], dp[N - 1][1])); } public int solve(int pos, boolean prevFeeded) { if (pos == N - 1) { if (!prevFeeded) { return a[pos]; } else { return b[pos]; } } if (dp[pos][prevFeeded ? 1 : 0] != -1) { return dp[pos][prevFeeded ? 1 : 0]; } int res; if (prevFeeded) { int r1 = solve(pos + 1, true) + b[pos]; int r2 = solve(pos + 1, false) + c[pos]; res = Math.max(r1, r2); } else { int r1 = solve(pos + 1, true) + a[pos]; int r2 = solve(pos + 1, false) + b[pos]; res = Math.max(r1, r2); } return dp[pos][prevFeeded ? 1 : 0] = res; } void print(Object... obj) { for (Object o : obj) { System.out.println(o); } } void print(int[] a) { System.out.println(); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } void print(int[][] arr) { System.out.println(); for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } void print(boolean[][] arr) { System.out.println(); for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } //----------------------------------------------------------- public static void main(String[] args) { new Main().run(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); tok = null; solve(); in.close(); } catch (IOException e) { System.exit(0); } } public String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } 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()); } BufferedReader in; StringTokenizer tok; }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 7
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≀ n ≀ 3000) β€” the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≀ ai, bi, ci ≀ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
73c56720ce5d95f2494429f3dffa507e
train_001.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.util.*; import java.io.*; public class Main implements Runnable { int[] a, b, c; int N; int[][] dp; public void solve() throws IOException { N = nextInt(); a = new int[N]; b = new int[N]; c = new int[N]; dp = new int[N][2]; for (int i = 0; i < N; i++) { a[i] = nextInt(); } for (int j = 0; j < N; j++) { b[j] = nextInt(); } for (int k = 0; k < N; k++) { c[k] = nextInt(); } for (int i = 0; i < N; i++) { Arrays.fill(dp[i], -1); } System.out.println(solve(0, false)); } public int solve(int pos, boolean prevFeeded) { if (pos == N - 1) { if (!prevFeeded) { return a[pos]; } else { return b[pos]; } } if (dp[pos][prevFeeded ? 1 : 0] != -1) { return dp[pos][prevFeeded ? 1 : 0]; } int res = 0; if (prevFeeded) { int r1 = solve(pos + 1, true) + b[pos]; int r2 = solve(pos + 1, false) + c[pos]; res = Math.max(r1, r2); } else { int r1 = solve(pos + 1, true) + a[pos]; int r2 = solve(pos + 1, false) + b[pos]; res = Math.max(r1, r2); } return dp[pos][prevFeeded ? 1 : 0] = res; } void print(Object... obj) { for (Object o : obj) { System.out.println(o); } } void print(int[] a) { System.out.println(); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } void print(int[][] arr) { System.out.println(); for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } void print(boolean[][] arr) { System.out.println(); for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } //----------------------------------------------------------- public static void main(String[] args) { new Main().run(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); tok = null; solve(); in.close(); } catch (IOException e) { System.exit(0); } } public String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } 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()); } BufferedReader in; StringTokenizer tok; }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 7
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≀ n ≀ 3000) β€” the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≀ ai, bi, ci ≀ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
71cb8fbe6894435ce6ec61e00dd66c56
train_001.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.util.Scanner; public class HappyHares { /** * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m[][] = new int[n][3]; for(int i = 0; i < n; i++){ m[i][0] = in.nextInt(); } for(int i = 0; i < n; i++){ m[i][1] = in.nextInt(); } for(int i = 0; i < n; i++){ m[i][2] = in.nextInt(); } int tab[][] = new int[n][2]; tab[0][0] = m[0][0]; tab[0][1] = m[0][1]; for(int i = 1; i < n; i++){ tab[i][0] = Math.max(tab[i-1][1] + m[i][0], tab[i-1][0] + m[i][1]); tab[i][1] = Math.max(tab[i-1][1] + m[i][1], tab[i-1][0] + m[i][2]); } System.out.println(tab[n-1][0]); } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 7
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≀ n ≀ 3000) β€” the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≀ ai, bi, ci ≀ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
7e45fd409a3c6ce3153e5ea654ad41a6
train_001.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
/** * Created with IntelliJ IDEA. * User: flevix * Date: 25.10.13 * Time: 19:26 */ import java.io.*; import java.util.*; public class D { FastScanner in; PrintWriter out; public void solve() throws IOException { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); int[] b = new int[n]; for (int i = 0; i < n; i++) b[i] = in.nextInt(); int[] c = new int[n]; for (int i = 0; i < n; i++) c[i] = in.nextInt(); int[] d0 = new int[n]; int[] d1 = new int[n]; d0[n - 1] = a[n - 1]; d1[n - 1] = b[n - 1]; for (int i = n - 2; i >= 0; i--) { d0[i] = Math.max(a[i] + d1[i + 1], b[i] + d0[i + 1]); d1[i] = Math.max(b[i] + d1[i + 1], c[i] + d0[i + 1]); } out.print(d0[0]); } public void run() { try { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new D().run(); } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 7
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≀ n ≀ 3000) β€” the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≀ ai, bi, ci ≀ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
fb992f23ec09a1b2430291a653668f0d
train_001.jsonl
1561136700
This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle.After a long time thinking, Tolik's uncle hasn't any ideas on how to solve it. But, he doesn't want to tell Tolik about his inability to solve it, so he hasn't found anything better than asking you how to solve this task.In this task you are given a cell field $$$n \cdot m$$$, consisting of $$$n$$$ rows and $$$m$$$ columns, where point's coordinates $$$(x, y)$$$ mean it is situated in the $$$x$$$-th row and $$$y$$$-th column, considering numeration from one ($$$1 \leq x \leq n, 1 \leq y \leq m$$$). Initially, you stand in the cell $$$(1, 1)$$$. Every move you can jump from cell $$$(x, y)$$$, which you stand in, by any non-zero vector $$$(dx, dy)$$$, thus you will stand in the $$$(x+dx, y+dy)$$$ cell. Obviously, you can't leave the field, but also there is one more important conditionΒ β€” you're not allowed to use one vector twice. Your task is to visit each cell of the field exactly once (the initial cell is considered as already visited).Tolik's uncle is a very respectful person. Help him to solve this task!
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.InputMismatchException; 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 { static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; Input in = new Input(inputStream); PrintWriter out = new PrintWriter(outputStream); DTolikAndHisUncle solver = new DTolikAndHisUncle(); solver.solve(1, in, out); out.close(); } } public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1<<29); thread.start(); thread.join(); } static class DTolikAndHisUncle { public DTolikAndHisUncle() { } public void solve(int testNumber, Input in, PrintWriter pw) { int n = in.nextInt(), m = in.nextInt(); for(int i = 0; i<n >> 1; i++) { for(int j = 0; j<m; j++) { pw.println((i+1)+" "+(j+1)); pw.println((n-i)+" "+(m-j)); } } if((n&1)==1) { for(int j = 0; j<m >> 1; j++) { pw.println((n+1 >> 1)+" "+(j+1)); pw.println((n+1 >> 1)+" "+(m-j)); } if((m&1)==1) { pw.println((n+1 >> 1)+" "+(m+1 >> 1)); } } } } static class Input { BufferedReader br; StringTokenizer st; public Input(InputStream is) { br = new BufferedReader(new InputStreamReader(is), 1<<16); st = null; } public boolean hasNext() { try { while(st==null||!st.hasMoreTokens()) { String s = br.readLine(); if(s==null) { return false; } st = new StringTokenizer(s); } return true; }catch(Exception e) { return false; } } public String next() { if(!hasNext()) { throw new InputMismatchException(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2 3", "1 1"]
1 second
["1 1\n1 3\n1 2\n2 2\n2 3\n2 1", "1 1"]
NoteThe vectors from the first example in the order of making jumps are $$$(0, 2), (0, -1), (1, 0), (0, 1), (0, -2)$$$.
Java 11
standard input
[ "constructive algorithms" ]
cc67015b9615f150aa06f7b8ed7e3152
The first and only line contains two positive integers $$$n, m$$$ ($$$1 \leq n \cdot m \leq 10^{6}$$$)Β β€” the number of rows and columns of the field respectively.
1,800
Print "-1" (without quotes) if it is impossible to visit every cell exactly once. Else print $$$n \cdot m$$$ pairs of integers, $$$i$$$-th from them should contain two integers $$$x_i, y_i$$$ ($$$1 \leq x_i \leq n, 1 \leq y_i \leq m$$$)Β β€” cells of the field in order of visiting, so that all of them are distinct and vectors of jumps between them are distinct too. Notice that the first cell should have $$$(1, 1)$$$ coordinates, according to the statement.
standard output
PASSED
ac96e6a32b956df7b9e9960636a0a142
train_001.jsonl
1561136700
This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle.After a long time thinking, Tolik's uncle hasn't any ideas on how to solve it. But, he doesn't want to tell Tolik about his inability to solve it, so he hasn't found anything better than asking you how to solve this task.In this task you are given a cell field $$$n \cdot m$$$, consisting of $$$n$$$ rows and $$$m$$$ columns, where point's coordinates $$$(x, y)$$$ mean it is situated in the $$$x$$$-th row and $$$y$$$-th column, considering numeration from one ($$$1 \leq x \leq n, 1 \leq y \leq m$$$). Initially, you stand in the cell $$$(1, 1)$$$. Every move you can jump from cell $$$(x, y)$$$, which you stand in, by any non-zero vector $$$(dx, dy)$$$, thus you will stand in the $$$(x+dx, y+dy)$$$ cell. Obviously, you can't leave the field, but also there is one more important conditionΒ β€” you're not allowed to use one vector twice. Your task is to visit each cell of the field exactly once (the initial cell is considered as already visited).Tolik's uncle is a very respectful person. Help him to solve this task!
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class Mamo { static long mod=1000000007; static Reader in=new Reader(); static List<Integer >G[]; static long a[],p[],xp[],xv[]; static StringBuilder Sd=new StringBuilder(),Sl=new StringBuilder(); public static void main(String [] args) { //Dir by MohammedElkady int n=in.nextInt(),m=in.nextInt(); for(int i=0;i<=n;i++) { if(n>i*2) for(int u=1,j=m;u<=m;u++,j--) { if(n-i-i-1==0&&j<u)break; out.append((i+1)+" "+(u)+"\n"); if(n-i-i-1==0&&j<=u)break; out.append((n-i)+" "+(j)+"\n"); } } out.close(); } static long ans=0L; static boolean v[]; static ArrayList<Integer>res; static Queue <Integer> pop; static Stack <Integer>rem; public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static long gcd(long g,long x){if(x<1)return g;else return gcd(x,g%x);} static class Reader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];} public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;} public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();} public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;} public int nextInt(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;} public double d() throws IOException {return Double.parseDouble(s()) ;} public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = nextInt();}return ret;} } } class stree{ public stree(int n,long a[]) { this.a=a; seg=new long[n*4]; lazy=new long[n*4]; build(1,0,n-1); } long seg[], a[],lazy[]; void check(int p,int s,int e) { if(lazy[p]!=0) { seg[p] += lazy[p]; if(s!=e) { lazy[2*p] += lazy[p]; lazy[2*p+1] += lazy[p]; } lazy[p] = 0; } } void build(int p,int s,int e) { check(p,s,e); if(s==e) { seg[p] = a[s]; return; } build(2*p,s,(s+e)/2); build(2*p+1,(s+e)/2+1,e); seg[p] = Math.max(seg[2*p], seg[2*p+1]); } void update(int p,int s,int e,int i,int v) { check(p,s,e); if(s==e) { seg[p] = v; return; } if(i<=(s+e)/2) update(2*p,s,(s+e)/2,i,v); else update(2*p+1,(s+e)/2+1,e,i,v); seg[p] = Math.max(seg[2*p],seg[2*p+1]); } void update(int p,int s,int e,int a,int b,int v) { check(p,s,e); if(s>=a && e<=b) { seg[p] += v; if(s!=e) { lazy[2*p] += v; lazy[2*p+1] += v; } return; } if(s>b || e<a) return; update(2*p,s,(s+e)/2,a,b,v); update(2*p+1,(s+e)/2+1,e,a,b,v); seg[p] = Math.max(seg[2*p],seg[2*p+1]); } long get(int p,int s,int e,int a,int b) { if(s>=a && e<=b) return seg[p]; if(s>b || e<a) return Long.MIN_VALUE; return Math.max(get(2*p,s,(s+e)/2,a,b), get(2*p+1,(s+e)/2+1,e,a,b)); } } class node implements Comparable<node>{ int a, b; node(int tt,int ll){ a=tt;b=ll; } @Override public int compareTo(node o) { return b-o.b; } } 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; } } class Sorting{ public static long[] bucketSort(long[] array, int bucketCount) { if (bucketCount <= 0) throw new IllegalArgumentException("Invalid bucket count"); if (array.length <= 1) return array; //trivially sorted long high = array[0]; long low = array[0]; for (int i = 1; i < array.length; i++) { //find the range of input elements if (array[i] > high) high = array[i]; if (array[i] < low) low = array[i]; } double interval = ((double)(high - low + 1))/bucketCount; //range of one bucket ArrayList<Long> buckets[] = new ArrayList[bucketCount]; for (int i = 0; i < bucketCount; i++) { //initialize buckets buckets[i] = new ArrayList(); } for (int i = 0; i < array.length; i++) { //partition the input array buckets[(int)((array[i] - low)/interval)].add(array[i]); } int pointer = 0; for (int i = 0; i < buckets.length; i++) { Collections.sort(buckets[i]); //mergeSort for (int j = 0; j < buckets[i].size(); j++) { //merge the buckets array[pointer] = buckets[i].get(j); pointer++; } } return array; } }
Java
["2 3", "1 1"]
1 second
["1 1\n1 3\n1 2\n2 2\n2 3\n2 1", "1 1"]
NoteThe vectors from the first example in the order of making jumps are $$$(0, 2), (0, -1), (1, 0), (0, 1), (0, -2)$$$.
Java 11
standard input
[ "constructive algorithms" ]
cc67015b9615f150aa06f7b8ed7e3152
The first and only line contains two positive integers $$$n, m$$$ ($$$1 \leq n \cdot m \leq 10^{6}$$$)Β β€” the number of rows and columns of the field respectively.
1,800
Print "-1" (without quotes) if it is impossible to visit every cell exactly once. Else print $$$n \cdot m$$$ pairs of integers, $$$i$$$-th from them should contain two integers $$$x_i, y_i$$$ ($$$1 \leq x_i \leq n, 1 \leq y_i \leq m$$$)Β β€” cells of the field in order of visiting, so that all of them are distinct and vectors of jumps between them are distinct too. Notice that the first cell should have $$$(1, 1)$$$ coordinates, according to the statement.
standard output
PASSED
2a6975ba8846300c9853d59059313c25
train_001.jsonl
1452789300
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
256 megabytes
import java.util.*; import java.io.*; public class marcose { public static void main(String [] args)throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); long l = Long.parseLong(st.nextToken()); long r = Long.parseLong(st.nextToken()); long k = Long.parseLong(st.nextToken()); StringBuilder sb = new StringBuilder(); long temp = 1; boolean flag = false; while(temp <= r){ if(temp >= l){ flag = true; sb.append(temp + " "); } if(r/temp < k)break; temp *= k; } if(!flag)System.out.print("-1"); else System.out.print(sb); } }
Java
["1 10 2", "2 4 5"]
2 seconds
["1 2 4 8", "-1"]
NoteNote to the first sample: numbers 20 = 1, 21 = 2, 22 = 4, 23 = 8 lie within the specified range. The number 24 = 16 is greater then 10, thus it shouldn't be printed.
Java 8
standard input
[ "implementation", "brute force" ]
8fcec28fb4d165eb58f829c03e6b31d1
The first line of the input contains three space-separated integers l, r and k (1 ≀ l ≀ r ≀ 1018, 2 ≀ k ≀ 109).
1,500
Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).
standard output
PASSED
5d9129bbbe1673d4bc3099953ebf2c3e
train_001.jsonl
1452789300
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
256 megabytes
import java.util.Scanner; import java.math.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long r,k,l; r = sc.nextLong(); k =sc.nextLong(); l = sc.nextLong(); int p = 0; boolean T = false; p = (int) (Math.log10(k)/Math.log10(l)); for(int i=0;i<=p;i++){ long res = 1; for(int j=1;j<=i;j++){ res *= l; } if(res < r || res > k) continue; else{ T = true; System.out.print(res); if(i<p){ System.out.print(" "); } } } if(T) System.out.println(); else if(!T){ System.out.println("-1"); } } }
Java
["1 10 2", "2 4 5"]
2 seconds
["1 2 4 8", "-1"]
NoteNote to the first sample: numbers 20 = 1, 21 = 2, 22 = 4, 23 = 8 lie within the specified range. The number 24 = 16 is greater then 10, thus it shouldn't be printed.
Java 8
standard input
[ "implementation", "brute force" ]
8fcec28fb4d165eb58f829c03e6b31d1
The first line of the input contains three space-separated integers l, r and k (1 ≀ l ≀ r ≀ 1018, 2 ≀ k ≀ 109).
1,500
Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).
standard output
PASSED
baf3e18264fc334b32134e555a5c8268
train_001.jsonl
1452789300
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Scanner; public class A { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); Scanner s = new Scanner(System.in); long l = s.nextLong(), r = s.nextLong(), k = s.nextLong(); ArrayList<BigInteger> pows = new ArrayList<>(); pows.add(BigInteger.ONE); for(BigInteger i = new BigInteger(k+""); i.compareTo(BigInteger.valueOf(r)) <= 0 && i.compareTo(BigInteger.valueOf(1000000000000000000l)) <= 0;) { // System.out.println(i); if(i.compareTo(BigInteger.ZERO) <= 0) break; pows.add(i); i = i.multiply(BigInteger.valueOf(k)); } // System.out.println(pows.toString()); boolean print = false; for(int i = 0; i < pows.size(); i++) { if(i != pows.size()-1 && pows.get(i).compareTo(BigInteger.valueOf(l)) >= 0) { out.print(pows.get(i)+" "); print = true; } else if(i == pows.size()-1 && pows.get(i).compareTo(BigInteger.valueOf(l)) >= 0) { out.println(pows.get(i)); print = true; } } if(!print) System.out.println(-1); out.close(); } }
Java
["1 10 2", "2 4 5"]
2 seconds
["1 2 4 8", "-1"]
NoteNote to the first sample: numbers 20 = 1, 21 = 2, 22 = 4, 23 = 8 lie within the specified range. The number 24 = 16 is greater then 10, thus it shouldn't be printed.
Java 8
standard input
[ "implementation", "brute force" ]
8fcec28fb4d165eb58f829c03e6b31d1
The first line of the input contains three space-separated integers l, r and k (1 ≀ l ≀ r ≀ 1018, 2 ≀ k ≀ 109).
1,500
Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).
standard output
PASSED
949b202834891af90a8df7e6b59887f2
train_001.jsonl
1452789300
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Locale; public class Main { public static void main(String[] args) throws IOException { Locale.setDefault(Locale.US); BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter saida = new BufferedWriter(new OutputStreamWriter(System.out)); String linha = entrada.readLine(); String vet[] = linha.split("\\s+"); long ini = Long.parseLong(vet[0]); long fim = Long.parseLong(vet[1]); long pot = Long.parseLong(vet[2]); long val = 1; //ver se entra no primeiro //se entrar vai pot * pot //verifica se vai estourar pot < MAX / potIni int cont = 0; while (val <= 1E18 / pot && val < ini) { val *= pot; } while (val <= 1E18 / pot && val <= fim) { saida.write(val + " "); cont++; val *= pot; } if (val <= fim && val >= ini) { saida.write(val + ""); cont++; } if (cont == 0) { saida.write("-1"); } saida.write("\n"); saida.flush(); } }
Java
["1 10 2", "2 4 5"]
2 seconds
["1 2 4 8", "-1"]
NoteNote to the first sample: numbers 20 = 1, 21 = 2, 22 = 4, 23 = 8 lie within the specified range. The number 24 = 16 is greater then 10, thus it shouldn't be printed.
Java 8
standard input
[ "implementation", "brute force" ]
8fcec28fb4d165eb58f829c03e6b31d1
The first line of the input contains three space-separated integers l, r and k (1 ≀ l ≀ r ≀ 1018, 2 ≀ k ≀ 109).
1,500
Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).
standard output
PASSED
e858436c42133d5776eaf3749d0be2f8
train_001.jsonl
1452789300
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { public static void main (String[] args) throws java.lang.Exception { Scanner sc = new Scanner(System.in); long back = -1, inf = sc.nextLong(), sup = sc.nextLong(), inc= sc.nextLong(), lim, dat, start, c; String res = "", si = "", sinc = ""; c = 0; dat = (long)Math.pow(inc, c); while(dat < inf){ c++; if(inc >= 688813) dat = mult(inc, c); else dat = (long)Math.pow(inc, c); } if( dat >= inf){ start = dat; } else { start = (long)Math.pow(inc, c+1); } if(start == 1){ res = "1 "; start = (long)Math.pow(inc, c+1); } sinc = ""+inc; for(long i = start ; i <= sup; i*=inc){ if(i < 0 || back > i) break; res = res + i + " "; si = ""+i; if((si.length()+sinc.length()-1) > 18 && i*inc != sup){ break; } back = i; } if(res.length() != 0) System.out.println(res); else System.out.println("-1"); } private static long mult(long n, long cant){ long res = 1; while(cant != 0){ res = res*n; cant--; } return res; } }
Java
["1 10 2", "2 4 5"]
2 seconds
["1 2 4 8", "-1"]
NoteNote to the first sample: numbers 20 = 1, 21 = 2, 22 = 4, 23 = 8 lie within the specified range. The number 24 = 16 is greater then 10, thus it shouldn't be printed.
Java 8
standard input
[ "implementation", "brute force" ]
8fcec28fb4d165eb58f829c03e6b31d1
The first line of the input contains three space-separated integers l, r and k (1 ≀ l ≀ r ≀ 1018, 2 ≀ k ≀ 109).
1,500
Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).
standard output
PASSED
b5c9ebec8427af57f13d3a57ccaf98ec
train_001.jsonl
1452789300
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
256 megabytes
/* * Code Author: Jayesh Udhani * Dhirubhai Ambani Institute of Information and Communication Technology (DA-IICT ,Gandhinagar) * 2nd Year ICT BTECH student */ import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { 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---------- long l,r,k; int i=0; boolean t=false; l=in.nextLong(); r=in.nextLong(); k=in.nextLong(); BigInteger b1=new BigInteger(Long.toString(l)); BigInteger b2=new BigInteger(Long.toString(r)); BigInteger b3=new BigInteger(Long.toString(k)); for(i=0;;i++) { if(b3.pow(i).compareTo(b1)>=0 && b3.pow(i).compareTo(b2)<=0) { t=true; System.out.print(b3.pow(i)+" "); } else if(b3.pow(i).compareTo(b2)==1) break; } if(!t) System.out.println("-1"); out.close(); //---------------The Endβ€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€”β€” } 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
["1 10 2", "2 4 5"]
2 seconds
["1 2 4 8", "-1"]
NoteNote to the first sample: numbers 20 = 1, 21 = 2, 22 = 4, 23 = 8 lie within the specified range. The number 24 = 16 is greater then 10, thus it shouldn't be printed.
Java 8
standard input
[ "implementation", "brute force" ]
8fcec28fb4d165eb58f829c03e6b31d1
The first line of the input contains three space-separated integers l, r and k (1 ≀ l ≀ r ≀ 1018, 2 ≀ k ≀ 109).
1,500
Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).
standard output
PASSED
6a559cecb244e3cab85f01bae950dc0f
train_001.jsonl
1452789300
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Div2_339_A { public static void main(String[] args) throws IOException { BufferedInputStream bis = new BufferedInputStream(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(bis)); String line; while((line = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(line); BigInteger L = new BigInteger(st.nextToken()); BigInteger R = new BigInteger(st.nextToken()); BigInteger K = new BigInteger(st.nextToken()); if(K.compareTo(BigInteger.ONE) == 0) { System.out.println((L.compareTo(K) <= 0 && R.compareTo(K) >= 0)?"1":"-1"); } else { BigInteger curr = new BigInteger("1"); boolean hasAns = false; while(curr.compareTo(R) <= 0) { if(curr.compareTo(L) >= 0) { System.out.print(curr+" "); hasAns = true; } curr = curr.multiply(K); } if(!hasAns) System.out.println(-1); else System.out.println(); } } } }
Java
["1 10 2", "2 4 5"]
2 seconds
["1 2 4 8", "-1"]
NoteNote to the first sample: numbers 20 = 1, 21 = 2, 22 = 4, 23 = 8 lie within the specified range. The number 24 = 16 is greater then 10, thus it shouldn't be printed.
Java 8
standard input
[ "implementation", "brute force" ]
8fcec28fb4d165eb58f829c03e6b31d1
The first line of the input contains three space-separated integers l, r and k (1 ≀ l ≀ r ≀ 1018, 2 ≀ k ≀ 109).
1,500
Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).
standard output
PASSED
0dcfa82acb325ae1adf5f6eb05d297a7
train_001.jsonl
1452789300
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
256 megabytes
import java.math.*; import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) { BigInteger r,bi1, bi2, bi3,bb; int n=0; Scanner in = new Scanner(System.in); bi1 = new BigInteger(in.next()); bi2 = new BigInteger(in.next()); bi3 = new BigInteger(in.next()); bb= new BigInteger("1"); int res = bi2.compareTo(bi1); if(res==0){ int i=0; while(bi2.compareTo(bb)==1||bi2.compareTo(bb)==0){ bb = bi3.pow(i); if(bi2.compareTo(bb)==0){ System.out.print(bb+" "); n=1; }i++; } if(n==0){ System.out.print("-1"); } System.out.println(); } else if(res==1){ int i=0; if(bi1.compareTo(bb)==0){ System.out.print(1+" "); n=1; } if(bi1.compareTo(bi3)==0) { System.out.print(bi3+" "); n=1; } while(bi1.compareTo(bb)==1||bi1.compareTo(bb)==0){ bb = bi3.pow(i); i++; } while(bi2.compareTo(bb)==1||bi2.compareTo(bb)==0){ System.out.print(bb+" "); bb = bi3.pow(i); i++; n=1; } if(n==0){ System.out.print("-1"); } System.out.println(); } else{ int i=0; if(bi1.compareTo(bb)==0){ System.out.print(1+" "); n=1; } if(bi1.compareTo(bi3)==0) { System.out.print(bi3+" "); n=1; } while(bi1.compareTo(bb)==1||bi1.compareTo(bb)==0){ bb = bi3.pow(i); i++; } while(bi2.compareTo(bb)==1||bi2.compareTo(bb)==0){ System.out.print(bb+" "); bb = bi3.pow(i); i++; n=1; } if(n==0){ System.out.print("-1"); } System.out.println(); } } }
Java
["1 10 2", "2 4 5"]
2 seconds
["1 2 4 8", "-1"]
NoteNote to the first sample: numbers 20 = 1, 21 = 2, 22 = 4, 23 = 8 lie within the specified range. The number 24 = 16 is greater then 10, thus it shouldn't be printed.
Java 8
standard input
[ "implementation", "brute force" ]
8fcec28fb4d165eb58f829c03e6b31d1
The first line of the input contains three space-separated integers l, r and k (1 ≀ l ≀ r ≀ 1018, 2 ≀ k ≀ 109).
1,500
Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).
standard output
PASSED
c18af7864f12912c86dfee1643936ad8
train_001.jsonl
1452789300
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
256 megabytes
//package DIV2; import java.io.*; import java.math.*; import java.util.*; public class link_cut_tree { public static void main(String[] args){ Scanner sc=new Scanner(System.in); BigInteger l=sc.nextBigInteger(); BigInteger r=sc.nextBigInteger(); BigInteger k=sc.nextBigInteger(); int fnd=0; int i=0; //i=0; BigInteger num=k.pow(i); int temp=num.compareTo(l); int temp2=num.compareTo(r); //System.out.println(num+" "+temp+" "+temp2); while(temp2<=0) { if(temp>=0 && temp2<=0) { fnd=1; System.out.println(num); } else if(temp2>0) { break; } i++; num=k.pow(i); temp=num.compareTo(l); temp2=num.compareTo(r); } if(fnd==0) { System.out.println("-1"); } } }
Java
["1 10 2", "2 4 5"]
2 seconds
["1 2 4 8", "-1"]
NoteNote to the first sample: numbers 20 = 1, 21 = 2, 22 = 4, 23 = 8 lie within the specified range. The number 24 = 16 is greater then 10, thus it shouldn't be printed.
Java 8
standard input
[ "implementation", "brute force" ]
8fcec28fb4d165eb58f829c03e6b31d1
The first line of the input contains three space-separated integers l, r and k (1 ≀ l ≀ r ≀ 1018, 2 ≀ k ≀ 109).
1,500
Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).
standard output
PASSED
9d60fd02186d5bca76fde57c736dca8f
train_001.jsonl
1452789300
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
256 megabytes
import java.math.BigInteger; import java.util.Scanner; public class TreeCut { public static int numCase = 0; public static Scanner in; private static void solveProblem() { long l = in.nextLong(); long r = in.nextLong(); int k = in.nextInt(); boolean found = false; BigInteger i = BigInteger.ONE; BigInteger right = new BigInteger(String.valueOf(r)); BigInteger left = new BigInteger(String.valueOf(l)); while (i.compareTo(right) <= 0) { if (i.compareTo(left) >= 0) { if (!found) { found = true; } else { System.out.print(" "); } System.out.print(i); } i = i.multiply(new BigInteger(String.valueOf(k))); } if (!found) { System.out.print(-1); } } public static void main(final String[] args) { in = new Scanner(System.in); solveProblem(); } }
Java
["1 10 2", "2 4 5"]
2 seconds
["1 2 4 8", "-1"]
NoteNote to the first sample: numbers 20 = 1, 21 = 2, 22 = 4, 23 = 8 lie within the specified range. The number 24 = 16 is greater then 10, thus it shouldn't be printed.
Java 8
standard input
[ "implementation", "brute force" ]
8fcec28fb4d165eb58f829c03e6b31d1
The first line of the input contains three space-separated integers l, r and k (1 ≀ l ≀ r ≀ 1018, 2 ≀ k ≀ 109).
1,500
Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).
standard output
PASSED
253025aa22e34c648a8bb17aeb9324e8
train_001.jsonl
1452789300
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
256 megabytes
import java.math.BigInteger; import java.util.Scanner; public class LinkTrees { public static void main(String[] args) { Scanner scan = new Scanner(System.in); BigInteger l = scan.nextBigInteger(); BigInteger r = scan.nextBigInteger(); BigInteger k = scan.nextBigInteger(); boolean check = false; BigInteger temp = BigInteger.ONE; if (l.compareTo(BigInteger.ONE) == 0) { System.out.print("1 "); check = true; } while (temp.compareTo(BigInteger.ZERO) > 0) { temp = temp.multiply(k); if (temp.compareTo(l) >= 0 && temp.compareTo(r) <= 0) { check = true; System.out.print(temp + " "); } if (temp.compareTo(r) > 0) break; } System.out.print(check ? "" : "-1"); scan.close(); } }
Java
["1 10 2", "2 4 5"]
2 seconds
["1 2 4 8", "-1"]
NoteNote to the first sample: numbers 20 = 1, 21 = 2, 22 = 4, 23 = 8 lie within the specified range. The number 24 = 16 is greater then 10, thus it shouldn't be printed.
Java 8
standard input
[ "implementation", "brute force" ]
8fcec28fb4d165eb58f829c03e6b31d1
The first line of the input contains three space-separated integers l, r and k (1 ≀ l ≀ r ≀ 1018, 2 ≀ k ≀ 109).
1,500
Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).
standard output
PASSED
56eec1ae0249d215d69a9d658db55b84
train_001.jsonl
1452789300
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
256 megabytes
import java.math.BigInteger; import java.util.Scanner; public class LinkcutTree { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); BigInteger l = input.nextBigInteger(); BigInteger r = input.nextBigInteger(); BigInteger k = input.nextBigInteger(); BigInteger t = BigInteger.valueOf(1); while(t.compareTo(l)<0)t = t.multiply(k); if(t.compareTo(r)>0){ System.out.println(-1); return ; } while(t.compareTo(r)<=0){ System.out.println(t + " "); t = t.multiply(k); } } }
Java
["1 10 2", "2 4 5"]
2 seconds
["1 2 4 8", "-1"]
NoteNote to the first sample: numbers 20 = 1, 21 = 2, 22 = 4, 23 = 8 lie within the specified range. The number 24 = 16 is greater then 10, thus it shouldn't be printed.
Java 8
standard input
[ "implementation", "brute force" ]
8fcec28fb4d165eb58f829c03e6b31d1
The first line of the input contains three space-separated integers l, r and k (1 ≀ l ≀ r ≀ 1018, 2 ≀ k ≀ 109).
1,500
Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).
standard output
PASSED
911af90aa3fc925cc6adefb4a77dba9e
train_001.jsonl
1452789300
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
256 megabytes
import java.util.Scanner; public class A614 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long l = sc.nextLong(); long r = sc.nextLong(); int k = sc.nextInt(); long n = 1; long last = 0; while (n < l && n>last) { last = n; n *= k; if (n/k != last) { System.out.println("-1"); return; } } if (n > r) { System.out.println("-1"); } else { last = 0; while (n <= r && n>last) { System.out.print(n+" "); last = n; n *= k; if (n/k != last) { return; } } } } }
Java
["1 10 2", "2 4 5"]
2 seconds
["1 2 4 8", "-1"]
NoteNote to the first sample: numbers 20 = 1, 21 = 2, 22 = 4, 23 = 8 lie within the specified range. The number 24 = 16 is greater then 10, thus it shouldn't be printed.
Java 8
standard input
[ "implementation", "brute force" ]
8fcec28fb4d165eb58f829c03e6b31d1
The first line of the input contains three space-separated integers l, r and k (1 ≀ l ≀ r ≀ 1018, 2 ≀ k ≀ 109).
1,500
Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).
standard output
PASSED
6af4129d5d5c763e77146098b128da89
train_001.jsonl
1452789300
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.StringTokenizer; public class LinkCutTree { public static void main(String[] args) throws IOException { MyScanner sc = new MyScanner(System.in); PrintWriter pw = new PrintWriter(System.out); long l = sc.nextLong(); long r = sc.nextLong(); long k = sc.nextLong(); boolean f = false; //int c = 0; if (k == 1){ if (k < r) { pw.println(k); f = true; // c++; } else { pw.println(-1); f = true; //c++; } } BigInteger ll = BigInteger.valueOf(l); BigInteger rr = BigInteger.valueOf(r); BigInteger kk = BigInteger.valueOf(k); for(int i = 0;;i++){ BigInteger ans = kk.pow(i); if(ans.compareTo(rr) >= 1) break; if(ans.compareTo(ll) >= 0){ f = true; pw.println(ans); } } if(!f) pw.println(-1); pw.close(); } static class MyScanner { StringTokenizer st; BufferedReader br; public MyScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["1 10 2", "2 4 5"]
2 seconds
["1 2 4 8", "-1"]
NoteNote to the first sample: numbers 20 = 1, 21 = 2, 22 = 4, 23 = 8 lie within the specified range. The number 24 = 16 is greater then 10, thus it shouldn't be printed.
Java 8
standard input
[ "implementation", "brute force" ]
8fcec28fb4d165eb58f829c03e6b31d1
The first line of the input contains three space-separated integers l, r and k (1 ≀ l ≀ r ≀ 1018, 2 ≀ k ≀ 109).
1,500
Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).
standard output
PASSED
5c842e9f840a46a7109013d8dd659d44
train_001.jsonl
1456683000
A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of a thimbles per day after the k days are complete.Initially, no orders are pending. The factory receives updates of the form di, ai, indicating that ai new orders have been placed for the di-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes.As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day pi. Help the owner answer his questions.
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.StringTokenizer; /** * Created by Anna on 01.04.2016. */ public class Template { StringTokenizer st; BufferedReader in; PrintWriter out; public static void main(String[] args) throws IOException { Template task = new Template(); task.open(); task.solve(); task.close(); } // // ArrayList<Integer> primes = new ArrayList<Integer>(); // int[] minPrimeDivisor; // // int getPrimes(int n) { // int cnt = 0; // minPrimeDivisor = new int[n + 1]; // for (int i = 2; i <= n; i++) { // if (minPrimeDivisor[i] == 0) { // minPrimeDivisor[i] = i; // primes.add(i); // cnt++; // } // // for (Integer prime : primes) { // if (prime <= minPrimeDivisor[i] && (1L * prime * i <= n)) { // minPrimeDivisor[prime * i] = prime; // cnt++; // } else break; // } // } // return cnt; // } // // int simpleGCD(int a, int b) { // if (b == 0) return a; // return simpleGCD(b, a % b); // } // // class Pair { // int x, y, value; // // Pair(int x, int y, int value) { // this.x = x; // this.y = y; // this.value = value; // } // } // // Pair gcd(int a, int b) { // if (a == 0) return new Pair(0, 1, b); // Pair res = gcd(b % a, a); // int y = res.x; // int x = res.y - (b / a) * res.x; // res.x = x; // res.y = y; // return res; // } class Decomposition { int[] array; long[] sums; int cntSums; int sizeOfSum; int maxValue; Decomposition(int[] a, int n, int maxValue) { sizeOfSum = (int) Math.sqrt(n); cntSums = n / sizeOfSum + (n % sizeOfSum == 0 ? 0 : 1); array = a.clone(); this.maxValue = maxValue; sums = new long[cntSums]; for (int i = 0; i < cntSums; i++) { for (int j = i * sizeOfSum; j < n && j < (i + 1) * sizeOfSum; j++) { if (array[j] > maxValue) array[j] = maxValue; sums[i] += array[j]; } } } long getSum(int queryLeft, int queryRight) { if (queryLeft > queryRight) return 0; int fromSum = queryLeft / sizeOfSum; int toSum = queryRight / sizeOfSum; long answer = 0; if (fromSum == toSum) { for (int i = queryLeft; i <= queryRight; i++) { answer += array[i]; } return answer; } for (int i = fromSum + 1; i < toSum; i++) { answer += sums[i]; } for (int i = queryLeft; i < (fromSum + 1) * sizeOfSum; i++) { answer += array[i]; } for (int i = toSum * sizeOfSum; i <= queryRight; i++) { answer += array[i]; } return answer; } void putValue(int pos, int value) { int posSum = pos / sizeOfSum; if (value > maxValue) value = maxValue; sums[posSum] -= array[pos]; array[pos] = value; sums[posSum] += value; } } private void solve() throws IOException { int n = nextInt(); int k = nextInt(); int a = nextInt(); int b = nextInt(); int q = nextInt(); int[] arr = new int[n]; Decomposition decompositionA = new Decomposition(arr, n, a); Decomposition decompositionB = new Decomposition(arr, n, b); for (int i = 0; i < q; i++) { int type = nextInt(); if (type == 1) { int day = nextInt() - 1; int value = nextInt(); arr[day] += value; decompositionA.putValue(day, arr[day]); decompositionB.putValue(day, arr[day]); } else { int fromRepair = nextInt() - 1; int toRepair = fromRepair + k - 1; long answ = decompositionB.getSum(0, fromRepair - 1) + decompositionA.getSum(toRepair + 1, n - 1); out.println(answ); } } } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String str = in.readLine(); if (str == null) return null; st = new StringTokenizer(str); } return st.nextToken(); } private void close() { out.close(); } private void open() { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } }
Java
["5 2 2 1 8\n1 1 2\n1 5 3\n1 2 1\n2 2\n1 4 2\n1 3 2\n2 1\n2 3", "5 4 10 1 6\n1 1 5\n1 5 5\n1 3 2\n1 5 2\n2 1\n2 2"]
4 seconds
["3\n6\n4", "7\n1"]
NoteConsider the first sample.We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days.For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled.For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders.
Java 8
standard input
[ "data structures" ]
d256f8cf105b08624eee21dd76a6ad3d
The first line contains five integers n, k, a, b, and q (1 ≀ k ≀ n ≀ 200 000, 1 ≀ b &lt; a ≀ 10 000, 1 ≀ q ≀ 200 000)Β β€” the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively. The next q lines contain the descriptions of the queries. Each query is of one of the following two forms: 1 di ai (1 ≀ di ≀ n, 1 ≀ ai ≀ 10 000), representing an update of ai orders on day di, or 2 pi (1 ≀ pi ≀ n - k + 1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day pi? It's guaranteed that the input will contain at least one query of the second type.
1,700
For each query of the second type, print a line containing a single integer β€” the maximum number of orders that the factory can fill over all n days.
standard output
PASSED
3ddefd2c284b0b1419a312c35af43986
train_001.jsonl
1456683000
A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but will be restored to its full production of a thimbles per day after the k days are complete.Initially, no orders are pending. The factory receives updates of the form di, ai, indicating that ai new orders have been placed for the di-th day. Each order requires a single thimble to be produced on precisely the specified day. The factory may opt to fill as many or as few of the orders in a single batch as it likes.As orders come in, the factory owner would like to know the maximum number of orders he will be able to fill if he starts repairs on a given day pi. Help the owner answer his questions.
256 megabytes
/** * Created by Anna on 14.03.2016. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class TaskD { StringTokenizer st; PrintWriter out; BufferedReader in; public static void main(String[] args) throws IOException { TaskD solver = new TaskD(); solver.open(); solver.solve(); solver.close(); } class Decomposition { long[] array; long[] sums; int n; int cntParts; int partCapacity; long max; public Decomposition(int n, long max) { array = new long[n]; this.n = n; this.partCapacity = (int) Math.sqrt(n); this.cntParts = this.n / this.partCapacity + (this.n % this.partCapacity == 0 ? 0 : 1); this.max = max; this.sums = new long[this.cntParts]; } public void updateElement(long value, int ind) { if (value > this.max) value = this.max; int partNumber = ind / this.partCapacity; long old = this.array[ind]; this.array[ind] = value; this.sums[partNumber] -= old; this.sums[partNumber] += value; } public long getSum(int from, int to) { if (from > to) return 0L; int fromPart = from / this.partCapacity; int toPart = to / this.partCapacity; long result = 0; if (fromPart == toPart) { for (int i = from; i <= to; i++) { result += array[i]; } return result; } for (int i = fromPart + 1; i < toPart; i++) { result += sums[i]; } int fromEnd = (fromPart + 1) * partCapacity - 1; int toStart = toPart * partCapacity; for (int i = from; i <= fromEnd; i++) { result += array[i]; } for (int i = toStart; i <= to; i++) { result += array[i]; } return result; } } private void solve() throws IOException { int n = nextInt(); int k = nextInt(); int a = nextInt(); int b = nextInt(); long[] orders = new long[n]; Decomposition before = new Decomposition(n, b); Decomposition after = new Decomposition(n, a); int q = nextInt(); for (int i = 0; i < q; i++) { int type = nextInt(); if (type == 1) { int day = nextInt() - 1; long cnt = nextLong(); orders[day] += cnt; before.updateElement(orders[day], day); after.updateElement(orders[day], day); } else { int p = nextInt() - 1; int left = p - 1; int right = p + k; long result = before.getSum(0,left) + after.getSum(right,n-1); out.println(result); } } } private String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String str = in.readLine(); if (str == null) return null; st = new StringTokenizer(str); } return st.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private void close() { out.close(); } private void open() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } }
Java
["5 2 2 1 8\n1 1 2\n1 5 3\n1 2 1\n2 2\n1 4 2\n1 3 2\n2 1\n2 3", "5 4 10 1 6\n1 1 5\n1 5 5\n1 3 2\n1 5 2\n2 1\n2 2"]
4 seconds
["3\n6\n4", "7\n1"]
NoteConsider the first sample.We produce up to 1 thimble a day currently and will produce up to 2 thimbles a day after repairs. Repairs take 2 days.For the first question, we are able to fill 1 order on day 1, no orders on days 2 and 3 since we are repairing, no orders on day 4 since no thimbles have been ordered for that day, and 2 orders for day 5 since we are limited to our production capacity, for a total of 3 orders filled.For the third question, we are able to fill 1 order on day 1, 1 order on day 2, and 2 orders on day 5, for a total of 4 orders.
Java 8
standard input
[ "data structures" ]
d256f8cf105b08624eee21dd76a6ad3d
The first line contains five integers n, k, a, b, and q (1 ≀ k ≀ n ≀ 200 000, 1 ≀ b &lt; a ≀ 10 000, 1 ≀ q ≀ 200 000)Β β€” the number of days, the length of the repair time, the production rates of the factory, and the number of updates, respectively. The next q lines contain the descriptions of the queries. Each query is of one of the following two forms: 1 di ai (1 ≀ di ≀ n, 1 ≀ ai ≀ 10 000), representing an update of ai orders on day di, or 2 pi (1 ≀ pi ≀ n - k + 1), representing a question: at the moment, how many orders could be filled if the factory decided to commence repairs on day pi? It's guaranteed that the input will contain at least one query of the second type.
1,700
For each query of the second type, print a line containing a single integer β€” the maximum number of orders that the factory can fill over all n days.
standard output