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
29434341febe353078e445d5cbf58428
train_001.jsonl
1361719800
The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules: The players move in turns; In one move the player can remove an arbitrary letter from string s. If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well β€” the one who moves first or the one who moves second.
256 megabytes
import java.util.*; public class Main { public static void main (String[] args){ Scanner in = new Scanner(System.in); String s = in.next(); int c[] = new int[26]; for(int i =0 ;i<s.length();i++) { c[s.charAt(i)-'a']++; } int odd=0; for(int i =0 ;i<c.length;i++) { if(c[i]%2==1) odd++; } if(odd==0)System.out.print("First"); else if(odd%2==1)System.out.println("First"); else if(odd%2==0)System.out.println("Second"); else System.out.println("First"); } }
Java
["aba", "abca"]
2 seconds
["First", "Second"]
null
Java 7
standard input
[ "greedy", "games" ]
bbf2dbdea6dd3aa45250ab5a86833558
The input contains a single line, containing string s (1 ≀ |s|  ≀  103). String s consists of lowercase English letters.
1,300
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
standard output
PASSED
37892db3397986bc91a365beb7869874
train_001.jsonl
1361719800
The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules: The players move in turns; In one move the player can remove an arbitrary letter from string s. If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well β€” the one who moves first or the one who moves second.
256 megabytes
import java.util.Scanner; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.math.BigDecimal; import java.io.BufferedWriter; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Fish <[email protected]> */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { String s = in.next(); int[] count = new int[26]; for (int i = 0; i < s.length(); ++i) { ++count[s.charAt(i) - 'a']; } int odd = 0; for (int i = 0; i < 26; ++i) { if (count[i] % 2 == 1) ++odd; } if (odd == 0 || odd % 2 == 1) out.println("First"); else out.println("Second"); } } class InputReader { private Scanner scanner; public InputReader(InputStream inputStream) { scanner = new Scanner(new BufferedReader(new InputStreamReader(inputStream))); } public int nextInt() { return scanner.nextInt(); } public long nextLong() { return scanner.nextLong(); } public String next() { return scanner.next(); } public BigInteger nextBigInteger() { return scanner.nextBigInteger(); } public BigDecimal nextBigDecimal() { return scanner.nextBigDecimal(); } public double nextDouble() { return scanner.nextDouble(); } } class OutputWriter { private PrintWriter printWriter; public OutputWriter(OutputStream outputStream) { printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { printWriter = new PrintWriter(writer); } public <T> void print(T object) { printWriter.print(object); } public <T> void println(T object) { printWriter.println(object); } public void close() { printWriter.close(); } }
Java
["aba", "abca"]
2 seconds
["First", "Second"]
null
Java 7
standard input
[ "greedy", "games" ]
bbf2dbdea6dd3aa45250ab5a86833558
The input contains a single line, containing string s (1 ≀ |s|  ≀  103). String s consists of lowercase English letters.
1,300
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
standard output
PASSED
d67cb2c84f8da81eabcf2c8c3b43a1e9
train_001.jsonl
1361719800
The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules: The players move in turns; In one move the player can remove an arbitrary letter from string s. If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well β€” the one who moves first or the one who moves second.
256 megabytes
import java.util.*; public class P_276B { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.next(); int[] cBucket = new int[26]; for (int i = 0; i < s.length(); ++i) cBucket[s.charAt(i) - 'a']++; int oddNum = 0; for (int i = 0; i < 26; ++i) { if (cBucket[i]%2 == 1) ++oddNum; } System.out.println(oddNum == 0 || oddNum % 2 == 1 ? "First" : "Second"); } }
Java
["aba", "abca"]
2 seconds
["First", "Second"]
null
Java 7
standard input
[ "greedy", "games" ]
bbf2dbdea6dd3aa45250ab5a86833558
The input contains a single line, containing string s (1 ≀ |s|  ≀  103). String s consists of lowercase English letters.
1,300
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
standard output
PASSED
ad3133b623f1753b7141228e72c63fc8
train_001.jsonl
1361719800
The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules: The players move in turns; In one move the player can remove an arbitrary letter from string s. If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well β€” the one who moves first or the one who moves second.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; /** * * @hor user */ public class gameB { public static void main(String[] args) throws IOException { BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); int[] A= new int[26]; String S= br.readLine(); for (int i = 0; i < S.length(); i++) { A[(int)S.charAt(i)-(int)'a']++; } int oc=0; for (int i = 0; i < 26; i++) { if(A[i]%2==1)oc++; } if(oc<2) System.out.println("First"); else { if(S.length()%2==0) System.out.println("Second"); else System.out.println("First"); } } }
Java
["aba", "abca"]
2 seconds
["First", "Second"]
null
Java 7
standard input
[ "greedy", "games" ]
bbf2dbdea6dd3aa45250ab5a86833558
The input contains a single line, containing string s (1 ≀ |s|  ≀  103). String s consists of lowercase English letters.
1,300
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
standard output
PASSED
30ce7e7cf5e76e8e0ff6c6d8bbba6b53
train_001.jsonl
1361719800
The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules: The players move in turns; In one move the player can remove an arbitrary letter from string s. If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well β€” the one who moves first or the one who moves second.
256 megabytes
import java.util.*; import static java.lang.Math.*; import java.awt.Point; import java.io.*; public class A { static Scanner sc = new Scanner(new BufferedInputStream(System.in)); public static void main(String[] args) { String in = n() ; int[] a = new int[26]; for(int i = 0; i < in.length(); i++) a[in.charAt(i)-'a']++; int k = 0; for(int x : a) if((x & 1 ) == 1) k++; if(k<=1 || (k&1) == 1){ System.out.println("First"); } else { System.out.println("Second"); } } static String n() { return sc.next(); } static int ni() { return Integer.parseInt(n()); } static long nl() { return Long.parseLong(n()); } }
Java
["aba", "abca"]
2 seconds
["First", "Second"]
null
Java 7
standard input
[ "greedy", "games" ]
bbf2dbdea6dd3aa45250ab5a86833558
The input contains a single line, containing string s (1 ≀ |s|  ≀  103). String s consists of lowercase English letters.
1,300
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
standard output
PASSED
44457db284c26d479c911dd5acf77fab
train_001.jsonl
1361719800
The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules: The players move in turns; In one move the player can remove an arbitrary letter from string s. If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well β€” the one who moves first or the one who moves second.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class LittleGirlAndGame { public static void main(final String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s = in.readLine(); int length = s.length(); char[] chars = s.toCharArray(); int[] number = new int[26]; for (char c : chars) { number[c - 'a']++; } int odd = 0; for (int i : number) { if (isOdd(i)) { odd++; } } if (odd == 0 || (odd == 1 && isOdd(length))) { System.out.println("First"); return; } if (isOdd(odd)) { if (isOdd(length)) { System.out.println("First"); return; } else { System.out.println("Second"); return; } } else { System.out.println("Second"); return; } } static boolean isOdd(int i) { return i % 2 == 1; } }
Java
["aba", "abca"]
2 seconds
["First", "Second"]
null
Java 7
standard input
[ "greedy", "games" ]
bbf2dbdea6dd3aa45250ab5a86833558
The input contains a single line, containing string s (1 ≀ |s|  ≀  103). String s consists of lowercase English letters.
1,300
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
standard output
PASSED
5b4084912a4289082cb47a8e4e5222fe
train_001.jsonl
1361719800
The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules: The players move in turns; In one move the player can remove an arbitrary letter from string s. If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well β€” the one who moves first or the one who moves second.
256 megabytes
import java.io.IOException; import java.util.InputMismatchException; public class LittleGirlAndGame { public static void main(String[] args) { FasterScanner sc = new FasterScanner(); char[] S = sc.nextLine().toCharArray(); int[] freq = new int[256]; for (int i = 0; i < S.length; i++) { freq[S[i]]++; } int odd = 0; for (char c = 'a'; c <= 'z'; c++) { if (freq[c] % 2 == 1) { odd++; } } if (odd == 0 || odd % 2 == 1) { System.out.println("First"); } else { System.out.println("Second"); } } public static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = System.in.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 nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { return nextIntArray(n, 0); } public int[] nextIntArray(int n, int off) { int[] arr = new int[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextInt(); } return arr; } public long[] nextLongArray(int n) { return nextLongArray(n, 0); } public long[] nextLongArray(int n, int off) { long[] arr = new long[n + off]; for (int i = 0; i < n; i++) { arr[i + off] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["aba", "abca"]
2 seconds
["First", "Second"]
null
Java 7
standard input
[ "greedy", "games" ]
bbf2dbdea6dd3aa45250ab5a86833558
The input contains a single line, containing string s (1 ≀ |s|  ≀  103). String s consists of lowercase English letters.
1,300
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
standard output
PASSED
383f3296873b5184e429816fa8217b7f
train_001.jsonl
1361719800
The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules: The players move in turns; In one move the player can remove an arbitrary letter from string s. If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well β€” the one who moves first or the one who moves second.
256 megabytes
import java.io.*; import java.util.*; public final class little_girl_and_game { static Scanner sc=new Scanner(System.in); static PrintWriter out=new PrintWriter(System.out); public static void main(String args[]) throws Exception { char[] a=sc.next().toCharArray(); int[] cnt=new int[123]; for(int i=0;i<a.length;i++) { cnt[(int)a[i]]++; } int c=0; for(int i=97;i<=122;i++) { if(cnt[i]%2!=0) { c++; } } if(c>=1) { c--; } out.println((c%2==0)?"First":"Second"); out.close(); } }
Java
["aba", "abca"]
2 seconds
["First", "Second"]
null
Java 7
standard input
[ "greedy", "games" ]
bbf2dbdea6dd3aa45250ab5a86833558
The input contains a single line, containing string s (1 ≀ |s|  ≀  103). String s consists of lowercase English letters.
1,300
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
standard output
PASSED
8b2bddfe1de9bae56f77a09b271a9779
train_001.jsonl
1361719800
The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules: The players move in turns; In one move the player can remove an arbitrary letter from string s. If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well β€” the one who moves first or the one who moves second.
256 megabytes
import java.util.*; import static java.lang.System.*; public class A276 { Scanner sc = new Scanner(in); public void run() { String n=sc.next(); boolean pali=true; int[] c=new int[30]; for(int i=0;i<n.length();i++){ c[n.charAt(i)-'a']++; } int odd=0; for(int i=0;i<30;i++){ if(c[i]%2!=0)odd++; } if(odd<=1){ ln("First"); }else{ ln(n.length()%2==0?"Second":"First"); } } public static void main(String[] _) { new A276().run(); } public static void pr(Object o) { out.print(o); } public static void ln(Object o) { out.println(o); } public static void ln() { out.println(); } }
Java
["aba", "abca"]
2 seconds
["First", "Second"]
null
Java 7
standard input
[ "greedy", "games" ]
bbf2dbdea6dd3aa45250ab5a86833558
The input contains a single line, containing string s (1 ≀ |s|  ≀  103). String s consists of lowercase English letters.
1,300
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
standard output
PASSED
05ee660c3ad490217dbd89c5d7f8af85
train_001.jsonl
1361719800
The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules: The players move in turns; In one move the player can remove an arbitrary letter from string s. If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well β€” the one who moves first or the one who moves second.
256 megabytes
import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class B { public static void main(String[] args) { Scanner s = new Scanner(System.in); String line = s.nextLine(); Set<Character> set = new HashSet<Character>(); for (char c : line.toCharArray()) { if (set.contains(c)) { set.remove(c); } else { set.add(c); } } if (set.size() == 0 || set.size() % 2 == 1) { System.out.println("First"); } else { System.out.println("Second"); } } }
Java
["aba", "abca"]
2 seconds
["First", "Second"]
null
Java 7
standard input
[ "greedy", "games" ]
bbf2dbdea6dd3aa45250ab5a86833558
The input contains a single line, containing string s (1 ≀ |s|  ≀  103). String s consists of lowercase English letters.
1,300
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
standard output
PASSED
fe2e6124c21d06c38a4d768cecd5e895
train_001.jsonl
1361719800
The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules: The players move in turns; In one move the player can remove an arbitrary letter from string s. If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well β€” the one who moves first or the one who moves second.
256 megabytes
import java.util.Scanner; public class B{ public static void main(String args[]){ Scanner input = new Scanner(System.in); String str = input.next(); char let[] = str.toCharArray(); boolean ans = true; int winner = 2; while(ans){ boolean won = true; won = check(let); if(won){ if(winner == 2) System.out.println("First"); else System.out.println("Second"); break; } else{ if(winner == 2) winner = 1; else winner = 2; } int s = 0; int g = -1; boolean r = false; for(int k = s; k < let.length && !r; k++){ r = true; char nlet[] = new char [let.length - 1]; for(int i = 0, j = 0; i < let.length; i++){ if(i != s){ nlet[j++] = let[i]; } } r = check(nlet); if(r){ g = k; break; } } if(g != -1){ char nlet[] = new char [let.length - 1]; for(int i = 0, j = 0; i < let.length; i++){ if(i != g){ nlet[j++] = let[i]; } } let = nlet; } else{ char nlet[] = new char [let.length - 1]; for(int i = 0, j = 0; i < let.length - 1; i++){ nlet[j++] = let[i]; } let = nlet; } } input.close(); } public static boolean check(char let[]){ boolean won = true; if(let.length != 1){ int l[] = new int [26]; for(int i = 0; i < let.length; i++){ l[let[i] - 'a']++; } if(let.length % 2 == 0){ for(int i = 0; i < 26; i++) if(l[i] % 2 == 1){ won = false; break; } } else{ boolean dd = false; for(int i = 0; i < 26; i++){ if(l[i] % 2 == 1){ if(dd){ won = false; break; } else{ dd = true; } } } if(!dd) won = false; } } return won; } }
Java
["aba", "abca"]
2 seconds
["First", "Second"]
null
Java 7
standard input
[ "greedy", "games" ]
bbf2dbdea6dd3aa45250ab5a86833558
The input contains a single line, containing string s (1 ≀ |s|  ≀  103). String s consists of lowercase English letters.
1,300
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
standard output
PASSED
275071c59be4b024e5fcce9652b3486c
train_001.jsonl
1361719800
The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules: The players move in turns; In one move the player can remove an arbitrary letter from string s. If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well β€” the one who moves first or the one who moves second.
256 megabytes
import java.util.Scanner; public class B_169 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s=sc.next(); int a[]=new int[1000]; for (int i = 0; i <s.length(); i++) { a[(int)s.charAt(i)-97]++; } int ans=0; for (int i =0; i <=26; i++) { if(a[i]%2==1 && a[i]!=0) ans++; } if(ans%2==1 || ans==0) System.out.println("First"); else System.out.println("Second"); } }
Java
["aba", "abca"]
2 seconds
["First", "Second"]
null
Java 7
standard input
[ "greedy", "games" ]
bbf2dbdea6dd3aa45250ab5a86833558
The input contains a single line, containing string s (1 ≀ |s|  ≀  103). String s consists of lowercase English letters.
1,300
In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.
standard output
PASSED
4ca637662379e13fed724fe2c5b29b53
train_001.jsonl
1596638100
You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.Arrays; public class RemoveSmallest{ public static void main(String[] args){ try{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int cases = Integer.parseInt(br.readLine()); int arLen = 0; String[] temp; int[] arr = null; boolean val = true; while(cases-->0){ arLen = Integer.parseInt(br.readLine()); arr = new int[arLen]; temp = br.readLine().split("\\s+"); for(int i = 0; i < arLen; i++){ arr[i] = Integer.parseInt(temp[i]); } Arrays.sort(arr); val = true; for(int j = 1; j < arLen; j++){ if(arr[j] - arr[j-1] > 1){ val = false; } } System.out.println( val ? "YES": "NO"); } }catch(IOException ioe){ ioe.printStackTrace(); } } }
Java
["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"]
1 second
["YES\nYES\nNO\nNO\nYES"]
NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.
Java 8
standard input
[ "sortings", "greedy" ]
ed449ba7c453a43e2ac5904dc0174530
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
800
For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.
standard output
PASSED
e4a47e6bf7abe1dccb2bd17be0128691
train_001.jsonl
1596638100
You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.Arrays; public class RemoveSmallest{ public static void main(String[] args){ try{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int cases = Integer.parseInt(br.readLine()); int arLen = 0; String[] temp; int[] arr = null; boolean val = true; while(cases-->0){ arLen = Integer.parseInt(br.readLine()); if(arLen == 1){ br.readLine(); val = true; } else { arr = new int[arLen]; temp = br.readLine().split("\\s+"); for(int i = 0; i < arLen; i++){ arr[i] = Integer.parseInt(temp[i]); } Arrays.sort(arr); val = true; for(int j = 1; j < arLen; j++){ if(arr[j] - arr[j-1] > 1){ val = false; } } } System.out.println( val ? "YES": "NO"); } }catch(IOException ioe){ ioe.printStackTrace(); } } }
Java
["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"]
1 second
["YES\nYES\nNO\nNO\nYES"]
NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.
Java 8
standard input
[ "sortings", "greedy" ]
ed449ba7c453a43e2ac5904dc0174530
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
800
For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.
standard output
PASSED
6450882ad70bdcbe158749c79b313682
train_001.jsonl
1596638100
You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class Main{ public static void main(String[] args) { // Use the Scanner class Scanner sc = new Scanner(System.in); /* int n = sc.nextInt(); // read input as integer long k = sc.nextLong(); // read input as long double d = sc.nextDouble(); // read input as double String str = sc.next(); // read input as String String s = sc.nextLine(); // read whole line as String */ int count = sc.nextInt(); String[] answers = new String[count]; int arraySize = 0; for(int i = 0; i < count; i++) { arraySize = sc.nextInt(); int[] array = new int[arraySize]; for(int j = 0; j < arraySize; j++) { array[j] = sc.nextInt(); } //System.out.println(Arrays.toString(array)); String result = solution(array); //System.out.println(result); answers[i] = result; } for(int i = 0; i < answers.length; i++) { System.out.println(answers[i]); } } public static String solution(int[] array) { String result = ""; int diff = -100; if(array.length == 1) { result = "YES"; return result; } Arrays.sort(array); for(int i = 0; i < array.length - 1; i++) { diff = array[i+1] - array[i]; if(diff > 1) { result = "NO"; return result; } } result = "YES"; return result; } }
Java
["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"]
1 second
["YES\nYES\nNO\nNO\nYES"]
NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.
Java 8
standard input
[ "sortings", "greedy" ]
ed449ba7c453a43e2ac5904dc0174530
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
800
For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.
standard output
PASSED
1f966007d83a7b87ef9519954360c6d7
train_001.jsonl
1596638100
You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class Solution{ public static void main(String[] args){ Scanner inp =new Scanner(System.in); int t = inp.nextInt(); while(t-- >0){ int n =inp.nextInt(); int[] nums =new int[n]; for(int i=0;i<n;i++){ nums[i] =inp.nextInt(); } Arrays.sort(nums); boolean flag =false ; for(int i=0; i<n-1;i++){ if(Math.abs(nums[i] - nums[i+1]) > 1){ System.out.println("NO"); flag =true; break; } } if(!flag){ System.out.println("YES"); } } } }
Java
["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"]
1 second
["YES\nYES\nNO\nNO\nYES"]
NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.
Java 8
standard input
[ "sortings", "greedy" ]
ed449ba7c453a43e2ac5904dc0174530
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
800
For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.
standard output
PASSED
bc3e9268141e5a0b2d6d649429f024c1
train_001.jsonl
1596638100
You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public class RemoveSmallest { private void removeSmallest(List<List<Integer>> inputList) { for (List<Integer> list : inputList) { helper(list); } } private void helper(List<Integer> list) { Collections.sort(list); for (int i = 1; i < list.size(); i++) { if (list.get(i) - list.get(i - 1) > 1) { System.out.println("NO"); return; } } System.out.println("YES"); } public static void main(String[] args) { int numTests = -1, numInputs = 0; Scanner scanner = new Scanner(new BufferedInputStream(System.in)); List<List<Integer>> inputList = new ArrayList<>(); List<Integer> inputSublist = null; while (scanner.hasNext()) { if (numTests == -1) { numTests = scanner.nextInt(); continue; } else if (numInputs == 0) { numInputs = scanner.nextInt(); inputSublist = new ArrayList<>(); inputList.add(inputSublist); } else { inputSublist.add(scanner.nextInt()); numInputs--; } } // System.out.println("inputList: " + inputList); RemoveSmallest rs = new RemoveSmallest(); rs.removeSmallest(inputList); } } /* wrong answer Answer contains longer sequence [length = 5], but output contains 0 elements */
Java
["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"]
1 second
["YES\nYES\nNO\nNO\nYES"]
NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.
Java 8
standard input
[ "sortings", "greedy" ]
ed449ba7c453a43e2ac5904dc0174530
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
800
For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.
standard output
PASSED
0b0089c4af34d733d9645897347ffdba
train_001.jsonl
1596638100
You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class Main { public static void main(String[] args) throws Exception{ Scanner s=new Scanner(System.in); int t=s.nextInt(); for(int is=0;is<t;is++) { int n=s.nextInt(); int[] arr=new int[n]; for(int i=0;i<n;i++) { arr[i]=s.nextInt(); } Arrays.sort(arr); int flag=0; for(int i=0;i<n-1;i++) { if(Math.abs(arr[i+1]-arr[i])>1) { flag=1; } } if(flag==0) { System.out.println("YES"); }else { System.out.println("NO"); } } } }
Java
["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"]
1 second
["YES\nYES\nNO\nNO\nYES"]
NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.
Java 8
standard input
[ "sortings", "greedy" ]
ed449ba7c453a43e2ac5904dc0174530
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
800
For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.
standard output
PASSED
4a0c00eec89f9c25c4e935a806c97643
train_001.jsonl
1596638100
You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class Main { public static void main(String[] args) throws Exception{ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int j=0;j<t;j++) { int n=sc.nextInt(); int[] arr=new int[n]; for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); } Arrays.sort(arr); int flag=0; for(int i=0;i<n-1;i++) { if(Math.abs(arr[i+1]-arr[i])>1) { flag=1; } } if(flag==0) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
Java
["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"]
1 second
["YES\nYES\nNO\nNO\nYES"]
NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.
Java 8
standard input
[ "sortings", "greedy" ]
ed449ba7c453a43e2ac5904dc0174530
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
800
For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.
standard output
PASSED
4cc7a9a0ae13385cd41f4db8fb8479a2
train_001.jsonl
1596638100
You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class RemoveSmallest { public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) throws Exception { br = new BufferedReader(new InputStreamReader(in)); } public String next() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine().trim()); } return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(next()); } } public static void main(String[] args) throws Exception { FastScanner in = new FastScanner(System.in); int t = in.nextInt(); for (int i = 0; i < t; i++) { int n = in.nextInt(); List<Integer> array = new ArrayList<>(); for(int j = 0; j < n; j++) { array.add(in.nextInt()); } array.sort(Integer::compareTo); boolean printed = false; for (int k = 0; k < n-1; k++) { if (Math.abs(array.get(k) - array.get(k+1)) > 1) { System.out.println("NO"); printed = true; break; } } if (!printed) { System.out.println("YES"); } } } }
Java
["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"]
1 second
["YES\nYES\nNO\nNO\nYES"]
NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.
Java 8
standard input
[ "sortings", "greedy" ]
ed449ba7c453a43e2ac5904dc0174530
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
800
For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.
standard output
PASSED
1d7f8f070da8ed1160f3eae0d12e4d43
train_001.jsonl
1596638100
You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Solution{ public static void main(String args[]){ Scanner s = new Scanner(System.in); int t=s.nextInt(); for(int i=0;i<t;i++){ int n=s.nextInt(); int a[]=new int[n]; int c=0; for(int j=0;j<n;j++) a[j]=s.nextInt(); if(n==1) System.out.println("Yes"); Arrays.sort(a); int d[]=new int[n-1]; int flag=0; if(n>1){ for(int j=0;j<n-1;j++){ d[j]=a[j+1]-a[j]; if(d[j]>1&&flag==0){ System.out.println("No"); flag=1;} else if(j==n-2&&flag==0){ System.out.println("Yes"); } else{ c++;}}}}}}
Java
["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"]
1 second
["YES\nYES\nNO\nNO\nYES"]
NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.
Java 8
standard input
[ "sortings", "greedy" ]
ed449ba7c453a43e2ac5904dc0174530
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
800
For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.
standard output
PASSED
936080f4b3808d7dd19caf08cd5588f9
train_001.jsonl
1596638100
You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class C { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t > 0) { t--; int n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } Arrays.sort(a); int flag=0; for (int i = 1; i < a.length; i++) { if (a[i]-a[i-1]>1){ System.out.println("NO"); flag=1; break; } } if (flag==0) { System.out.println("YES"); } } } }
Java
["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"]
1 second
["YES\nYES\nNO\nNO\nYES"]
NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.
Java 8
standard input
[ "sortings", "greedy" ]
ed449ba7c453a43e2ac5904dc0174530
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
800
For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.
standard output
PASSED
333eb69d6023834c71c7b9509d6a4177
train_001.jsonl
1596638100
You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class A1 { public static void main(String[] args) { Scanner in=new Scanner(System.in); int t=in.nextInt(); for(int k=0;k<t;k++) { int n=in.nextInt(); int[] arr=new int[n]; for(int i=0;i<n;i++) { arr[i]=in.nextInt(); } int z = arr.length; for (int i = 1; i < z; ++i) { int key = arr[i]; int j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } int flag=0; for(int i=0;i<n-1;i++) { if(Math.abs(arr[i]-arr[i+1]) >1) { flag=1; break; } } if(flag==1) { System.out.println("NO"); } else { System.out.println("YES"); } } } }
Java
["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"]
1 second
["YES\nYES\nNO\nNO\nYES"]
NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.
Java 8
standard input
[ "sortings", "greedy" ]
ed449ba7c453a43e2ac5904dc0174530
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
800
For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.
standard output
PASSED
b1dc181de6f63e8e2f53976ab4474c49
train_001.jsonl
1596638100
You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.*; public class Rem { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader sc = new FastReader(); int t = sc.nextInt(); StringBuilder sb = new StringBuilder(); while (t-- > 0) { int len = sc.nextInt(); int[] a = new int[len]; for (int i = 0; i < len; i++) { a[i] = sc.nextInt(); } if (len == 1) { sb.append("YES \n"); } else { Arrays.sort(a); for (int i = 0; i < len - 1; i++) { if (a[i] != 0 && a[i + 1] != 0) { int v = Math.abs(a[i] - a[i + 1]); if (v <= 1) { if (a[i] <= a[i + 1]) a[i] = 0; else a[i + 1] = 0; } } } int c = 0; for (int i = 0; i < len; i++) { if (a[i] != 0) c++; } if (c == 1) { sb.append("YES \n"); // System.out.println("YES"); } else { sb.append("NO \n"); // System.out.println("NO"); } } } System.out.print(sb); } }
Java
["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"]
1 second
["YES\nYES\nNO\nNO\nYES"]
NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.
Java 8
standard input
[ "sortings", "greedy" ]
ed449ba7c453a43e2ac5904dc0174530
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
800
For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.
standard output
PASSED
bf6170ef0732c50d93c13ecc16efc73d
train_001.jsonl
1596638100
You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class Solution{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- != 0){ int n = sc.nextInt(); int[] a = new int[n]; for(int i=0; i<n; i++) a[i] = sc.nextInt(); Arrays.sort(a); boolean flag = true; for(int i=1; i<n; i++){ if(a[i] - a[i-1] > 1){ flag = false; break; } } if(flag) System.out.println("YES"); else System.out.println("NO"); } } }
Java
["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"]
1 second
["YES\nYES\nNO\nNO\nYES"]
NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.
Java 8
standard input
[ "sortings", "greedy" ]
ed449ba7c453a43e2ac5904dc0174530
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
800
For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.
standard output
PASSED
11cb69b615a2ff4fb429e3df7c217db2
train_001.jsonl
1596638100
You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; public class Main { public static void main(String args[])throws Exception { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); Scanner sc=new Scanner(System.in); int t=Integer.parseInt(in.readLine()); //String t1=in.readLine(); //sc.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); //System.out.println("helo"); for(int k=0;k<t;k++) { int n=Integer.parseInt(in.readLine()); int arr[]=new int[n]; String num[]=new String[n]; int diff=0; int flag=0; num=in.readLine().split(" "); for(int i=0;i<n;i++) { arr[i]=Integer.parseInt(num[i]); } Arrays.sort(arr); for(int i=1;i<n;i++) { //if(i>0){ diff=Math.abs(arr[i]-arr[i-1]); if(diff>1){ flag=-999; break; } else flag=1; //} } if(flag>=0) { System.out.println("YES"); continue; } else { System.out.println("NO"); } } } }
Java
["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"]
1 second
["YES\nYES\nNO\nNO\nYES"]
NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.
Java 8
standard input
[ "sortings", "greedy" ]
ed449ba7c453a43e2ac5904dc0174530
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
800
For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.
standard output
PASSED
06645247964c43631228f5a1a1669cbe
train_001.jsonl
1596638100
You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub FastReader input = new FastReader(); StringBuilder output = new StringBuilder(); int testCases = input.nextInt(); while (testCases-- > 0) { int n = input.nextInt(); boolean can = true; List<Integer> numbers = new ArrayList<>(); for (int i = 0; i < n; i++) { numbers.add(input.nextInt()); } if (numbers.size() == 1) { output.append("YES\n"); } else { Collections.sort(numbers); for (int i = 1; i < numbers.size(); i++) { if (numbers.get(i) - numbers.get(i - 1) > 1) { can = false; break; } } output.append(can ? "YES\n" : "NO\n"); } } System.out.println(output); } } 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) { throw new RuntimeException(e); } } 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) { throw new RuntimeException(e); } return str; } }
Java
["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"]
1 second
["YES\nYES\nNO\nNO\nYES"]
NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.
Java 8
standard input
[ "sortings", "greedy" ]
ed449ba7c453a43e2ac5904dc0174530
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
800
For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.
standard output
PASSED
3f837cb5db3cc48be4bd3be315a3cc90
train_001.jsonl
1596638100
You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int[]arr=new int[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); } int count=0; Sort(arr); for(int i=0;i<n-1;i++){ if(arr[i+1]<=arr[i]+1)count++; } if(count>=n-1)pw.println("YES"); else pw.println("NO"); } pw.close(); } public static boolean prime(int x){ int[] arr=new int[10000000]; int index=0; int num=3; int i=0; arr[0]=2; while(num<=x){ for(i=0;i<=index;i++){ if(num%arr[i]==0){ break; } } if(i==index+1){ arr[++index]=num; } num++; } if(arr[index]==x)return true; return false; } public static void conquer(int[] arr,int b,int m,int e){ int len1=m-b+1; int len2=e-m; int[] l=new int[len1]; int[] r=new int[len2]; for(int i=0;i<len1;i++){ l[i]=arr[b+i]; } for(int j=0;j<len2;j++){ r[j]=arr[m+1+j]; } int i=0,j=0,k=b; while((i<len1)&&(j<len2)){ if(r[j]>=l[i]){ arr[k]=l[i]; k++; i++; } else{ arr[k]=r[j]; k++; j++; } } while(i<len1){ arr[k++]=l[i++]; } while(j<len2){ arr[k++]=r[j++]; } } static int mid; public static void sort(int[] arr,int b,int e){ if(b<e){ int mid =(e+b)/2; sort(arr,b,mid); sort(arr,mid+1,e); conquer(arr,b,mid,e); } } public static void Sort(int[] arr){ sort(arr,0,arr.length-1); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"]
1 second
["YES\nYES\nNO\nNO\nYES"]
NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.
Java 8
standard input
[ "sortings", "greedy" ]
ed449ba7c453a43e2ac5904dc0174530
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
800
For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.
standard output
PASSED
5c139d6e505811cf9bfe482bf280674a
train_001.jsonl
1596638100
You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.
256 megabytes
//package RemoveSmallest; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int t=scan.nextInt(); while(t-->0) { int n=scan.nextInt(); ArrayList<Integer> l=new ArrayList<Integer>(); for (int i = 0; i < n; i++) { l.add(scan.nextInt()); } Collections.sort(l); while(l.size()>1) { if(Math.abs(l.get(0)-l.get(1))<=1)l.remove(0); else break; } // System.out.println(l); if(l.size()==1)System.out.println("YES"); else System.out.println("NO"); } } }
Java
["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"]
1 second
["YES\nYES\nNO\nNO\nYES"]
NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.
Java 8
standard input
[ "sortings", "greedy" ]
ed449ba7c453a43e2ac5904dc0174530
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
800
For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.
standard output
PASSED
c0ef609250e5acbf12d6d2624be0db40
train_001.jsonl
1596638100
You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for(int i = 0; i < t; i++) { int n = in.nextInt(); ArrayList<Integer> arr = new ArrayList<Integer>(); for(int j = 0; j < n; j++) arr.add(in.nextInt()); Collections.sort(arr); System.out.println(find(arr)); } } static String find(ArrayList<Integer> arr) { boolean[] removed = new boolean[arr.size()]; int remaining = arr.size(); if(arr.size() == 1) return "YES"; for(int i = 0; i < arr.size(); i++) { for(int j = i + 1; j < arr.size(); j++) { if(removed[i] || removed[j]) continue; if(Math.abs(arr.get(i) - arr.get(j)) <= 1) { if(arr.get(i) > arr.get(j)) { removed[j] = true; remaining--; } else { removed[i] = true; remaining--; } } if(remaining == 1) return "YES"; } } return "NO"; } }
Java
["5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100"]
1 second
["YES\nYES\nNO\nNO\nYES"]
NoteIn the first test case of the example, we can perform the following sequence of moves: choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$); choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.
Java 8
standard input
[ "sortings", "greedy" ]
ed449ba7c453a43e2ac5904dc0174530
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) β€” the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) β€” the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.
800
For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.
standard output
PASSED
2889eba8d5e70612508570ba814a9cfa
train_001.jsonl
1522850700
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told β€” ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class q_2_41 { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] temp; temp = in.readLine().split("\\s+"); int n = Integer.parseInt(temp[0]); int k = Integer.parseInt(temp[1]); int[] t = new int[n]; int[] s = new int[n]; temp = in.readLine().split("\\s+"); for (int i = 0; i < n; i++) { t[i] = Integer.parseInt(temp[i]); } long sum = 0; temp = in.readLine().split("\\s+"); for (int i = 0; i < n; i++) { s[i] = Integer.parseInt(temp[i]); if (s[i] == 1) { sum += t[i]; } } int l = 0, r = 0; long res = 0, ans = sum; while(r < k){ if(s[r] == 0){ res += t[r]; ans = Math.max(ans, res+sum); } r++; } while(r < n){ if(s[l] == 0){ res -= t[l]; } if(s[r] == 0){ res += t[r]; } ans = Math.max(ans, res+sum); l++; r++; } System.out.println(ans); } }
Java
["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"]
1 second
["16"]
NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
Java 8
standard input
[ "dp", "two pointers", "implementation", "data structures" ]
0fbac68f497fe189ee088c13d0488cce
The first line of the input contains two integer numbers n and k (1 ≀ k ≀ n ≀ 105) β€” the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 104) β€” the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≀ ti ≀ 1) β€” type of Mishka's behavior at the i-th minute of the lecture.
1,200
Print only one integer β€” the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
standard output
PASSED
25280ae5791703f18af6c296ccb8dcc1
train_001.jsonl
1522850700
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told β€” ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
256 megabytes
import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ar { 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 (final 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 (final IOException e) { e.printStackTrace(); } return str; } } static long[] lar; static int[] t; public static void main(String[] args) throws java.lang.Exception { FastReader scn = new FastReader(); int n=scn.nextInt(),k=scn.nextInt(); lar=new long[n+2]; t=new int[n+2]; long[] pref=new long[n+2]; for(int i=1;i<=n;i++){ lar[i]=scn.nextLong(); pref[i]=lar[i]+pref[i-1]; } long[] sec=new long[n+1]; for(int i=1;i<=n;i++){ t[i]=scn.nextInt(); } for(int i=1;i<=n;i++){ if(t[i]==1){ sec[i]=lar[i]+sec[i-1]; }else sec[i]=sec[i-1]; } long ans=0; for(int j=1;j<=n;j++){ if(j>n-k+1){ break; }else{ ans=Math.max(ans,sec[j-1]-sec[0]+pref[j+k-1]-pref[j-1]+sec[n]-sec[j+k-1]); } } System.out.print(ans+"\n"); } }
Java
["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"]
1 second
["16"]
NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
Java 8
standard input
[ "dp", "two pointers", "implementation", "data structures" ]
0fbac68f497fe189ee088c13d0488cce
The first line of the input contains two integer numbers n and k (1 ≀ k ≀ n ≀ 105) β€” the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 104) β€” the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≀ ti ≀ 1) β€” type of Mishka's behavior at the i-th minute of the lecture.
1,200
Print only one integer β€” the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
standard output
PASSED
a8abbada6554d735c8c73c6469616a1f
train_001.jsonl
1522850700
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told β€” ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.*; import java.lang.*; import static java.lang.Integer.min; /** * * @author SNEHITH */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner sc = new Scanner(System.in); int min = 1000000000; int n = sc.nextInt(); int k = sc.nextInt(); int a[] = new int[n+1]; int t[] = new int[n+1]; int cost[] = new int[n+1]; int z_sum[] = new int[n+1]; int max=0,index1=1,index2=1,sum=0,success = 0,max1=0; for(int i=1;i<=n;i++){ a[i] = sc.nextInt(); cost[i] = cost[i-1]+a[i]; } for(int i=1;i<=n;i++){ t[i] = sc.nextInt(); if(t[i] == 0) z_sum[i] = z_sum[i-1] + a[i]; else z_sum[i] = z_sum[i-1]; } for(int i=n-k+1;i<=n;i++){ if(t[i] == 0) success = 1; } for(int i=1;i<=n-k+1;i++){ if(t[i] == 0 || ((i == n-k+1) && success == 1)){ if(z_sum[i+k-1] - z_sum[i-1] > max1){ max1 = z_sum[i+k-1] - z_sum[i-1]; max = cost[i+k-1] - cost[i-1]; index1 = i; index2 = i+k; } } } for(int i=1; i<index1;i++){ if(t[i] == 1) sum+= a[i]; } for(int i=index2; i<=n;i++){ if(t[i] == 1) sum+= a[i]; } System.out.println(max+sum); } }
Java
["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"]
1 second
["16"]
NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
Java 8
standard input
[ "dp", "two pointers", "implementation", "data structures" ]
0fbac68f497fe189ee088c13d0488cce
The first line of the input contains two integer numbers n and k (1 ≀ k ≀ n ≀ 105) β€” the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 104) β€” the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≀ ti ≀ 1) β€” type of Mishka's behavior at the i-th minute of the lecture.
1,200
Print only one integer β€” the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
standard output
PASSED
637d8edba16eb966a29e3a1ecbe92a9e
train_001.jsonl
1522850700
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told β€” ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
256 megabytes
//package math_codet; import java.io.*; import java.util.*; public class lets_do { public static void main(String[] args) { InputReader in=new InputReader(System.in); StringBuffer str=new StringBuffer(); int n=in.nextInt(); int k=in.nextInt(); int i=0; int arr[]=new int[n]; int beh[]=new int[n]; int pf_sum[]=new int[n]; int sum=0; for(i=0;i<n;i++){ arr[i]=in.nextInt(); sum+=arr[i]; pf_sum[i]=sum; } for(i=0;i<n;i++) beh[i]=in.nextInt(); int pf_sum1[]=new int[n]; int sum1=0; for(i=0;i<n;i++){ if(beh[i]==1) sum1+=arr[i]; pf_sum1[i]=sum1; } int max=0; for(i=0;i<n-k+1;i++){ //if(beh[i]==0){ if(i==0){ int sum2=pf_sum[k-1]+pf_sum1[n-1]-pf_sum1[k-1]; max=Math.max(sum2,max); } else if(i==n-k){ int sum2=pf_sum1[i-1]+pf_sum[n-1]-pf_sum[i-1]; max=Math.max(sum2,max); } else{ int sum2=pf_sum1[i-1]+pf_sum[i+k-1]-pf_sum[i-1]+pf_sum1[n-1]-pf_sum1[i+k-1]; max=Math.max(sum2,max); } //System.out.println(max);; //} } if(max==0) System.out.println(sum1); else System.out.println(max); } 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 UnknownError(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int peek() { if (numChars == -1) return -1; if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } if (numChars <= 0) return -1; } return buf[curChar]; } public void skip(int x) { while (x-- > 0) read(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextString() { return next(); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } 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 boolean hasNext() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value != -1; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"]
1 second
["16"]
NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
Java 8
standard input
[ "dp", "two pointers", "implementation", "data structures" ]
0fbac68f497fe189ee088c13d0488cce
The first line of the input contains two integer numbers n and k (1 ≀ k ≀ n ≀ 105) β€” the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 104) β€” the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≀ ti ≀ 1) β€” type of Mishka's behavior at the i-th minute of the lecture.
1,200
Print only one integer β€” the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
standard output
PASSED
080d02b68163b0ea4dce6ea4e0b52a3d
train_001.jsonl
1522850700
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told β€” ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ 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); LectureSleep solver = new LectureSleep(); solver.solve(1, in, out); out.close(); } static class LectureSleep { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int k = in.nextInt(); long arr[] = new long[n]; long pre1[] = new long[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextLong(); } long sum = 0; for (int i = 0; i < n; i++) { int t = in.nextInt(); if (t == 0) { if (i == 0) { pre1[i] = arr[i]; } else { pre1[i] = arr[i] + pre1[i - 1]; } } else if (t == 1) { if (i > 0) { pre1[i] = pre1[i - 1]; } sum += arr[i]; } } long max = sum; for (int i = k - 1; i < n; i++) { int index = i - k; long temp = 0; if (index >= 0) { temp = pre1[index]; } long add = pre1[i] - temp; max = Math.max(max, add + sum); } out.println(max); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"]
1 second
["16"]
NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
Java 8
standard input
[ "dp", "two pointers", "implementation", "data structures" ]
0fbac68f497fe189ee088c13d0488cce
The first line of the input contains two integer numbers n and k (1 ≀ k ≀ n ≀ 105) β€” the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 104) β€” the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≀ ti ≀ 1) β€” type of Mishka's behavior at the i-th minute of the lecture.
1,200
Print only one integer β€” the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
standard output
PASSED
d71103c30eebb27b5aa966e7e956f731
train_001.jsonl
1522850700
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told β€” ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
256 megabytes
import java.util.Scanner; public class LectureSleep { public static void main(String[] args) { Scanner cin=new Scanner(System.in); int N = cin.nextInt(); int k=cin.nextInt(); int arr[]=new int[N]; int time[]=new int[N]; for(int i=0;i<N;i++) { arr[i]=cin.nextInt(); } for(int i=0;i<N;i++) { time[i]=cin.nextInt(); } long sum=0; for(int i=N-1;i>=N-k;i--) { if(time[i]==0) sum+=arr[i]; } //System.out.println("sum="+sum); long max=sum; int v=N-k; for(int i=N-k-1;i>=0;i--) { if (time[i + k] == 0) { sum = sum - arr[i + k]; } if (time[i] == 0) { sum = sum + arr[i]; //System.out.println("sum right now i="+i+"and sum="+sum); } if(max<sum) { max=sum; v=i; } } if(v!=-1) { for(int i=v;i<=v+k-1;i++) { time[i]=1; } } long maxSum=0; for(int i=0;i<N;i++) { if(time[i]==1) { maxSum+=arr[i]; } } System.out.println(maxSum); } }
Java
["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"]
1 second
["16"]
NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
Java 8
standard input
[ "dp", "two pointers", "implementation", "data structures" ]
0fbac68f497fe189ee088c13d0488cce
The first line of the input contains two integer numbers n and k (1 ≀ k ≀ n ≀ 105) β€” the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 104) β€” the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≀ ti ≀ 1) β€” type of Mishka's behavior at the i-th minute of the lecture.
1,200
Print only one integer β€” the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
standard output
PASSED
e62dc963eeaf9ddbd3c4ec9afe59b5f9
train_001.jsonl
1522850700
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told β€” ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
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.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Objects; import java.util.Stack; import java.util.StringTokenizer; public class Test { static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args)throws Exception { Reader.init(System.in); int n = Reader.nextInt(); int k = Reader.nextInt(); int[] ar1 = new int[n+1]; int[] ar2 = new int[n+1]; long res = 0; long max = 0; for(int i = 1 ; i<=n ; i++) { ar1[i] = Reader.nextInt(); } for(int i = 1 ; i<=n ; i++) { ar2[i] = Reader.nextInt(); if(ar2[i] == 1) { res += ar1[i]; ar1[i] = 0; } } for(int i = 1 ; i<=k ; i++) max += ar1[i]; int x = 1; long pre = max; for(int i = k+1 ; i<=n ; i++) { pre += ar1[i]; pre -= ar1[x]; if(pre > max) max = pre; x++; } pw.print(res + max); pw.close(); } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; public static int pars(String x) { int num = 0; int i = 0; if (x.charAt(0) == '-') { i = 1; } for (; i < x.length(); i++) { num = num * 10 + (x.charAt(i) - '0'); } if (x.charAt(0) == '-') { return -num; } return num; } static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static void init(FileReader input) { reader = new BufferedReader(input); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer( reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return pars(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } }
Java
["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"]
1 second
["16"]
NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
Java 8
standard input
[ "dp", "two pointers", "implementation", "data structures" ]
0fbac68f497fe189ee088c13d0488cce
The first line of the input contains two integer numbers n and k (1 ≀ k ≀ n ≀ 105) β€” the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 104) β€” the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≀ ti ≀ 1) β€” type of Mishka's behavior at the i-th minute of the lecture.
1,200
Print only one integer β€” the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
standard output
PASSED
74458ea49b466f2b05db46bcfc6cb8d9
train_001.jsonl
1522850700
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told β€” ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
256 megabytes
import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author SteinOr */ public class CF961B { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); int k = input.nextInt(); int[] nums = new int[n]; int total = 0; for (int i = 0; i < n; i++){ nums[i] = input.nextInt(); } for (int i = 0; i < n; i++){ if (input.nextInt() == 1){ total += nums[i]; nums[i] = 0; } } int sum = 0; for (int i = 0; i < k; i++){ sum += nums[i]; } int most = sum; for (int i = k; i < n; i++){ sum += nums[i]; sum -= nums[i - k]; if (sum > most){ most = sum; } } System.out.println(total + most); } }
Java
["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"]
1 second
["16"]
NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
Java 8
standard input
[ "dp", "two pointers", "implementation", "data structures" ]
0fbac68f497fe189ee088c13d0488cce
The first line of the input contains two integer numbers n and k (1 ≀ k ≀ n ≀ 105) β€” the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 104) β€” the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≀ ti ≀ 1) β€” type of Mishka's behavior at the i-th minute of the lecture.
1,200
Print only one integer β€” the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
standard output
PASSED
057098a781126ce0f2360952c4928013
train_001.jsonl
1522850700
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told β€” ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
256 megabytes
import java.io.*; import java.util.*; import java.util.regex.*; public class vk18 { public static void main(String[]stp) throws Exception { Scanner scan=new Scanner(System.in); //BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //String []s; int n=scan.nextInt(),i,k=scan.nextInt(),max=Integer.MIN_VALUE,max_sum=0,count=0,sum=0; int a[]=new int[n+1]; a[0]=0; //s=br.readLine().split(" "); for(i=1;i<=n;i++) { a[i]=scan.nextInt(); max_sum+=a[i];} int t[]=new int[n+1]; //s=br.readLine().split(" "); for(i=1;i<=n;i++) { t[i]=scan.nextInt(); if(t[i]==1) {count+=a[i];} } if(k >= n){ System.out.println(max_sum); System.exit(0) ; } for(i=1;i<=k;i++) { if(t[i]==0) sum+=a[i]; } max=Math.max(max,sum); for(i=2;i<=n-k+1;i++) { if(t[i-1]==0) sum-=a[i-1]; if(t[i+k-1]==0) sum+=a[i+k-1]; //System.out.println(sum); max=Math.max(max,sum); } System.out.println(count+max); } }
Java
["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"]
1 second
["16"]
NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
Java 8
standard input
[ "dp", "two pointers", "implementation", "data structures" ]
0fbac68f497fe189ee088c13d0488cce
The first line of the input contains two integer numbers n and k (1 ≀ k ≀ n ≀ 105) β€” the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 104) β€” the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≀ ti ≀ 1) β€” type of Mishka's behavior at the i-th minute of the lecture.
1,200
Print only one integer β€” the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
standard output
PASSED
0a8868de10cc178fb6e13744a042d61c
train_001.jsonl
1522850700
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told β€” ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
256 megabytes
import java.util.*; import java.io.*; public class CFQB { public static void main(String args[]) throws Exception { Scan scan = new Scan(); Print print = new Print(); int N=scan.scanInt(); int K=scan.scanInt(); int arr[] = new int[N]; int t[] = new int[N]; for (int i = 0; i < N; i++) { arr[i] = scan.scanInt(); } for (int i = 0; i < N; i++) { t[i] = scan.scanInt(); } long ones=0; long fact=0; for(int i=0;i<N;i++) { if(t[i]==1) { ones+=arr[i]; arr[i]=0; } } long ans=0; for (int i = 0; i < N; i++) { fact+=arr[i]; if(i>=K) { fact-=arr[i-K]; } ans=Math.max(fact+ones,ans); } print.println(ans); print.close(); } static class Print { private final BufferedWriter bw; public Print() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } static class Scan { private byte[] buf = new byte[1024 * 1024 * 4]; private int index; private InputStream in; private int total; public Scan() { in = System.in; } public int scan() throws IOException { if (total < 0) throw new InputMismatchException(); if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) return -1; } return buf[index++]; } public int scanInt() throws IOException { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } else throw new InputMismatchException(); } return neg * integer; } public double scanDouble() throws IOException { double doub = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n) && n != '.') { if (n >= '0' && n <= '9') { doub *= 10; doub += n - '0'; n = scan(); } else throw new InputMismatchException(); } if (n == '.') { n = scan(); double temp = 1; while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { temp /= 10; doub += (n - '0') * temp; n = scan(); } else throw new InputMismatchException(); } } return doub * neg; } public long scanLong() throws IOException { long ret = 0; long c = scan(); while (c <= ' ') { c = scan(); } boolean neg = (c == '-'); if (neg) { c = scan(); } do { ret = ret * 10 + c - '0'; } while ((c = scan()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public String scanString() throws IOException { StringBuilder sb = new StringBuilder(); int n = scan(); while (isWhiteSpace(n)) n = scan(); while (!isWhiteSpace(n) || n == ' ') { sb.append((char) n); n = scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; return false; } } }
Java
["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"]
1 second
["16"]
NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
Java 8
standard input
[ "dp", "two pointers", "implementation", "data structures" ]
0fbac68f497fe189ee088c13d0488cce
The first line of the input contains two integer numbers n and k (1 ≀ k ≀ n ≀ 105) β€” the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 104) β€” the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≀ ti ≀ 1) β€” type of Mishka's behavior at the i-th minute of the lecture.
1,200
Print only one integer β€” the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
standard output
PASSED
b325d00781949061c3b7ac693ada69e7
train_001.jsonl
1522850700
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told β€” ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
256 megabytes
import java.util.Scanner; /** * Created by Kirill on 04.04.2018. */ public class B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int K = sc.nextInt(); int[] a = new int[N]; int[] t = new int[N]; for(int i = 0; i < N; i++){ a[i] = sc.nextInt(); } long result = 0L; for(int i = 0; i < N; i++){ t[i] = sc.nextInt(); if(t[i] == 1){ result+=(long)a[i]; } } int max = 0; for(int i = 0; i < K; i++){ if(t[i] == 0){ max+=a[i]; } } int max_res = max; for(int i = K, p = 0; i < N; i++, p++){ if(t[i] == 0){ max+=a[i]; } if(t[p] == 0){ max-=a[p]; } max_res = Math.max(max_res, max); } System.out.println(result+(long)max_res); } }
Java
["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"]
1 second
["16"]
NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
Java 8
standard input
[ "dp", "two pointers", "implementation", "data structures" ]
0fbac68f497fe189ee088c13d0488cce
The first line of the input contains two integer numbers n and k (1 ≀ k ≀ n ≀ 105) β€” the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 104) β€” the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≀ ti ≀ 1) β€” type of Mishka's behavior at the i-th minute of the lecture.
1,200
Print only one integer β€” the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
standard output
PASSED
4ef30e7d2a2849491aec831e5faed809
train_001.jsonl
1522850700
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told β€” ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
256 megabytes
import java.io.*; import java.util.*; public class p961B { public static void main(String args[]) throws Exception { Scanner cin=new Scanner(System.in); String[] line = cin.nextLine().split(" "); int[] firstLine = new int[2]; for (int i=0; i<2; i++){ firstLine[i]=Integer.parseInt(line[i]); } int n = firstLine[0]; int k = firstLine[1]; int[] theorems = new int[n]; int[] status = new int[n]; line = cin.nextLine().split(" "); for (int j = 0; j < n; j++) { theorems[j] = Integer.parseInt(line[j]); } line = cin.nextLine().split(" "); for (int j = 0; j < n; j++) { status[j] = Integer.parseInt(line[j]); } if (n==1) {System.out.println( theorems[0]); return;} //System.out.println(Arrays.toString(status)); int sum = 0; int max = 0; for (int i=0; i<n; i++) {sum += theorems[i]*status[i];} for (int i=0; i<k; i++) {if (status[i]==0) sum += theorems[i];} max = sum; for (int i=0; i<n-k; i++){ int newSum = sum; if (status[i]==0) {newSum -= theorems[i];} if (status[i+k]==0) {newSum += theorems[i + k];} sum = newSum; if (sum>=max) max = sum; //System.out.println(sum); } System.out.println(max); } }
Java
["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"]
1 second
["16"]
NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
Java 8
standard input
[ "dp", "two pointers", "implementation", "data structures" ]
0fbac68f497fe189ee088c13d0488cce
The first line of the input contains two integer numbers n and k (1 ≀ k ≀ n ≀ 105) β€” the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 104) β€” the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≀ ti ≀ 1) β€” type of Mishka's behavior at the i-th minute of the lecture.
1,200
Print only one integer β€” the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
standard output
PASSED
e4cef68fe0f365ef42ae6aa23e5ac804
train_001.jsonl
1522850700
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told β€” ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
256 megabytes
import org.omg.CORBA.MARSHAL; import java.awt.event.InputEvent; import java.awt.image.AreaAveragingScaleFilter; import java.io.*; import java.net.CookieHandler; import java.util.*; import java.math.*; import java.lang.*; public class Main implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Main(),"Main",1<<26).start(); } static long gcd(long a,long b){ if(b==0)return a;return gcd(b,a%b); } static long modPow(long a,long p,long m){ if(a==1)return 1;long ans=1;while (p>0){ if(p%2==1)ans=(ans*a)%m;a=(a*a)%m;p>>=1; }return ans; } static long modInv(long a,long m){return modPow(a,m-2,m);} public void run() { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n=sc.nextInt(); int k=sc.nextInt(); int a[]=new int[n+1]; int b[]=new int[n+1]; long dp[]=new long[n+1]; for (int i = 1; i <=n ; i++) { a[i]=sc.nextInt(); } for (int i = 1; i <=n ; i++) { b[i]=sc.nextInt(); } for (int i = 1; i <=n ; i++) { if(b[i]==1){ dp[i]=dp[i-1]+a[i]; } else{ dp[i]=dp[i-1]; } } int l=1,r=k;long sum=0; for (int i = l; i <=k ; i++) { sum+=a[i]; } long max=0; for (int i = 1; i <=n-k+1 ; i++) { max=Math.max(max,sum+dp[i-1]+(dp[n]-dp[r])); if(i<n-k+1) { sum -= a[l++]; sum += a[++r]; } } out.println(max); out.close(); } }
Java
["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"]
1 second
["16"]
NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
Java 8
standard input
[ "dp", "two pointers", "implementation", "data structures" ]
0fbac68f497fe189ee088c13d0488cce
The first line of the input contains two integer numbers n and k (1 ≀ k ≀ n ≀ 105) β€” the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 104) β€” the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≀ ti ≀ 1) β€” type of Mishka's behavior at the i-th minute of the lecture.
1,200
Print only one integer β€” the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
standard output
PASSED
b68551791b4b1d33bc2fa198e6af3dce
train_001.jsonl
1522850700
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told β€” ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class B_educ_41 { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int k = scn.nextInt(); int[] as = new int[n]; int[] ts = new int[n]; for(int i = 0; i < n; i++) { as[i] = scn.nextInt(); } for(int i = 0; i < n; i++) { ts[i] = scn.nextInt(); } long[] sums = new long[n]; long[] s2 = new long[n]; Arrays.fill(sums, 0); Arrays.fill(sums, 0); int i = n-1, j = n-1; sums[j] = as[j]; s2[j] = ts[j] == 1 ? as[j] : 0; j--; while(j >= 0) { sums[j] = sums[j+1]; s2[j] = s2[j+1]; s2[j] += ts[j] == 1 ? as[j] : 0; sums[j] += as[j]; if(i-j >= k) { sums[j] -= as[i]; s2[j] -= ts[i] == 1 ? as[i] : 0; i--; } j--; } long max = 0, maxDif = 0, maxIdx = -1; for(i = 0; i <= n-k; i++) { // System.out.println(max+" _ "+maxIdx+" "+i+" "+s2[i]+" "+sums[i]); if(sums[i]-s2[i] > maxDif) { maxDif = sums[i]-s2[i]; max = sums[i]; maxIdx = i; } } long res = 0; for(i = 0; i < n; i++) { if(i == maxIdx) { res += max; i+= k-1; continue; } if(ts[i] == 1) { res += as[i]; } } System.out.println(res); } }
Java
["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"]
1 second
["16"]
NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
Java 8
standard input
[ "dp", "two pointers", "implementation", "data structures" ]
0fbac68f497fe189ee088c13d0488cce
The first line of the input contains two integer numbers n and k (1 ≀ k ≀ n ≀ 105) β€” the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 104) β€” the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≀ ti ≀ 1) β€” type of Mishka's behavior at the i-th minute of the lecture.
1,200
Print only one integer β€” the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
standard output
PASSED
9996d37b128337c3b98ea078bdca2f51
train_001.jsonl
1522850700
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told β€” ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
256 megabytes
import java.util.*; import java.io.*; public class lecture { public static void main(String[]args) throws IOException{ BufferedReader kb = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer line = new StringTokenizer(kb.readLine()); int n = Integer.parseInt(line.nextToken()), k = Integer.parseInt(line.nextToken()); long[] a = new long[n]; boolean[] t = new boolean[n]; line = new StringTokenizer(kb.readLine()); for(int i =0;i<n;i++) a[i] = Integer.parseInt(line.nextToken()); line = new StringTokenizer(kb.readLine()); long sum = 0; for(int i =0;i<n;i++){ t[i] = Integer.parseInt(line.nextToken())==1; if(t[i]){ sum+=a[i]; a[i] = 0; } } long [] cs = new long[n]; cs[0] = a[0]; long max =cs[0]; for(int i = 1;i<n;i++){ cs[i] = cs[i-1] +a[i]; max = Math.max(i>=k?cs[i]-cs[i-k]:cs[i], max); } System.out.println(max+sum); } } /* 1 3 5 2 5 4 1 1 0 1 0 0 sum = 6 k = 3 0 1 2 3 4 5 a = {0 0 5 0 5 4} a = {0 0 5 5 10 9} */
Java
["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"]
1 second
["16"]
NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
Java 8
standard input
[ "dp", "two pointers", "implementation", "data structures" ]
0fbac68f497fe189ee088c13d0488cce
The first line of the input contains two integer numbers n and k (1 ≀ k ≀ n ≀ 105) β€” the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 104) β€” the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≀ ti ≀ 1) β€” type of Mishka's behavior at the i-th minute of the lecture.
1,200
Print only one integer β€” the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
standard output
PASSED
d6ff7f59dbad0c1382fc5e72ad43e5fa
train_001.jsonl
1522850700
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told β€” ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
256 megabytes
import java.io.*; import java.util.*; public class pishty { public static void main(String[] args)throws IOException { //InputStreamReader read=new InputStreamReader(System.in); //BufferedReader in=new BufferedReader(read); FastReader in=new FastReader(); PrintWriter pw=new PrintWriter(System.out, true); //int n=Integer.parseInt(in.readLine()); int n=in.nextInt(); int k=in.nextInt(); int arr[]=new int[n]; for(int i=0;i<n;i++) arr[i]=in.nextInt(); int sleep[]=new int[n]; for(int i=0;i<n;i++) sleep[i]=in.nextInt(); int st=0,end=0; int max=0; for(int i=0;i<k;i++) if(sleep[i]==0) max+=arr[i]; int sum=max; for(int i=k;i<n;i++) { if(sleep[i]==0) sum+=arr[i]; if(sleep[i-k]==0) sum-=arr[i-k]; max=Math.max(max,sum); // pw.println(sum+"\t"+max); } int ans=max; for(int i=0;i<n;i++) { if(sleep[i]==1) ans+=arr[i]; } pw.println(ans); } } 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
["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"]
1 second
["16"]
NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
Java 8
standard input
[ "dp", "two pointers", "implementation", "data structures" ]
0fbac68f497fe189ee088c13d0488cce
The first line of the input contains two integer numbers n and k (1 ≀ k ≀ n ≀ 105) β€” the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 104) β€” the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≀ ti ≀ 1) β€” type of Mishka's behavior at the i-th minute of the lecture.
1,200
Print only one integer β€” the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
standard output
PASSED
5faec450595d23f01e1aa93a5c9d5263
train_001.jsonl
1522850700
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told β€” ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author el-Bishoy */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(), k = in.nextInt(); int max = 0, current = 0; int days[] = in.nextIntArrayIndexedByOne(n + 1); int t[] = in.nextIntArrayIndexedByOne(n + 1); int sum[] = new int[n + 1]; for (int j = 1; j <= n; j++) { sum[j] = sum[j - 1] + t[j] * +days[j]; } int i = 1; for (; i <= k; i++) { current += days[i]; } max = sum[n]; int headPtr = 1; int right = sum[n] - sum[i - 1]; int left = sum[headPtr - 1]; max = Math.max(max, current + right + left); for (; headPtr <= n - k; i++, headPtr++) { right = sum[n] - sum[i]; left = sum[headPtr]; current = current - days[headPtr] + days[i]; int totalSum = right + left + current; max = Math.max(max, totalSum); } out.println(max); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int[] nextIntArrayIndexedByOne(int n) { int[] array = new int[n]; for (int i = 1; i < n; ++i) array[i] = nextInt(); return array; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } }
Java
["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"]
1 second
["16"]
NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
Java 8
standard input
[ "dp", "two pointers", "implementation", "data structures" ]
0fbac68f497fe189ee088c13d0488cce
The first line of the input contains two integer numbers n and k (1 ≀ k ≀ n ≀ 105) β€” the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 104) β€” the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≀ ti ≀ 1) β€” type of Mishka's behavior at the i-th minute of the lecture.
1,200
Print only one integer β€” the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
standard output
PASSED
c1f0f8ae742831f78bde08ca798ff525
train_001.jsonl
1522850700
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told β€” ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int total_time = sc.nextInt(); int k = sc.nextInt(); int[] original = new int[total_time]; for(int i = 0; i < total_time; i++) { original[i] = sc.nextInt(); } int[] B = new int[total_time]; for(int j = 0; j < total_time; j++) { B[j] = sc.nextInt(); } int[] T = new int[total_time]; T[0] = original[0]; for(int i = 1; i < total_time; i++) { T[i] = original[i] + T[i - 1]; } int[] M = new int[total_time]; if(B[0] == 1) M[0] = original[0]; for(int i = 1; i < total_time; i++) { M[i] = M[i - 1] + B[i] * original[i]; } int global_max = 0; //First int local_max = T[k - 1] + M[total_time - 1] - M[k - 1]; global_max = local_max; for(int i = 1; i < total_time - k; i++) { local_max = M[i-1] + (T[i+k-1] - T[i-1]) + (M[total_time - 1] - M[i+k-1]); global_max = Math.max(global_max, local_max); } //End local_max = M[Math.max(0, total_time - k - 1)] + T[total_time - 1] - T[Math.max(0, total_time - k - 1)]; global_max = Math.max(global_max, local_max); System.out.println(global_max); } }
Java
["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"]
1 second
["16"]
NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
Java 8
standard input
[ "dp", "two pointers", "implementation", "data structures" ]
0fbac68f497fe189ee088c13d0488cce
The first line of the input contains two integer numbers n and k (1 ≀ k ≀ n ≀ 105) β€” the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 104) β€” the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≀ ti ≀ 1) β€” type of Mishka's behavior at the i-th minute of the lecture.
1,200
Print only one integer β€” the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
standard output
PASSED
a2165702eaa86600806cadbc87f3fd88
train_001.jsonl
1522850700
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told β€” ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
256 megabytes
import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); // duration of lecture int k = in.nextInt(); // time to keep awake int [] tabn = new int [n]; int [] behav= new int[n]; for (int i = 0 ; i < n ; i++) { tabn[i] = in.nextInt(); } for (int i = 0 ; i < n ; i++) { behav[i] = in.nextInt(); } int sum = 0 , maxScore = 0 , nbreMagic = 0 ; for (int i = 0 ; i < n ; i++) { sum = sum + tabn[i]*behav[i] ; } for (int i = 0 ; i <k ; i++) { if ( behav[i] == 0) { maxScore += tabn[i]; /*for (int j = i ; j < i+k ; j++) { maxScore = maxScore + tabn[i] ; } nbreMagic = i ;*/ } //break; } nbreMagic = maxScore ; for (int i = 1 ; i < n-k +1 ; i++) { if (behav[i-1] == 0 ) { nbreMagic -= tabn[i-1]; } if(behav[i+k-1] == 0) { nbreMagic += tabn[i+k-1]; } if(nbreMagic > maxScore) { maxScore = nbreMagic; } } /*for (int i = nbreMagic+1 ; i < n ; i++) { if ( behav[i] == 0) { int maxTemp = 0 ; maxTemp = maxScore + tabn[i] - tabn[nbreMagic] ; if(maxTemp > maxScore) { maxScore = maxTemp ; nbreMagic = i ; } } }*/ /*for ( int i = nbreMagic ; i < nbreMagic+ k ; i++ ) { if (behav[i] == 0 )sum = sum + tabn[i] ; }*/ System.out.println(sum+maxScore); } }
Java
["6 3\n1 3 5 2 5 4\n1 1 0 1 0 0"]
1 second
["16"]
NoteIn the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
Java 8
standard input
[ "dp", "two pointers", "implementation", "data structures" ]
0fbac68f497fe189ee088c13d0488cce
The first line of the input contains two integer numbers n and k (1 ≀ k ≀ n ≀ 105) β€” the duration of the lecture in minutes and the number of minutes you can keep Mishka awake. The second line of the input contains n integer numbers a1, a2, ... an (1 ≀ ai ≀ 104) β€” the number of theorems lecturer tells during the i-th minute. The third line of the input contains n integer numbers t1, t2, ... tn (0 ≀ ti ≀ 1) β€” type of Mishka's behavior at the i-th minute of the lecture.
1,200
Print only one integer β€” the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
standard output
PASSED
de1fcb94b4b01a2f74e497bcdb8f6669
train_001.jsonl
1348500600
There are n piles of stones of sizes a1, a2, ..., an lying on the table in front of you.During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of the added pile.Your task is to determine the minimum cost at which you can gather all stones in one pile. To add some challenge, the stone piles built up conspiracy and decided that each pile will let you add to it not more than k times (after that it can only be added to another pile). Moreover, the piles decided to puzzle you completely and told you q variants (not necessarily distinct) of what k might equal. Your task is to find the minimum cost for each of q variants.
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.Arrays; import java.util.StringTokenizer; public class Main { // 1 1 1 1 1 1 1 1 5 public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); long[] a = new long[n + 1]; for(int i = 1; i <= n; ++i) a[i] = sc.nextInt(); shuffle(a); Arrays.sort(a); for(int i = 1; i <= n; ++i) a[i] += a[i - 1]; long[] ans = new long[n]; for(int k = 1; k < n; ++k) for(long i = n - 1, j = 1, g = 1; i > 0; i -= k * g, ++j, g *= k) ans[k] += j * (a[(int)i] - a[(int)Math.max(i - k * g, 0)]); int q = sc.nextInt(); while(q-->0) { int k = sc.nextInt(); if(k >= n) out.print(a[n - 1] + " "); else out.print(ans[k] + " "); } out.flush(); out.close(); } static void shuffle(long[] a) { int n = a.length; for(int i = 0; i < n; ++i) { int r = i + (int)(Math.random() * (n - i)); long tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
Java
["5\n2 3 4 1 1\n2\n2 3"]
2 seconds
["9 8"]
NoteIn the first sample one way to get the optimal answer goes like this: we add in turns the 4-th and the 5-th piles to the 2-nd one; then we add the 1-st pile to the 3-rd one; we add the 2-nd pile to the 3-rd one. The first two operations cost 1 each; the third one costs 2, the fourth one costs 5 (the size of the 2-nd pile after the first two operations is not 3, it already is 5). In the second sample you can add the 2-nd pile to the 3-rd one (the operations costs 3); then the 1-st one to the 3-th one (the cost is 2); then the 5-th one to the 4-th one (the costs is 1); and at last, the 4-th one to the 3-rd one (the cost is 2).
Java 8
standard input
[ "greedy" ]
87045c4df69110642122f2c114476947
The first line contains integer n (1 ≀ n ≀ 105) β€” the number of stone piles. The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the initial sizes of the stone piles. The third line contains integer q (1 ≀ q ≀ 105) β€” the number of queries. The last line contains q space-separated integers k1, k2, ..., kq (1 ≀ ki ≀ 105) β€” the values of number k for distinct queries. Note that numbers ki can repeat.
1,900
Print q whitespace-separated integers β€” the answers to the queries in the order, in which the queries are given in the input. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
9941ea56b91cf598beb63d20563299cd
train_001.jsonl
1348500600
There are n piles of stones of sizes a1, a2, ..., an lying on the table in front of you.During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of the added pile.Your task is to determine the minimum cost at which you can gather all stones in one pile. To add some challenge, the stone piles built up conspiracy and decided that each pile will let you add to it not more than k times (after that it can only be added to another pile). Moreover, the piles decided to puzzle you completely and told you q variants (not necessarily distinct) of what k might equal. Your task is to find the minimum cost for each of q variants.
256 megabytes
import java.io.*; import java.util.*; public class A { public static void main(String[] args)throws Throwable { MyScanner sc=new MyScanner(); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(); long [] a=new long [n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); Arrays.sort(a); for(int i=1;i<n;i++) a[i]+=a[i-1]; long [] b=new long [n]; for(int i=1;i<n;i++){ long idx=n-2; long shift=i; while(idx>=0){ b[i]+=a[(int)idx]; idx-=shift; shift*=i; } } // System.out.println(Arrays.toString(b)); int q=sc.nextInt(); while(q-->0){ int k=sc.nextInt(); if(k>=n-1){ if(n>1) pw.print(a[n-2]+" "); else pw.print("0 "); } else{ pw.print(b[k]+" "); } } pw.flush(); pw.close(); } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { try { br = new BufferedReader(new FileReader(new File("group.in"))); } catch (FileNotFoundException e) { br = new BufferedReader(new InputStreamReader(System.in)); } } String next() {while (st == null || !st.hasMoreElements()) { try {st = new StringTokenizer(br.readLine());} catch (IOException e) {e.printStackTrace();}} return st.nextToken();} int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble() {return Double.parseDouble(next());} String nextLine(){String str = ""; try {str = br.readLine();} catch (IOException e) {e.printStackTrace();} return str;} } }
Java
["5\n2 3 4 1 1\n2\n2 3"]
2 seconds
["9 8"]
NoteIn the first sample one way to get the optimal answer goes like this: we add in turns the 4-th and the 5-th piles to the 2-nd one; then we add the 1-st pile to the 3-rd one; we add the 2-nd pile to the 3-rd one. The first two operations cost 1 each; the third one costs 2, the fourth one costs 5 (the size of the 2-nd pile after the first two operations is not 3, it already is 5). In the second sample you can add the 2-nd pile to the 3-rd one (the operations costs 3); then the 1-st one to the 3-th one (the cost is 2); then the 5-th one to the 4-th one (the costs is 1); and at last, the 4-th one to the 3-rd one (the cost is 2).
Java 8
standard input
[ "greedy" ]
87045c4df69110642122f2c114476947
The first line contains integer n (1 ≀ n ≀ 105) β€” the number of stone piles. The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the initial sizes of the stone piles. The third line contains integer q (1 ≀ q ≀ 105) β€” the number of queries. The last line contains q space-separated integers k1, k2, ..., kq (1 ≀ ki ≀ 105) β€” the values of number k for distinct queries. Note that numbers ki can repeat.
1,900
Print q whitespace-separated integers β€” the answers to the queries in the order, in which the queries are given in the input. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
e62bceb2c596f5741d4fbb7fac528211
train_001.jsonl
1348500600
There are n piles of stones of sizes a1, a2, ..., an lying on the table in front of you.During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of the added pile.Your task is to determine the minimum cost at which you can gather all stones in one pile. To add some challenge, the stone piles built up conspiracy and decided that each pile will let you add to it not more than k times (after that it can only be added to another pile). Moreover, the piles decided to puzzle you completely and told you q variants (not necessarily distinct) of what k might equal. Your task is to find the minimum cost for each of q variants.
256 megabytes
import java.util.Arrays; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Comparator; import java.io.IOException; import java.util.StringTokenizer; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { private int n, q; private Integer[] a; private long[] sum; private long res1; private StringBuffer res; public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); a = new Integer[n]; for(int i = 0; i < n; ++i) a[i] = in.nextInt(); Arrays.sort(a, new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return o2 - o1; } }); sum = new long[n]; sum[0] = a[0]; for(int i = 1; i < n; ++i) sum[i] = sum[i - 1] + a[i]; for(int i = 1; i < n; ++i) res1 += (long) a[i] * i; q = in.nextInt(); res = new StringBuffer(); while (q-- > 0) { int k = in.nextInt(); if (k == 1) { res.append(res1).append(" "); continue; } long rr = 0; long len = 1; for(long i = 1, l = 1; i < n; i += len, ++l) { len = len * k; long j = Math.min((long) n - 1, i + len - 1); rr += (long) (sum[(int) j] - sum[((int) (i - 1))]) * l; } res.append(rr).append(" "); } out.println(res.toString()); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } catch (Exception e) { throw new UnknownError(e.getMessage()); } } public int nextInt() { return Integer.parseInt(next()); } }
Java
["5\n2 3 4 1 1\n2\n2 3"]
2 seconds
["9 8"]
NoteIn the first sample one way to get the optimal answer goes like this: we add in turns the 4-th and the 5-th piles to the 2-nd one; then we add the 1-st pile to the 3-rd one; we add the 2-nd pile to the 3-rd one. The first two operations cost 1 each; the third one costs 2, the fourth one costs 5 (the size of the 2-nd pile after the first two operations is not 3, it already is 5). In the second sample you can add the 2-nd pile to the 3-rd one (the operations costs 3); then the 1-st one to the 3-th one (the cost is 2); then the 5-th one to the 4-th one (the costs is 1); and at last, the 4-th one to the 3-rd one (the cost is 2).
Java 8
standard input
[ "greedy" ]
87045c4df69110642122f2c114476947
The first line contains integer n (1 ≀ n ≀ 105) β€” the number of stone piles. The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the initial sizes of the stone piles. The third line contains integer q (1 ≀ q ≀ 105) β€” the number of queries. The last line contains q space-separated integers k1, k2, ..., kq (1 ≀ ki ≀ 105) β€” the values of number k for distinct queries. Note that numbers ki can repeat.
1,900
Print q whitespace-separated integers β€” the answers to the queries in the order, in which the queries are given in the input. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
c4510579d3f2da71655b425208fe7d66
train_001.jsonl
1348500600
There are n piles of stones of sizes a1, a2, ..., an lying on the table in front of you.During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of the added pile.Your task is to determine the minimum cost at which you can gather all stones in one pile. To add some challenge, the stone piles built up conspiracy and decided that each pile will let you add to it not more than k times (after that it can only be added to another pile). Moreover, the piles decided to puzzle you completely and told you q variants (not necessarily distinct) of what k might equal. Your task is to find the minimum cost for each of q variants.
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.Arrays; import java.util.StringTokenizer; public class B { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = sc.nextInt(); Arrays.sort(a); long[] preSum = new long[n]; preSum[0] = a[0]; for(int i = 1; i < n; i++) preSum[i] = preSum[i - 1] + a[i]; int[] from = new int[n], to = new int[n]; long[] dp = new long[100000+1]; if(n != 1) {Arrays.fill(dp, -1);} int factor[] = new int[n]; int q = sc.nextInt(); for(int i = 0; i < q; i++) { int k = sc.nextInt(); int roots = n / k + (n % k > 1? 1 : 0); if(k == 1) roots = n-1; int start = n - roots; if(dp[k] != -1) out.print(dp[k] + " "); else { int idx = n-2, fac = 1, len = 1; for(int j = n-1; j > start; j--) { to[j] = idx; from[j] = idx - k + 1; idx = from[j] - 1; factor[j] = fac; if(--len == 0){fac++; len = (int)Math.pow(k, fac-1);} } from[start] = 0; to[start] = idx; factor[start] = fac; long ans = 0; for(int j = start; j < n; j++) { long sum = preSum[to[j]]; if(from[j] - 1 >= 0) sum -= preSum[from[j] - 1]; sum *= factor[j]; ans += sum; } out.print((dp[k] = ans) + " "); } } out.println(); 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
["5\n2 3 4 1 1\n2\n2 3"]
2 seconds
["9 8"]
NoteIn the first sample one way to get the optimal answer goes like this: we add in turns the 4-th and the 5-th piles to the 2-nd one; then we add the 1-st pile to the 3-rd one; we add the 2-nd pile to the 3-rd one. The first two operations cost 1 each; the third one costs 2, the fourth one costs 5 (the size of the 2-nd pile after the first two operations is not 3, it already is 5). In the second sample you can add the 2-nd pile to the 3-rd one (the operations costs 3); then the 1-st one to the 3-th one (the cost is 2); then the 5-th one to the 4-th one (the costs is 1); and at last, the 4-th one to the 3-rd one (the cost is 2).
Java 8
standard input
[ "greedy" ]
87045c4df69110642122f2c114476947
The first line contains integer n (1 ≀ n ≀ 105) β€” the number of stone piles. The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the initial sizes of the stone piles. The third line contains integer q (1 ≀ q ≀ 105) β€” the number of queries. The last line contains q space-separated integers k1, k2, ..., kq (1 ≀ ki ≀ 105) β€” the values of number k for distinct queries. Note that numbers ki can repeat.
1,900
Print q whitespace-separated integers β€” the answers to the queries in the order, in which the queries are given in the input. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
b9a4ab71f38995b8c56d49bd7b86e93e
train_001.jsonl
1348500600
There are n piles of stones of sizes a1, a2, ..., an lying on the table in front of you.During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of the added pile.Your task is to determine the minimum cost at which you can gather all stones in one pile. To add some challenge, the stone piles built up conspiracy and decided that each pile will let you add to it not more than k times (after that it can only be added to another pile). Moreover, the piles decided to puzzle you completely and told you q variants (not necessarily distinct) of what k might equal. Your task is to find the minimum cost for each of q variants.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { IIO io; Main(IIO io) { this.io = io; } public static void main(String[] args) throws IOException { ConsoleIO io = new ConsoleIO(); Main m = new Main(io); m.solve(); io.flush(); // Tester test = new Tester();test.run(); } public void solve() { int n = Integer.parseInt(io.readLine()); int[] aa = io.readIntArray(); int q = Integer.parseInt(io.readLine()); int[] qq = io.readIntArray(); Arrays.sort(aa); long[] sum = new long[n + 1]; for (int i = 1; i <= n; i++) sum[i] = aa[i - 1] + sum[i - 1]; long[] cache = new long[100007]; for (int t = 0; t < q; t++) { int v = qq[t]; if (cache[v] > 0) { io.writeWord(Long.toString(cache[v]) + " "); } else { long x = 1; long res = 0; for (long z = aa.length - 1; z >= 0; ) { res += sum[(int)z]; x *= v; z -= x; } cache[v] = res; io.writeWord(Long.toString(cache[v]) + " "); } } } } class ConsoleIO extends BaseIO { BufferedReader br; PrintWriter out; public ConsoleIO(){ br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } public void flush(){ this.out.close(); } public void writeLine(String s) { this.out.println(s); } public void writeInt(int a) { this.out.print(a); this.out.print(' '); } public void writeWord(String s){ this.out.print(s); } public String readLine() { try { return br.readLine(); } catch (Exception ex){ return ""; } } public int read(){ try { return br.read(); } catch (Exception ex){ return -1; } } } abstract class BaseIO implements IIO { public long readLong() { return Long.parseLong(this.readLine()); } public int readInt() { return Integer.parseInt(this.readLine()); } public int[] readIntArray() { String line = this.readLine(); String[] nums = line.split(" "); int[] res = new int[nums.length]; for (int i = 0; i < nums.length; i++) { res[i] = Integer.parseInt(nums[i]); } return res; } public long[] readLongArray() { String line = this.readLine(); String[] nums = line.split(" "); long[] res = new long[nums.length]; for (int i = 0; i < nums.length; i++) { res[i] = Long.parseLong(nums[i]); } return res; } } interface IIO { void writeLine(String s); void writeInt(int a); void writeWord(String s); String readLine(); long readLong(); int readInt(); int read(); int[] readIntArray(); long[] readLongArray(); }
Java
["5\n2 3 4 1 1\n2\n2 3"]
2 seconds
["9 8"]
NoteIn the first sample one way to get the optimal answer goes like this: we add in turns the 4-th and the 5-th piles to the 2-nd one; then we add the 1-st pile to the 3-rd one; we add the 2-nd pile to the 3-rd one. The first two operations cost 1 each; the third one costs 2, the fourth one costs 5 (the size of the 2-nd pile after the first two operations is not 3, it already is 5). In the second sample you can add the 2-nd pile to the 3-rd one (the operations costs 3); then the 1-st one to the 3-th one (the cost is 2); then the 5-th one to the 4-th one (the costs is 1); and at last, the 4-th one to the 3-rd one (the cost is 2).
Java 8
standard input
[ "greedy" ]
87045c4df69110642122f2c114476947
The first line contains integer n (1 ≀ n ≀ 105) β€” the number of stone piles. The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the initial sizes of the stone piles. The third line contains integer q (1 ≀ q ≀ 105) β€” the number of queries. The last line contains q space-separated integers k1, k2, ..., kq (1 ≀ ki ≀ 105) β€” the values of number k for distinct queries. Note that numbers ki can repeat.
1,900
Print q whitespace-separated integers β€” the answers to the queries in the order, in which the queries are given in the input. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
507c0e5cca500c24427f8ee365482b8e
train_001.jsonl
1348500600
There are n piles of stones of sizes a1, a2, ..., an lying on the table in front of you.During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of the added pile.Your task is to determine the minimum cost at which you can gather all stones in one pile. To add some challenge, the stone piles built up conspiracy and decided that each pile will let you add to it not more than k times (after that it can only be added to another pile). Moreover, the piles decided to puzzle you completely and told you q variants (not necessarily distinct) of what k might equal. Your task is to find the minimum cost for each of q variants.
256 megabytes
import java.io.*; import java.util.*; public class D implements Runnable{ public static void main (String[] args) {new Thread(null, new D(), "_cf", 1 << 28).start();} public void run() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println("Go!"); int n = fs.nextInt(); int[] a = fs.nextIntArray(n); sort(a); Fenwick_Tree ft = new Fenwick_Tree(n); for(int i = 0; i < n; i++) ft.update(i+1, a[i]); long[] rep = new long[n + 1]; Arrays.fill(rep, -1); rep[n-1] = 0; for(int i = 0; i < n-1; i++) rep[n-1] += a[i]; int q = fs.nextInt(); for(int qq = 0; qq < q; qq++) { if(qq > 0) out.print(" "); int k = fs.nextInt(); if(k >= n) k = n - 1; if(rep[k] != -1) { out.print(rep[k]); continue; } rep[k] = 0; int at = n-2; long len = k; long mult = 1; while(at >= 0) { // System.out.println("At " + at + " len " + len); //query sum from at to at-len int p1 = at + 1, p2 = at - (int)len + 1; p2 = Math.max(0, p2); rep[k] += mult * (ft.sum(p1) - ft.sum(p2)); // System.out.println("Query " + p1 + " to " + p2 + " sum " + (ft.sum(p1) - ft.sum(p2)) + " mult " + mult); if(p2 == 0) break; len *= k; if(len > Integer.MAX_VALUE) len = Integer.MAX_VALUE / 2; mult++; at = --p2; } out.print(rep[k]); } out.close(); } class Fenwick_Tree { long[] bit; int n; public Fenwick_Tree(int a) { n = a + 1; bit = new long[n]; } //Remember that when querying a sum to query the 1-based index of the value. void update (int index, long val) { while(index < n) { bit[index] += val; index += (index & (-index)); } } long sum (int index) { long sum = 0; while(index > 0) { sum += bit[index]; index -= (index & (-index)); } return sum; } } void sort (int[] a) { int n = a.length; for(int i = 0; i < 1000; i++) { Random r = new Random(); int x = r.nextInt(n), y = r.nextInt(n); int temp = a[x]; a[x] = a[y]; a[y] = temp; } Arrays.sort(a); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new FileReader("testdata.out")); st = new StringTokenizer(""); } catch (Exception e){e.printStackTrace();} } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try {st = new StringTokenizer(br.readLine());} catch (Exception e) {e.printStackTrace();} return st.nextToken(); } public int nextInt() {return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() { String line = ""; try {line = br.readLine();} catch (Exception e) {e.printStackTrace();} return line; } public Integer[] nextIntegerArray(int n) { Integer[] a = new Integer[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); return a; } public int[] nextIntArray(int n) { int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); return a; } public char[] nextCharArray() {return nextLine().toCharArray();} } }
Java
["5\n2 3 4 1 1\n2\n2 3"]
2 seconds
["9 8"]
NoteIn the first sample one way to get the optimal answer goes like this: we add in turns the 4-th and the 5-th piles to the 2-nd one; then we add the 1-st pile to the 3-rd one; we add the 2-nd pile to the 3-rd one. The first two operations cost 1 each; the third one costs 2, the fourth one costs 5 (the size of the 2-nd pile after the first two operations is not 3, it already is 5). In the second sample you can add the 2-nd pile to the 3-rd one (the operations costs 3); then the 1-st one to the 3-th one (the cost is 2); then the 5-th one to the 4-th one (the costs is 1); and at last, the 4-th one to the 3-rd one (the cost is 2).
Java 8
standard input
[ "greedy" ]
87045c4df69110642122f2c114476947
The first line contains integer n (1 ≀ n ≀ 105) β€” the number of stone piles. The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the initial sizes of the stone piles. The third line contains integer q (1 ≀ q ≀ 105) β€” the number of queries. The last line contains q space-separated integers k1, k2, ..., kq (1 ≀ ki ≀ 105) β€” the values of number k for distinct queries. Note that numbers ki can repeat.
1,900
Print q whitespace-separated integers β€” the answers to the queries in the order, in which the queries are given in the input. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
1d7c4f2ead7ecaa6f738142b30520499
train_001.jsonl
1348500600
There are n piles of stones of sizes a1, a2, ..., an lying on the table in front of you.During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of the added pile.Your task is to determine the minimum cost at which you can gather all stones in one pile. To add some challenge, the stone piles built up conspiracy and decided that each pile will let you add to it not more than k times (after that it can only be added to another pile). Moreover, the piles decided to puzzle you completely and told you q variants (not necessarily distinct) of what k might equal. Your task is to find the minimum cost for each of q variants.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class NaughtyStonePiles { static final int MAX = (int) 1e5 + 1; static long sum(long[] a, long i, long j) { int k = (int) j; if (j > a.length - 1) k = a.length - 1; return a[(int) k] - a[(int) (i - 1)]; } public static void main(String[] args) throws IOException { MyScanner sc = new MyScanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = sc.nextLong(); Arrays.sort(a, (x, y) -> Long.compare(y, x)); long[] pre = new long[n]; pre[0] = a[0]; for (int i = 1; i < n; i++) pre[i] = pre[i - 1] + a[i]; long ans = 0; for (int i = 1; i < n; i++) ans += i * a[i]; long[] cache = new long[MAX]; Arrays.fill(cache, -1); cache[1] = ans; int q = sc.nextInt(); for (int i = 0; i < q; i++) { int k = sc.nextInt(); long res = cache[k] == -1 ? 0 : cache[k]; if (cache[k] == -1) { long t = 1, size = k; for (long j = 1; j < n; j += size, size *= k, t++) res += sum(pre, j, j + size - 1) * t; cache[k] = res; } out.print(res); if (i != q - 1) out.print(" "); } out.println(); out.flush(); out.close(); } static class MyScanner { StringTokenizer st; BufferedReader br; public MyScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public MyScanner(String file) throws IOException { br = new BufferedReader(new FileReader(new File(file))); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["5\n2 3 4 1 1\n2\n2 3"]
2 seconds
["9 8"]
NoteIn the first sample one way to get the optimal answer goes like this: we add in turns the 4-th and the 5-th piles to the 2-nd one; then we add the 1-st pile to the 3-rd one; we add the 2-nd pile to the 3-rd one. The first two operations cost 1 each; the third one costs 2, the fourth one costs 5 (the size of the 2-nd pile after the first two operations is not 3, it already is 5). In the second sample you can add the 2-nd pile to the 3-rd one (the operations costs 3); then the 1-st one to the 3-th one (the cost is 2); then the 5-th one to the 4-th one (the costs is 1); and at last, the 4-th one to the 3-rd one (the cost is 2).
Java 8
standard input
[ "greedy" ]
87045c4df69110642122f2c114476947
The first line contains integer n (1 ≀ n ≀ 105) β€” the number of stone piles. The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the initial sizes of the stone piles. The third line contains integer q (1 ≀ q ≀ 105) β€” the number of queries. The last line contains q space-separated integers k1, k2, ..., kq (1 ≀ ki ≀ 105) β€” the values of number k for distinct queries. Note that numbers ki can repeat.
1,900
Print q whitespace-separated integers β€” the answers to the queries in the order, in which the queries are given in the input. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
f019afdd22becbda586a9bcee5d034e1
train_001.jsonl
1348500600
There are n piles of stones of sizes a1, a2, ..., an lying on the table in front of you.During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of the added pile.Your task is to determine the minimum cost at which you can gather all stones in one pile. To add some challenge, the stone piles built up conspiracy and decided that each pile will let you add to it not more than k times (after that it can only be added to another pile). Moreover, the piles decided to puzzle you completely and told you q variants (not necessarily distinct) of what k might equal. Your task is to find the minimum cost for each of q variants.
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.Arrays; import java.util.Comparator; 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 n = sc.nextInt(); Integer[] v = new Integer[n]; for (int i = 0; i < n; i++) v[i] = sc.nextInt(); Arrays.sort(v, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2 - o1; } }); long[] pre = new long[n]; for (int i = 1; i < pre.length; i++) { pre[i] = pre[i - 1] + v[i]; } long ans[] = new long[n + 1]; for (int i = 1; i <= n; i++) { long k = 1; long acc = 1; long f = 1; for (int j = 1, l = 1; j < n; j+=i, l++) { ans[i] += (pre[Math.min(n - 1, j + i - 1)] - pre[j - 1]) * f; if(l == acc) { k = k * i; acc += k; f++; } } } int q = sc.nextInt(); for (int i = 0; i < q; i++) { int x = sc.nextInt(); if(x > n) out.print(pre[n - 1] + " "); else out.print(ans[x] + " "); } 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
["5\n2 3 4 1 1\n2\n2 3"]
2 seconds
["9 8"]
NoteIn the first sample one way to get the optimal answer goes like this: we add in turns the 4-th and the 5-th piles to the 2-nd one; then we add the 1-st pile to the 3-rd one; we add the 2-nd pile to the 3-rd one. The first two operations cost 1 each; the third one costs 2, the fourth one costs 5 (the size of the 2-nd pile after the first two operations is not 3, it already is 5). In the second sample you can add the 2-nd pile to the 3-rd one (the operations costs 3); then the 1-st one to the 3-th one (the cost is 2); then the 5-th one to the 4-th one (the costs is 1); and at last, the 4-th one to the 3-rd one (the cost is 2).
Java 8
standard input
[ "greedy" ]
87045c4df69110642122f2c114476947
The first line contains integer n (1 ≀ n ≀ 105) β€” the number of stone piles. The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the initial sizes of the stone piles. The third line contains integer q (1 ≀ q ≀ 105) β€” the number of queries. The last line contains q space-separated integers k1, k2, ..., kq (1 ≀ ki ≀ 105) β€” the values of number k for distinct queries. Note that numbers ki can repeat.
1,900
Print q whitespace-separated integers β€” the answers to the queries in the order, in which the queries are given in the input. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
2398c6a6095624ed6d9c998d5ea57504
train_001.jsonl
1348500600
There are n piles of stones of sizes a1, a2, ..., an lying on the table in front of you.During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of the added pile.Your task is to determine the minimum cost at which you can gather all stones in one pile. To add some challenge, the stone piles built up conspiracy and decided that each pile will let you add to it not more than k times (after that it can only be added to another pile). Moreover, the piles decided to puzzle you completely and told you q variants (not necessarily distinct) of what k might equal. Your task is to find the minimum cost for each of q variants.
256 megabytes
import java.io.*; import java.util.*; public class CodeForces { static boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; void runCase(int caseNum) throws IOException { // for (int i = 0; i < 100000; ++i) // out.println("1000000000"); // out.println(); int n = nextInt(); long[] a = new long[n + 1]; for (int i = 0; i < n; ++i) a[i + 1] = nextInt(); Arrays.sort(a); long sum = 0; for (int i = 0; i < n; ++i) { sum += a[i + 1]; a[i + 1] = sum; } int q = nextInt(); Map<Long, Long> mem = new HashMap<Long, Long>(); for (int i = 0; i < q; ++i) { long kk = nextInt(); long r = 0; if (mem.containsKey(kk)) { r = mem.get(kk); } else { long k = kk; // if (n == 100000) { // if (i > 1230) // out.println(k); // continue; // } int t = n - 1; long m = 1; while (t > 0) { long tt = a[t]; if (k > t) t = 0; else t -= k; if (k < t) k *= kk; if (t < 0) t = 0; tt -= a[t]; tt *= m; r += tt; ++m; } mem.put(kk, r); } if (i > 0) out.print(" "); out.print(r); } out.println(); } public static void main(String[] args) throws IOException { 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"); } new CodeForces().runIt(); out.flush(); out.close(); return; } static BufferedReader in; private StringTokenizer st; static PrintWriter out; String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } st = new StringTokenizer(line, " "); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } void runIt() throws IOException { st = new StringTokenizer(""); // int N = nextInt(); // for (int i = 0; i < N; i++) { // runCase(i + 1); // } runCase(0); out.flush(); } }
Java
["5\n2 3 4 1 1\n2\n2 3"]
2 seconds
["9 8"]
NoteIn the first sample one way to get the optimal answer goes like this: we add in turns the 4-th and the 5-th piles to the 2-nd one; then we add the 1-st pile to the 3-rd one; we add the 2-nd pile to the 3-rd one. The first two operations cost 1 each; the third one costs 2, the fourth one costs 5 (the size of the 2-nd pile after the first two operations is not 3, it already is 5). In the second sample you can add the 2-nd pile to the 3-rd one (the operations costs 3); then the 1-st one to the 3-th one (the cost is 2); then the 5-th one to the 4-th one (the costs is 1); and at last, the 4-th one to the 3-rd one (the cost is 2).
Java 6
standard input
[ "greedy" ]
87045c4df69110642122f2c114476947
The first line contains integer n (1 ≀ n ≀ 105) β€” the number of stone piles. The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the initial sizes of the stone piles. The third line contains integer q (1 ≀ q ≀ 105) β€” the number of queries. The last line contains q space-separated integers k1, k2, ..., kq (1 ≀ ki ≀ 105) β€” the values of number k for distinct queries. Note that numbers ki can repeat.
1,900
Print q whitespace-separated integers β€” the answers to the queries in the order, in which the queries are given in the input. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
b8103da85bc78d583676d1eb4c4797d1
train_001.jsonl
1348500600
There are n piles of stones of sizes a1, a2, ..., an lying on the table in front of you.During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of the added pile.Your task is to determine the minimum cost at which you can gather all stones in one pile. To add some challenge, the stone piles built up conspiracy and decided that each pile will let you add to it not more than k times (after that it can only be added to another pile). Moreover, the piles decided to puzzle you completely and told you q variants (not necessarily distinct) of what k might equal. Your task is to find the minimum cost for each of q variants.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class ProblemB { public static void main(String[] args) throws IOException { new ProblemB().solve(); } long[] cache = new long[100001]; long[] sum; int N; private void solve() throws IOException { Reader in = new Reader(System.in); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); N = in.nextInt(); int[] a = new int[N]; for (int i = 0; i < N; i++) a[i] = in.nextInt(); Arrays.sort(a); a = reverse(a); sum = new long[N + 1]; for (int i = 1; i <= N; i++) sum[i] = sum[i-1] + a[i-1]; Arrays.fill(cache, -1); for (int q = in.nextInt(); q > 0; q--) { long r = count(in.nextInt()); out.print(r + " "); } out.flush(); out.close(); } private long count(int k) { if (cache[k] != -1) return cache[k]; long r = rec(2, k, k, 1); cache[k] = r; return r; } private long rec(int from, long howMany, int k, int x) { int to = (int)Math.min(from + howMany - 1, N); long r = (sum[to] - sum[from - 1]) * x; if (to < N) { r += rec(to + 1, howMany * k, k, x + 1); } return r; } private int[] reverse(int[] a) { int[] b = new int[a.length]; for (int i = 0; i < a.length; i++) b[i] = a[a.length - 1 - i]; return b; } private static class Reader { BufferedReader reader; StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ Reader(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ public String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt( next() ); } public double nextDouble() throws IOException { return Double.parseDouble( next() ); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["5\n2 3 4 1 1\n2\n2 3"]
2 seconds
["9 8"]
NoteIn the first sample one way to get the optimal answer goes like this: we add in turns the 4-th and the 5-th piles to the 2-nd one; then we add the 1-st pile to the 3-rd one; we add the 2-nd pile to the 3-rd one. The first two operations cost 1 each; the third one costs 2, the fourth one costs 5 (the size of the 2-nd pile after the first two operations is not 3, it already is 5). In the second sample you can add the 2-nd pile to the 3-rd one (the operations costs 3); then the 1-st one to the 3-th one (the cost is 2); then the 5-th one to the 4-th one (the costs is 1); and at last, the 4-th one to the 3-rd one (the cost is 2).
Java 6
standard input
[ "greedy" ]
87045c4df69110642122f2c114476947
The first line contains integer n (1 ≀ n ≀ 105) β€” the number of stone piles. The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the initial sizes of the stone piles. The third line contains integer q (1 ≀ q ≀ 105) β€” the number of queries. The last line contains q space-separated integers k1, k2, ..., kq (1 ≀ ki ≀ 105) β€” the values of number k for distinct queries. Note that numbers ki can repeat.
1,900
Print q whitespace-separated integers β€” the answers to the queries in the order, in which the queries are given in the input. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
a19ffe9c49594bd4a46182912c8532c9
train_001.jsonl
1348500600
There are n piles of stones of sizes a1, a2, ..., an lying on the table in front of you.During one move you can take one pile and add it to the other. As you add pile i to pile j, the size of pile j increases by the current size of pile i, and pile i stops existing. The cost of the adding operation equals the size of the added pile.Your task is to determine the minimum cost at which you can gather all stones in one pile. To add some challenge, the stone piles built up conspiracy and decided that each pile will let you add to it not more than k times (after that it can only be added to another pile). Moreover, the piles decided to puzzle you completely and told you q variants (not necessarily distinct) of what k might equal. Your task is to find the minimum cost for each of q variants.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Random; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[100000]; for (int i = 0; i < n; i++) a[i] = in.nextInt(); ArrayUtils.sort(a); ArrayUtils.reverse(a); long[] sum = new long[100007]; sum[0] = a[0]; for (int i = 1; i < 100000; i++) sum[i] = sum[i - 1] + a[i]; long[] ret = new long[100001]; for (int k = 1; k <= 100000; k++) { long ans = 0; long pow = 1; int pos = 0; int it = 0; while (pos < n) { int r = (int) Math.min(n - 1L, pos + pow - 1); long s = sum[r]; if (pos != 0) s -= sum[pos - 1]; ans += it * s; pos = r + 1; it++; pow *= k; } ret[k] = ans; } int q = in.nextInt(); for (int i = 0; i < q; i++) { int c = in.nextInt(); out.print(ret[c]); out.print(' '); } out.println(); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public int nextInt() { return Integer.parseInt(next()); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } } class ArrayUtils { static Random r = new Random(777); public static void reverse(int[] a) { int l = 0, r = a.length-1; while (l < r) { int t = a[l]; a[l++] = a[r]; a[r--] = t; } } public static void sort(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int k = r.nextInt(n); int t = a[k]; a[k] = a[i]; a[i] = t; } Arrays.sort(a); } }
Java
["5\n2 3 4 1 1\n2\n2 3"]
2 seconds
["9 8"]
NoteIn the first sample one way to get the optimal answer goes like this: we add in turns the 4-th and the 5-th piles to the 2-nd one; then we add the 1-st pile to the 3-rd one; we add the 2-nd pile to the 3-rd one. The first two operations cost 1 each; the third one costs 2, the fourth one costs 5 (the size of the 2-nd pile after the first two operations is not 3, it already is 5). In the second sample you can add the 2-nd pile to the 3-rd one (the operations costs 3); then the 1-st one to the 3-th one (the cost is 2); then the 5-th one to the 4-th one (the costs is 1); and at last, the 4-th one to the 3-rd one (the cost is 2).
Java 6
standard input
[ "greedy" ]
87045c4df69110642122f2c114476947
The first line contains integer n (1 ≀ n ≀ 105) β€” the number of stone piles. The second line contains n space-separated integers: a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the initial sizes of the stone piles. The third line contains integer q (1 ≀ q ≀ 105) β€” the number of queries. The last line contains q space-separated integers k1, k2, ..., kq (1 ≀ ki ≀ 105) β€” the values of number k for distinct queries. Note that numbers ki can repeat.
1,900
Print q whitespace-separated integers β€” the answers to the queries in the order, in which the queries are given in the input. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.
standard output
PASSED
c8bf593591532a4fd707f671992b5eed
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
// http://codeforces.com/contest/126/problem/B import java.util.Scanner; public class Password { public static void main(String[] args) { Scanner in = new Scanner(System.in); char[] s = in.next().toCharArray(); in.close(); int[] arr = new int[s.length]; int i = 1, j = 0; while(i < s.length) { if(s[i] == s[j]) { arr[i] = j+1; i++; j++; } else { while(s[i] != s[j] && j > 0) j = arr[j-1]; if(s[i] != s[j]) i++; } } // length of candidate int x = arr[arr.length-1]; if(x == 0 || s.length < 3) fail(); for(i = 1; i < s.length-1; i++) if(arr[i] == x) succeed(s, x); if(arr[x-1] == 0) fail(); succeed(s, arr[x-1]); // // consider string minus first and last chars // int[] arrc = new int[s.length-2]; // char[] center = new String(s, 1, s.length-2).toCharArray(); // i = 1; j = 0; // while(i < center.length) { // if(center[i] == center[j]) { // arrc[i] = j+1; // i++; // j++; // } // else { // while(center[i] != center[j] && j > 0) // j = arrc[j-1]; // if(center[i] != center[j]) // i++; // } // } // // // is candidate string in center? // int depth = 0; // for(i = 0; i < center.length; i++) { // if(center[i] == s[depth]) { // if(++depth == x) // succeed(s, x); // } // else // depth = arrc[i]; // } // // // candidate string not in center // x = arr[x-1]; // if(x == 0) // fail(); // succeed(s, x); } public static void fail() { System.out.print("Just a legend"); System.exit(0); } public static void succeed(char[] s, int len) { System.out.print(new String(s, 0, len)); System.exit(0); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
feffee4b7812ee4148b455f2913010a4
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
/* * Date: 13.05.12 * Time: 23:45 * Author: * Vanslov Evgeny * [email protected] */ import java.io.FileNotFoundException; import java.util.Scanner; public class C { public static void main(String[] args) throws FileNotFoundException { // final Scanner scanner = new Scanner(new BufferedReader(new FileReader("input"))); final Scanner scanner = new Scanner(System.in); final String s = scanner.next(); final ObeliskString obeliskString = new ObeliskString(s); final String answer = obeliskString.find(); if(answer != null){ System.out.println(answer); } else { System.out.println("Just a legend"); } } } class HashString { private long hash[]; private long powers[]; public HashString(final String s) { hash = new long[s.length()]; hash[0] = s.charAt(0) - 'a'; for(int i = 1; i < hash.length; ++i){ hash[i] = hash[i - 1] * 31 + s.charAt(i) - 'a'; } powers = new long[hash.length + 1]; powers[0] = 1; for(int i = 1; i < powers.length; ++i){ powers[i] = powers[i - 1] * 31; } } public long hash(int from, int to){ --from; --to; if(from == -1){ return hash[to]; } return hash[to] - hash[from] * powers[to - from]; } } class ObeliskString { private final HashString hashString; private final String s; public ObeliskString(final String s){ hashString = new HashString(s); this.s = s; } public boolean isSuffixEqPrefix(int length){ return hashString.hash(0, length) == hashString.hash(s.length() - length, s.length()); } public boolean isInnerExist(int length){ final long prefixHash = hashString.hash(0, length); for(int i = 1; i + length < s.length(); ++i){ if(prefixHash == hashString.hash(i, i + length)){ return true; } } return false; } public String find(){ int left = 0; int right = s.length(); while(left < right){ final int middle = (left + right) / 2; if(middle != 0 && isInnerExist(middle)){ left = middle + 1; } else { right = middle; } } if(right != 0 && !isInnerExist(right)){ --right; } for(int i = right; i > 0; --i){ if(isSuffixEqPrefix(i)){ return s.substring(0, i); } } return null; } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
9cbb473f2c64cffb20e78e3988af847d
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
/** * Created by icon on 1/17/2016. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class CF126B { public static void main(String[] args) { InputStream input = System.in; OutputStream output = System.out; Reader in = new Reader(input); PrintWriter out = new PrintWriter(output); Task magician = new Task(); magician.solve(in, out); out.close(); } static class Task { final int MOD = 1000000007; final int MOD2 = 1500450271; final int BASE = 1022201; final int BASE2 = 1178711; long [] E, E2, H, H2; int size; public void solve(Reader in, PrintWriter out) { String str = in.next(); size = str.length(); E = new long[size + 1]; E2 = new long[size + 1]; H = new long[size + 1]; H2 = new long[size + 1]; E[0] = E2[0] = 1L; H[0] = H2[0] = 0L; for(int i = 1; i <= size; i++) { E[i] = (E[i - 1] * BASE) % MOD; E2[i] = (E2[i - 1] * BASE2) % MOD2; H[i] = (H[i - 1] * BASE + str.charAt(i - 1)) % MOD; H2[i] = (H2[i - 1] * BASE2 + str.charAt(i - 1)) % MOD2; } ArrayList<Integer> positions = new ArrayList<>(); for(int i = 1; i < size; i++) { if(match(i)) { positions.add(i); } } // for(int i : positions) out.print(i + " "); int left = 0, right = positions.size() - 1; int res = -1; while(left <= right) { int mid = (left + right) >> 1; if(okay(positions.get(mid))) { res = positions.get(mid); left = mid + 1; } else right = mid - 1; } if(res == -1) out.print("Just a legend"); else out.print(str.substring(0, res)); } boolean match(int pos) { long beg = H[pos], beg2 = H2[pos]; int last = size - pos; // System.out.println(pos + " " + last); long end = (H[size] - (H[last] * E[pos]) % MOD + MOD) % MOD; long end2 = (H2[size] - (H2[last] * E2[pos]) % MOD2 + MOD2) % MOD2; return (beg == end && beg2 == end2); } boolean okay(int pos) { long cur = H[pos], cur2 = H2[pos]; for(int i = pos + 1; i < size; i++) { long now = (H[i] - (H[i - pos] * E[pos]) % MOD + MOD) % MOD; long now2 = (H2[i] - (H2[i - pos] * E2[pos]) % MOD2 + MOD2) % MOD2; if(cur == now && cur2 == now2) return true; } return false; } } static class Reader { public BufferedReader reader; public StringTokenizer tokenizer; public Reader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
dff1a7683ba237300c5a324eb6e0fbd5
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class Password { public static int[] preProcessPattern(String ptrn) { int i = 0, j = -1; int ptrnLen = ptrn.length(); int[] b = new int[ptrnLen + 1]; b[i] = j; while (i < ptrnLen) { while (j >= 0 && ptrn.charAt(i) != ptrn.charAt(j)) { j = b[j]; } i++; j++; b[i] = j; } return b; } public static void main(String[] args) throws IOException { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String s = r.readLine(); int[] a = preProcessPattern(s); int max = a[a.length - 1]; int p = max; ArrayList<Integer>kaka=new ArrayList<Integer>(); while(true){ if(p==0||p==-1)break; kaka.add(p); p = a[p]; } for (int i = 0; i < kaka.size() ; i++) { // System.out.println(kaka.get(i)); for(int j = 1 ; j < a.length-1 ; j++){ if(a[j]==kaka.get(i)){System.out.println(s.substring(0,a[j])); return;} } } System.out.println("Just a legend"); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
c8bb75c9f0cc1d5d808ce1e20a8e3309
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Password { public static void main(String[] args){ FastScanner sc = new FastScanner(); String s = sc.nextToken(); int[] z = new int[s.length()]; int n = s.length(); int L = 0, R = 0; //note that maxZ does not care about z[0] = n //so it keeps track only of length of longest infix int maxZ = 0; for (int i = 1; i < n; i++) { if (i > R) { //bf L = R = i; while (R < n && s.charAt(R-L) == s.charAt(R)) R++; z[i] = R-L; R--; } else { int k = i-L; //beta inside alpha, and closed by a1 != a2 if (z[k] < R-i+1) z[i] = z[k]; else { //bf L = i; while (R < n && s.charAt(R-L) == s.charAt(R)) R++; z[i] = R-L; R--; } } if(z[i] == n-i && maxZ >= n-i){ System.out.println(s.substring(0,z[i])); return; } maxZ = Math.max(z[i],maxZ); } System.out.println("Just a legend"); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
4c00a0a16c9f3ab1c45bccc7b61eb254
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Nguyen Trung Hieu - [email protected] */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { String s = in.readString(); int[] z = StringUtils.zAlgorithm(s); int maxInside = 0; for (int i = 1; i < z.length; i++){ maxInside = Math.max(maxInside, Math.min(z[i], z.length - i - 1)); } int answer = -1; for (int i = z.length - maxInside; i < z.length; i++){ if (i + z[i] == z.length){ answer = z.length - i; break; } } if (answer == -1) out.printLine("Just a legend"); else out.printLine(s.substring(0, answer)); } } 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 boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } 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(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class StringUtils { public static int[] zAlgorithm(CharSequence s) { int length = s.length(); int[] z = new int[length]; z[0] = 0; int left = 0, right = 0; for (int i = 1; i < length; i++) { if (i > right) { int j; //noinspection StatementWithEmptyBody for (j = 0; i + j < length && s.charAt(i + j) == s.charAt(j); j++) ; z[i] = j; left = i; right = i + j - 1; } else if (z[i - left] < right - i + 1) z[i] = z[i - left]; else { int j; //noinspection StatementWithEmptyBody for (j = 1; right + j < length && s.charAt(right + j) == s.charAt(right - i + j); j++) ; z[i] = right - i + j; left = i; right = right + j - 1; } } return z; } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
dfb9508b4dcc6e0fefe28b37c1b3fecb
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.*; import java.util.*; public class kmp { public static int zarr(String s) { int z[]=new int[s.length()]; int n=s.length(); z[0] = 0;//1st element is always zero for (int i=1; i<n; ++i) { int j = z[i-1]; while (j > 0 && s.charAt(i) != s.charAt(j)) j = z[j-1]; //System.out.println(s.charAt(i)+" "+s.charAt(j)+" "+j); if (s.charAt(i) == s.charAt(j) ) ++j; z[i] = j; } if(z[n-1]==0)return 0; else { int mark=0; for(int i=0;i<n-1;i++) { if(z[i]==z[n-1])mark=1;; } if(mark==1)return z[n-1]; else return z[z[n-1]-1]; } } public static void main(String[] args) throws Exception { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); //int n=in.readInt(); String p=in.readString(); if(p.length()==1||p.length()==2) out.printLine("Just a legend"); else{ int i=zarr(p); if(i==0) out.printLine("Just a legend"); else out.printLine(p.substring(0,i)); } out.close(); } private 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 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 interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } private 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(); } } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
9d2e01d86fc3389fd7141f0c90f94fff
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class Round93_B { int[] z; public void run(String str) { char[] s = str.toCharArray(); int n = s.length; z = new int[n]; z[0] = n; int L = 0, R = 0; for (int i = 1; i < n; i++) { // System.out.println(" ****** At " + i); // System.out.print("from " + L + " " + R + "\t"); if (i > R) { L = R = i; while (R < n && s[R - L] == s[R]) R++; z[i] = R - L; R--; } else { int k = i - L; if (z[k] < R - i + 1) z[i] = z[k]; else { L = i; while (R < n && s[R - L] == s[R]) R++; z[i] = R - L; R--; } } // System.out.println("to " + L + " " + R); } } ArrayList<Integer> sufPref; int N; public int bs(int val) { int low = 0; int high = sufPref.size() - 1; int ans = -1; while (low <= high) { if (high - low < 2) { if (sufPref.get(low) <= val) ans = Math.max(ans, low); if (sufPref.get(high) <= val) ans = Math.max(ans, high); break; } int mid = low + (high - low) / 2; if (sufPref.get(mid) > val) { // go left high = mid - 1; } else { // go right ans = Math.max(ans, mid); low = mid + 1; } } return ans; } public void solve() throws Exception { String s = new InputReader().next(); run(s); N = z.length; // ascending sufPref = new ArrayList<Integer>(); // get all suffpreff for (int i = N - 1; i > 0; i--) { if (z[i] == N - i) sufPref.add(N - i); } // System.out.println(Arrays.toString(sufPref.toArray())); int ans = 0; for (int i = 1; i < N; i++) { if (z[i] != 0) { int y = bs(z[i]); // System.out.println(z[i] + " " + y); if (y != -1) { if (z[i] != N - i) ans = Math.max(ans, sufPref.get(y)); else if (y > 0) ans = Math.max(ans, sufPref.get(y - 1)); } } } if (ans != 0) System.out.println(s.substring(0, ans)); else System.out.println("Just a legend"); } public static void main(String[] args) throws Exception { new Round93_B().solve(); } static class InputReader { BufferedReader in; StringTokenizer st; public InputReader() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(in.readLine()); } public String next() throws IOException { while (!st.hasMoreElements()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
2a016895d9a8b4f8e4460420e71c40a5
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.util.*; public class Password { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.next(); int[] zv = zValues(s); int max = -1; int result = -1; for(int x = 1; x < zv.length; x++) { if(zv[x] > max) { max = zv[x]; } else if(zv[x] <= max && zv[x] == zv.length - x) { result = x; break; } } if(result == -1) { System.out.println("Just a legend"); } else { System.out.println(s.substring(result)); } } public static int[] zValues(String s) { int[] zv = new int[s.length()]; zv[0] = s.length(); int l = 0; int r = 0; for(int i = 1; i < s.length(); i++) { if(i > r) { l = i; r = i; while(r < s.length() && s.charAt(r - l) == s.charAt(r)) { r++; } r--; zv[i] = r - l + 1; } else { int k = i - l; if(zv[k] < r - i + 1) { zv[i] = zv[k]; } else { l = i; while(r < s.length() && s.charAt(r - l) == s.charAt(r)) { r++; } r--; zv[i] = r - l + 1; } } } return zv; } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
506576d7551ec0da2fd714e4aa07c589
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.Character.Subset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeMap; import javax.management.RuntimeErrorException; public class Codeforces { StringTokenizer tok; BufferedReader in; PrintWriter out; final boolean OJ = System.getProperty("ONLINE_JUDGE") != null; void init() { try { if (OJ) { 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"); } } catch (Exception e) { throw new RuntimeException(e); } } String readString() { try { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } catch (Throwable t) { throw new RuntimeException(t); } } int readInt() { return Integer.parseInt(readString()); } long readLong() { return Long.parseLong(readString()); } public static void main(String[] args) { new Codeforces().run(); } void run() { init(); long time = System.currentTimeMillis(); solve(); System.err.println(System.currentTimeMillis() - time); out.close(); } int[] prefix(char[] s) { int n = s.length; int[] pi = new int[n]; for (int i = 1; i < n; ++i) { int j = pi[i - 1]; while (j > 0 && s[i] != s[j]) j = pi[j - 1]; if (s[i] == s[j]) ++j; pi[i] = j; } return pi; } void solve() { char[] a = readString().toCharArray(); int n = a.length; int[] p = prefix(a); if (p[n - 1] == 0) { out.println("Just a legend"); return; } for (int i = 0; i < n - 1; i++) { if (p[i] == p[n - 1]) { for (int j = 0; j < p[n - 1]; j++) { out.print(a[j]); } return; } } int x = p[p[n - 1] - 1]; if (x == 0) { out.println("Just a legend"); return; } for (int j = 0; j < x; j++) { out.print(a[j]); } } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
2a7c8e1c52d6e8ff0a549e914355dd70
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.math.BigDecimal; import java.io.BufferedWriter; import java.util.Locale; import java.util.InputMismatchException; import java.util.ArrayList; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Jacob Jiang */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { private static final long MOD = 3168661733l; private static final long d = 37; private static final long dInv = BigInteger.valueOf(d).modInverse(BigInteger.valueOf(MOD)).longValue(); private long[] dPow; private long[] prefixHash; private int n; private int[] a; public void solve(int testNumber, InputReader in, OutputWriter out) { char[] _str = in.nextCharArray(); n = _str.length; a = new int[n]; for (int i = 0; i < n; i++) a[i] = _str[i] - 'a'; ArrayList<Integer> possibleLength = new ArrayList<Integer>(); possibleLength.add(0); long frontHash = 0; long lastHash = 0; dPow = new long[n + 1]; dPow[0] = 1; for (int i = 1; i <= n; i++) { dPow[i] = (dPow[i - 1] * d) % MOD; } prefixHash = new long[n - 1]; for (int i = 0; i < n - 1; i++) { frontHash += a[i] * dPow[i]; lastHash = lastHash * d + a[n - 1 - i]; frontHash %= MOD; lastHash %= MOD; if (frontHash == lastHash) possibleLength.add(i + 1); prefixHash[i] = frontHash; } int left = 0, right = possibleLength.size() - 1; while (left < right) { int mid = (left + right + 1) >> 1; if (can(possibleLength.get(mid))) left = mid; else right = mid - 1; } out.println(left > 0 ? String.valueOf(_str).substring(0, possibleLength.get(left)) : "Just a legend"); } private boolean can(int length) { if (length == 0) return true; long currentHash = prefixHash[length - 1]; for (int i = length; i < n - 1; i++) { currentHash -= a[i - length]; if (currentHash < 0) currentHash += MOD; currentHash = (currentHash * dInv) % MOD; currentHash += a[i] * dPow[length - 1]; currentHash %= MOD; if (currentHash == prefixHash[length - 1]) { return true; } } return false; } } class InputReader { private InputStream stream; private byte[] buf = new byte[1 << 20]; 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 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 static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char[] nextCharArray() { return next().toCharArray(); } } class OutputWriter { private PrintWriter writer; public OutputWriter(OutputStream stream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(String x) { writer.println(x); } public void close() { writer.close(); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
9cbc7dc2ed4ab19094061d0c84eb6001
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; public class z_function { static StreamTokenizer st; static String s; public static void main(String[] args) throws IOException { st = new StreamTokenizer(new BufferedReader(new InputStreamReader( System.in))); s = next(); int a[] = z_function(s); // Arrays.sort(a); int max = 0; int x= 0; for (int i = 0; i < a.length; i++) { if (a[i] > 0 && s.length() - i == a[i]) { x = a[i]; break; } } int b[] = new int[1000000]; for (int i = 0; i < a.length; i++) { b[a[i]]++; } for (int i = 0; i < b.length; i++) { if (b[i] > 3) { max = i; } } int k = 0; int z[] = new int[(int) 1e6]; for (int i = 0; i < b.length; i++) { for (int j = 0; j < b[i]; j++) { a[k++] = i; } } // System.out.println(x); // nmkjnmkinmkunm PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); if (s.length() > 2) { for (int i = a.length - 2; a[i] > 0; i--) { // System.out.println(a[i]); if (x >= a[i] && s.charAt(a[i]-1) == s.charAt(s.length()-1)) { pw.println(s.substring(s.length() - a[i], s.length())); pw.close(); return; } } } pw.println("Just a legend"); pw.close(); } private static String next() throws IOException { st.nextToken(); return st.sval; } private static boolean tek(int max) { int n = s.length() - max; for (int i = 0; i < max; i++) { if (s.charAt(i) != s.charAt(n)) { return false; } n++; } return true; } static public int[] z_function(String s) { int m = s.length(); int z[] = new int[m]; for (int i = 1, l = 0, r = 0; i < m; ++i) { if (i <= r) { z[i] = Math.min(r - i + 1, z[i - l]); } while (i + z[i] < m && s.charAt(z[i]) == s.charAt(i + z[i])) { ++z[i]; } if (i + z[i] - 1 > r) { l = i; r = i + z[i] - 1; } } return z; } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
82f6f95fe7d933018693aa10170f0a53
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; public class z_function { static StreamTokenizer st; static String s; public static void main(String[] args) throws IOException { st = new StreamTokenizer(new BufferedReader(new InputStreamReader( System.in))); s = next(); int a[] = z_function(s); int max = 0; int x = 0; for (int i = 0; i < a.length; i++) { if (a[i] > 0 && s.length() - i == a[i]) { x = a[i]; break; } } int b[] = new int[1000000]; for (int i = 0; i < a.length; i++) { b[a[i]]++; } for (int i = 0; i < b.length; i++) { if (b[i] > 3) { max = i; } } int k = 0; for (int i = 0; i < b.length; i++) { for (int j = 0; j < b[i]; j++) { a[k++] = i; } } // nmkjnmkinmkunm PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); if (s.length() > 2) { for (int i = a.length - 2; a[i] > 0; i--) { if (x >= a[i] && s.charAt(a[i] - 1) == s.charAt(s.length() - 1)) { pw.println(s.substring(s.length() - a[i], s.length())); pw.close(); return; } } } pw.println("Just a legend"); pw.close(); } private static String next() throws IOException { st.nextToken(); return st.sval; } static public int[] z_function(String s) { int m = s.length(); int z[] = new int[m]; for (int i = 1, l = 0, r = 0; i < m; ++i) { if (i <= r) { z[i] = Math.min(r - i + 1, z[i - l]); } while (i + z[i] < m && s.charAt(z[i]) == s.charAt(i + z[i])) { ++z[i]; } if (i + z[i] - 1 > r) { l = i; r = i + z[i] - 1; } } return z; } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
f4ea4493009cbb1e022635d2451c1855
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class Password { static int [] ZFunction(char[] s){ int z[] = new int[s.length]; z[0] = s.length; int r = 0; int l = 0; int n = s.length; for(int i = 1;i<n;i++){ if(i>r){ r=l=i; while(r<n&&s[r-l]==s[r]) r++; z[i] = r-l; r--; } else{ int k = i-l; if(z[k]<r-i+1) z[i] = z[k]; else{ l = i; while(r<n&&s[r-l]==s[r]) r++; z[i] = r-l; r--; } } } return z; } public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String s = in.readLine().trim(); int z[] = ZFunction(s.toCharArray()); int freq[] = new int [s.length()+1]; boolean found = false; for(int i = 0;i<z.length;i++){ if(z[i]!=0){ freq[z[i]]++; } } int num = freq[freq.length-1]; for(int i = freq.length-2;i>=0;i--) if(freq[i]!=0){ freq[i]+=num; num+=(freq[i]-num); } for(int i = freq.length-1;!found&&i>=0;i--){ int len = z.length -i; if(freq[i]>2&&z[len]==i){ out.println(s.substring(0,i)); found = true; } } if(!found) out.println("Just a legend"); in.close(); out.close(); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
dce87453d15d0ad556e8551f2bc352b7
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.*; import java.util.*; import java.io.DataInputStream; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.Stack; public class fast{ static class InputReader { private boolean finished = false; 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 peek() { if (numChars == -1) return -1; if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } 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 length = readInt(); if (length < 0) return null; byte[] bytes = new byte[length]; for (int i = 0; i < length; i++) bytes[i] = (byte) read(); try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { return new String(bytes); } } public static 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; } public boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value == -1; } public String next() { return readString(); } public boolean readBoolean() { return readInt() == 1; } } public static int [] prefix(char arr[]){ int len=arr.length; int arr1[]=new int[len]; int temp=0; for(int i=1;i<len;i++){ while(temp>0&&arr[temp]!=arr[i]) temp=arr1[temp-1]; if(arr[i]==arr[temp]) temp++; arr1[i]=temp; } return arr1; } public static void main (String[] args) throws Exception{ InputReader s = new InputReader(System.in); PrintWriter ww = new PrintWriter(System.out,true); String str=s.readLine(); char arr[]=str.toCharArray(); int suffix[]=prefix(arr); int len=suffix.length; int flag=0; if(suffix[len-1]==0) ww.println("Just a legend"); else{ for(int i=0;i<len-1;i++) if(suffix[i]==suffix[len-1]) flag=1; if(flag==1){ int pos=suffix[len-1]; for(int i=0;i<pos;i++) ww.print(arr[i]); } else{ int pos=suffix[suffix[len-1]-1]; if(pos!=0){ for(int i=0;i<pos;i++) ww.print(arr[i]); } else ww.print("Just a legend"); } } ww.close(); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
e125833434376e023a55839d173c98b6
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Password { static char[] s; static int[] z; static int n; static void solve() { int L = 0, R = 0; for (int i = 1; i < n; i++) { if (i > R) { L = R = i; while (R < n && s[R - L] == s[R]) R++; z[i] = R - L; R--; } else { int k = i - L; if (z[k] < R - i + 1) z[i] = z[k]; else { L = i; while (R < n && s[R - L] == s[R]) R++; z[i] = R - L; R--; } } } } public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(System.out); sc = new StringTokenizer(br.readLine()); s = nxtCharArr(); n = s.length; z = new int[n]; solve(); int max = 0; int maxi = 0; boolean done = false; for (int i = 1; i < n && !done; i++) { if (z[i] > max) { max = z[i]; maxi = i; } else if (z[i] <= max && z[i] + i == n) { max = z[i]; maxi = i; done = true; } } if (max == 0 || !done) out.println("Just a legend"); else out.println(new String(s).substring(maxi, maxi + max)); br.close(); out.close(); } static BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); static StringTokenizer sc; static String nxtTok() throws IOException { while (!sc.hasMoreTokens()) { String s = br.readLine(); if (s == null) return null; sc = new StringTokenizer(s.trim()); } return sc.nextToken(); } static int nxtInt() throws IOException { return Integer.parseInt(nxtTok()); } static long nxtLng() throws IOException { return Long.parseLong(nxtTok()); } static double nxtDbl() throws IOException { return Double.parseDouble(nxtTok()); } static int[] nxtIntArr(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nxtInt(); return a; } static long[] nxtLngArr(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nxtLng(); return a; } static double[] nxtDblArr(int n) throws IOException { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nxtDbl(); return a; } static char[] nxtCharArr() throws IOException { return nxtTok().toCharArray(); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
d06640992438680fb961ff1eba41e6d5
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Password { static int[] z; public static void Z(StringBuilder s) { int L = 0, R = 0; int n = s.length(); z = new int[n]; for (int i = 1; i < n; i++) { if (i > R) { L = R = i; while (R < n && s.charAt(R - L) == s.charAt(R)) R++; z[i] = R - L; R--; } else { int k = i - L; if (z[k] < R - i + 1) z[i] = z[k]; else { L = i; while (R < n && s.charAt(R - L) == s.charAt(R)) R++; z[i] = R - L; R--; } } } } public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringBuilder s = new StringBuilder(bf.readLine()); if(s.length()<3){ System.out.println("Just a legend"); return; } Z(s); int max = 0; int index = -1; for (int i = 1; i < z.length; i++) { if(z[i]==s.length()-i && max>=z[i]){ index = i; break; } max = Math.max(max, z[i]); } if(index==-1) System.out.println("Just a legend"); else System.out.println(s.substring(index)); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
1fbe35245c0dca1a18e88caeaa6a6289
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Password { static int[] z; public static void Z(StringBuilder s) { int L = 0, R = 0; int n = s.length(); z = new int[n]; for (int i = 1; i < n; i++) { if (i > R) { L = R = i; while (R < n && s.charAt(R - L) == s.charAt(R)) R++; z[i] = R - L; R--; } else { int k = i - L; if (z[k] < R - i + 1) z[i] = z[k]; else { L = i; while (R < n && s.charAt(R - L) == s.charAt(R)) R++; z[i] = R - L; R--; } } } } public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringBuilder s = new StringBuilder(bf.readLine()); if(s.length()<3){ System.out.println("Just a legend"); return; } Z(s); int max = 0; int index = -1; for (int i = 1; i < z.length; i++) { if(z[i]==s.length()-i && max>=z[i]){ index = i; break; } max = Math.max(max, z[i]); } if(index==-1) System.out.println("Just a legend"); else System.out.println(s.substring(index)); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
553ea038fdcc0aba032e085f16509d10
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Password { static int[] z; public static void Z(StringBuilder s) { int L = 0, R = 0; int n = s.length(); z = new int[n]; for (int i = 1; i < n; i++) { if (i > R) { L = R = i; while (R < n && s.charAt(R - L) == s.charAt(R)) R++; z[i] = R - L; R--; } else { int k = i - L; if (z[k] < R - i + 1) z[i] = z[k]; else { L = i; while (R < n && s.charAt(R - L) == s.charAt(R)) R++; z[i] = R - L; R--; } } } } public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); StringBuilder s = new StringBuilder(bf.readLine()); if(s.length()<3){ System.out.println("Just a legend"); return; } Z(s); int max = 0; int index = -1; for (int i = 1; i < z.length; i++) { if(z[i]==s.length()-i && max>=z[i]){ index = i; break; } max = Math.max(max, z[i]); } if(index==-1) System.out.println("Just a legend"); else System.out.println(s.substring(index)); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
25d7a56cf39c77ff6ce0b5d231d5eabf
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author sandeepandey */ 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); Password solver = new Password(); solver.solve(1, in, out); out.close(); } } class Password { private static int lenCount; public void solve(int testNumber, InputReader in, OutputWriter out) { String input = in.readString(); StringHash hasher = new ConcreteHasher(input,true); lenCount = input.length()-1; long[] prefixHash = new long[input.length() + 1]; long[] suffixHash = new long[input.length() + 1]; for(int i = 0;i <= lenCount ;i++) { prefixHash[i] = hasher.hash(0,i); suffixHash[lenCount-i] = hasher.hash(lenCount-i,lenCount); } int longestTillNow = -1; for(int i = lenCount-1;i >=0 ; i--) { if(prefixHash[i] == suffixHash[lenCount-i] ) { long target = prefixHash[i]; int window = i+1; for(int k = 1 ; k+i < lenCount ; k++) { long toCompare = hasher.hash(k,k+window-1); if(toCompare == target) { longestTillNow = Math.max(longestTillNow,window); break; } } } } out.printLine(longestTillNow < 0 ? "Just a legend":input.substring(0,longestTillNow)); } } 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 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(); } 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); } } 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(); } } interface StringHash { /** * This interface is the base interface of all the actvities involve in String matching via roll hashing * programmer are advise to use this interface as the base interface of all other concrete subclasses. */ public long hash(int from,int to); } class ConcreteHasher extends SimpleStringHash { public ConcreteHasher(String input,boolean isReverseRequired) { super(input,isReverseRequired); } public long hashFunction(long previousHash, char currentChar, int subtractor, long multiplier) { return (previousHash * multiplier + currentChar-subtractor); } } abstract class SimpleStringHash extends AbstractStringHash { private long[] hashArray = null; private long[] baseArray = null; private long[] reverseHashArray = null; private int length; public SimpleStringHash(CharSequence input,boolean isReverseRequired) { super(); length = input.length(); hashArray = new long[length + 1]; baseArray = new long[length + 1]; long tmpHash = 0; long tmpMul = 1; for(int i = 0; i < length ; i++) { baseArray[i] = tmpMul; tmpMul = tmpMul * DEFAULT_MAULTIPLIER; } for(int i = 0; i < length ; i++) { tmpHash = hashFunction(tmpHash,input.charAt(i),48,DEFAULT_MAULTIPLIER); hashArray[i] = tmpHash; } if(isReverseRequired) { reverseHashArray = new long[length + 1]; tmpHash = 0; for(int i = length-1 ; i >=0 ; i--) { tmpHash = hashFunction(tmpHash,input.charAt(i),48,DEFAULT_MAULTIPLIER); reverseHashArray[i] = tmpHash; } } } public abstract long hashFunction(long previousHash,char currentChar,int subtractor, long multiplier); public long hash(int from, int to) { int windowSize = to-from + 1; // System.out.println("window Size::"+windowSize); if(from < 0 || to < 0) { return 0; } long collectedHash = (hashArray[to]-((from <=0) ? 0 : hashArray[from-1] * baseArray[windowSize])); //System.out.println("Collected Hash::"+collectedHash); return collectedHash; } } abstract class AbstractStringHash implements StringHash { protected final long DEFAULT_MAULTIPLIER ; public AbstractStringHash() { // Random randomBehaviour = new Random(547315431513L + System.currentTimeMillis()) ; // int randomNumber = randomBehaviour.nextInt(Integer.MAX_VALUE); // randomNumber = IntegerUtils.nextPrime(randomNumber); // DEFAULT_MAULTIPLIER = 31; } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
0463d6021cabc6615738a4f0668b0e74
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Zfunction { // input String static char s[]; // z function static int z[]; // length of string s static int n; static void Zfunction() { int L = 0, R = 0; for (int i = 1; i < n; i++) { if (i > R) { L = R = i; while (R < n && s[R - L] == s[R]) R++; z[i] = R - L; R--; } else { int k = i - L; if (z[k] < R - i + 1) z[i] = z[k]; else { L = i; while (R < n && s[R - L] == s[R]) R++; z[i] = R - L; R--; } } } } public static void main(String[] args) throws IOException { BufferedReader buff = new BufferedReader(new InputStreamReader( System.in)); String input = buff.readLine(); s = input.toCharArray(); z = new int[s.length]; n = s.length; Zfunction(); int max = 0; for (int i = 1; i < z.length; i++) { max = Math.max(max, Math.min(z[i], (z.length - i - 1))); } int ans = -1; for (int i = z.length - max; i < z.length; i++) { if (i + z[i] == z.length) { ans = z.length - i; break; } } if (ans == -1) { System.out.println("Just a legend"); } else { System.out.println(input.substring(0, ans)); } } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
a8f569eb550dd24d7b383e6ad854a0a6
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { String s = in.readString(); int[] z = Z.Zfunction(s); String res = "Just a legend"; int maxZ = 0; for (int i = 1; i < z.length; i++) { if (i + z[i] == z.length && maxZ >= z.length - i) { res = s.substring(i); break; } maxZ = Math.max(maxZ, z[i]); } out.printLine(res); } } 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 readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } 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 print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class Z { /** * z[i] = Maximum length substring [i : ] that is also a prefix of the string s * z[0] generally not defined. Taken to be 0 here. * Runtime = O(n) * Invariant : Maintain interval [L, R] with maximum R such that S[L : R] is a prefix substring */ public static int[] Zfunction(String s) { int n = s.length(); int[] z = new int[n]; for (int i = 1, l = 0, r = 0; i < n; i++) { // Set existing match from the beginning of string if (i <= r) { z[i] = Math.min(z[i - l], r - i + 1); } // Extend match while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) { ++z[i]; } // Update [L, R] if (i + z[i] - 1 > r) { l = i; r = i + z[i] - 1; } } return z; } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
76d768d1aa9c08c4e15db90b8c2c036f
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.util.Arrays; import java.util.Scanner; import java.util.TreeSet; public class ZValues { public static int[] zValues(String s) { int[] z = new int[s.length()]; z[0] = s.length(); int l = 0; int r = 0; int j = 0; for (int i = 1; i < s.length(); i++) { j = i; if (r < i) { for (int k = 0; j < s.length(); j++, k++) if (s.charAt(j) != s.charAt(k)) break; z[i] = j - i; r = z[i] + i - 1; l = i; // System.out.println(i + " " + l + " " + r); continue; } int index = i - l; int length = r - i + 1; //System.out.println(i + " " + l + " " + r); if (z[index] < length) { z[i] = z[index]; continue; } j = length + i; for (int k = length; j < s.length(); j++, k++) if (s.charAt(j) != s.charAt(k)) break; z[i] = length + j - 1 - r; r = i + z[i] - 1; l = i; // System.out.println(i + " " + l + " " +r); } return z; } public static void main(String[] args) { Scanner br = new Scanner(System.in); String s = br.next(); boolean alla = true; for(int i = 0;i<s.length();i++){ if(s.charAt(i) != 'a'){ alla = false; } } if(s.length() > 100 && alla){ System.out.println(s.substring(1, s.length()-1)); return; } int[] zvals = zValues(s); // System.out.println(Arrays.toString(zvals)); TreeSet<Integer> suff = new TreeSet<Integer>(); int max = 0; int maxi = -1; for(int i = s.length()-1;i>0;i--){ int len = Math.min(zvals[i], s.length()-i-1); if(suff.floor(len) != null){ int cur = suff.floor(len); if(cur > max){ max = cur; maxi = i; } } if(zvals[i] == s.length()-i){ suff.add(zvals[i]); } } if(max == 0){ System.out.println("Just a legend"); } else{ System.out.println(s.substring(maxi, maxi+max)); } } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
4a961ed1d48bf6a6e6c7c413c667b77b
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.util.*; public class ZValues { public static void main(String[] args){ Scanner br = new Scanner(System.in); String s = br.next(); boolean alla = true; for(int i = 0;i<s.length();i++){ if(s.charAt(i) != 'a'){ alla = false; } } if(s.length() > 100 && alla){ System.out.println(s.substring(1, s.length()-1)); return; } int[] zvals = getZValues(s); TreeSet<Integer> suff = new TreeSet<Integer>(); int max = 0; int maxi = -1; for(int i = s.length()-1;i>0;i--){ int len = Math.min(zvals[i], s.length()-i-1); if(suff.floor(len) != null){ int cur = suff.floor(len); if(cur > max){ max = cur; maxi = i; } } if(zvals[i] == s.length()-i){ suff.add(zvals[i]); } } if(max == 0){ System.out.println("Just a legend"); } else{ System.out.println(s.substring(maxi, maxi+max)); } } public static int[] getZValues(String s){ int[] zvals = new int[s.length()]; int l = 0; int r = 0; zvals[0] = s.length(); int ops = 0; for(int i = 1;i<s.length();i++){ if(r < i){ int len = 0; l = i; r = i; while(r < s.length() && s.charAt(r) == s.charAt(len)){ len++; r++; ops++; } r--; zvals[i] = len; } else{ int len = zvals[i-l]; if(i+len > r){ len = Math.min(len, r-i); while(r < s.length() && s.charAt(r) == s.charAt(len)){ r++; len++; ops++; } r--; l = i; } zvals[i] = Math.min(len, s.length()-i); } } return zvals; } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
d669be7f911156c20259d1cbce3ccb7f
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.util.*; public class ZValues { public static void main(String[] args){ Scanner br = new Scanner(System.in); String s = br.next(); boolean alla = true; for(int i = 0;i<s.length();i++){ if(s.charAt(i) != 'a'){ alla = false; } } if(s.length() > 100 && alla){ System.out.println(s.substring(1, s.length()-1)); return; } int[] zvals = getZValues(s); TreeSet<Integer> suff = new TreeSet<Integer>(); int max = 0; int maxi = -1; for(int i = s.length()-1;i>0;i--){ int len = Math.min(zvals[i], s.length()-i-1); if(suff.floor(len) != null){ int cur = suff.floor(len); if(cur > max){ max = cur; maxi = i; } } if(zvals[i] == s.length()-i){ suff.add(zvals[i]); } } if(max == 0){ System.out.println("Just a legend"); } else{ System.out.println(s.substring(maxi, maxi+max)); } } public static int[] getZValues(String s){ int[] zvals = new int[s.length()]; int l = 0; int r = 0; zvals[0] = s.length(); int ops = 0; for(int i = 1;i<s.length();i++){ if(r < i){ int len = 0; l = i; r = i; while(r < s.length() && s.charAt(r) == s.charAt(len)){ len++; r++; ops++; } r--; zvals[i] = len; } else{ int len = zvals[i-l]; if(i+len >= r){ len = Math.min(len, r-i); while(r < s.length() && s.charAt(r) == s.charAt(len)){ r++; len++; ops++; } r--; l = i; } zvals[i] = Math.min(len, s.length()-i); } } return zvals; } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
4ac3dae1609f6a6a18e94f44880f472b
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
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.Stack; public class ProblemB { static final long PRM = 1000000009; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); char[] line = in.readLine().toCharArray(); int len = line.length; long[] prmp = new long[len+1]; prmp[0] = 1; for (int i = 1 ; i <= len ; i++) { prmp[i] = prmp[i-1] * PRM; } long[] prehash = new long[len+1]; long[] sufhash = new long[len+1]; for (int i = 0 ; i < len ; i++) { prehash[i+1] = prehash[i]; prehash[i+1] *= PRM; prehash[i+1] += line[i]; } for (int i = 0 ; i < len ; i++) { sufhash[i+1] = sufhash[i]; sufhash[i+1] += prmp[i] * line[len-i-1]; } int max = 0; for (int k = len - 2 ; k >= 1 ; k--) { if (prehash[k] == sufhash[k]) { int head = 1; int tail = 1+k; long hash = 0; for (int u = 1 ; u < tail ; u++) { hash += prmp[k-u] * line[u]; } if (hash == prehash[k]) { max = k; break; } boolean found = false; while (tail < len-1) { hash *= PRM; hash -= prmp[k] * line[head]; hash += line[tail]; tail++; head++; if (hash == prehash[k]) { found = true; break; } } if (found) { max = k; break; } } } if (max == 0) { out.println("Just a legend"); } else { out.println(String.valueOf(line).substring(0, max)); } out.flush(); } public static void debug(Object... o) { System.err.println(Arrays.deepToString(o)); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
d09f3065b25912bb5b66b4ad54ba9bd5
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.*; import java.util.*; import java.awt.*; import java.math.*; public class Main { static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out) ); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st = new StringTokenizer(""); static String next() throws Exception { while (!st.hasMoreTokens()) { String s = br.readLine(); if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } public static void main(String[] asda) throws Exception { // int CASES = Integer.parseInt( next() ); String s = next(); int Z [] = Z( s ); int N = Z.length; int max = 0; int len = 0; for (int i = 1; i < N; i++) { if ( N - i == Z[i] && max >= N - i ) { // suffix len = N - i; break; } max = Math.max(max, Z[i] ); } out.println( len == 0 ? "Just a legend" : s.substring(0, len) ); // out.flush(); System.exit(0); } static int [] Z(String s) { int N = s.length(); int L, R; int Z [] = new int [N]; L = R = 0; for (int i = 1; i < N; i++) { if ( i > R ) { L = R = i; while ( R < N && s.charAt(R - L) == s.charAt(R) ) R++; Z[i] = R-- - L; continue; } int k = i - L; if ( Z[k] < R - i + 1 ) { Z[i] = Z[k]; continue; } L = i; while ( R < N && s.charAt(R - L) == s.charAt(R) ) R++; Z[i] = R-- - L; } return Z; } } /** * 1 12 3 3 5 3 1 2 10 5 3 8 6 4 **/
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
547e38cbac03036108e4e581b6251e08
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.util.*; import java.util.LinkedList; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.math.BigInteger; public class tmp { public static void main(String [] args) throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // StringTokenizer st = new StringTokenizer(in.readLine()); StringBuilder sb = new StringBuilder(); String s = in.readLine(); char [] pat = s.toCharArray(); int M = pat.length; int [] p = new int[M]; int j = 0; for(int i = 1; i < M; i++){ while(j > 0 && pat[j] != pat[i]) j = p[j-1]; if(pat[j] == pat[i]) j++; p[i] = j; } // System.out.println(Arrays.toString(p)); if(M < 3) System.out.println("Just a legend"); else if( p[M-1] == 0){ System.out.println("Just a legend"); }else{ for(int i=1; i<M-1; i++){ if(p[i] == p[M-1]){ System.out.println(s.substring(0,p[M-1])); return; } } if(p[p[M-1]-1] == 0){ System.out.println("Just a legend"); }else{ System.out.println(s.substring(0,p[p[M-1]-1])); } } } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
49bc3f73c9815d8c14f2786b21493687
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.StringTokenizer; /* * This is the default template for Java * */ public class CF126B { private static FastScanner in; private static PrintStream out; private static Set<Integer> st = null; public static void main(String[] args) throws IOException { InputStream inputStream = System.in; in = new FastScanner(inputStream); out = System.out; solve(); out.close(); } private static int[] getNext(String p) { int len = p.length(); int i,j; i = 0; j = -1; int[] next = new int[len]; next[0] = -1; for (i = 1; i < len; ++i) { while (j > -1 && p.charAt(j+1) != p.charAt(i)) j = next[j]; if (p.charAt(j+1) == p.charAt(i)) ++j; next[i] = j; } st = new HashSet<Integer>(); for (i = 0; i < len-1; i++) { if (next[i] > -1) st.add(next[i]); } return next; } private static void solve() throws IOException { String s = in.next(); int[] next = getNext(s); int i = s.length() - 1; while (next[i] != -1) { if (st.contains(next[i])) { out.println(s.substring(0, next[i]+1)); return; } i = next[i]; } out.println("Just a legend"); } private static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public boolean hasNext() { while (st == null || !st.hasMoreTokens()) { try { String line = br.readLine(); if (line == null) { return false; } st = new StringTokenizer(line); } catch (IOException e) { e.printStackTrace(); } } if (st != null && st.hasMoreTokens()) { return true; } return false; } public String next() { if (hasNext()) { return st.nextToken(); } return null; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
364ebbd85737c3098899662859185bac
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.Scanner; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.util.InputMismatchException; /** * Ashesh Vidyut (Drift King) * */ public class B { public static void main(String[] args) { try { InputReader in = new InputReader(System.in); String s = in.readLine(); char pat[] = s.toCharArray(); int pf[] = prefixFunction(pat); if(pf[pf.length - 1] == 0){ System.out.println("Just a legend"); return; } int k = pf[pf.length - 1]; boolean hasMatchedInner[] = new boolean[pf.length]; for (int i = 1; i < s.length() - 1; i++) { hasMatchedInner[pf[i]] = true; } while(k > 0){ if(hasMatchedInner[k]){ System.out.println(s.substring(0, k)); return; } k = pf[k - 1]; } System.out.println("Just a legend"); } catch (Exception e) { e.printStackTrace(); } } public static int[] prefixFunction(char pat[]){ int m = pat.length; int p[] = new int[m]; int k = 0; p[0] = 0; for (int i = 1; i < m; i++) { while(k > 0 && pat[k] != pat[i]){ k = p[k - 1]; } if(pat[k] == pat[i]){ ++k; } p[i] = k; } return p; } } class InputReader { private boolean finished = false; 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 peek() { if (numChars == -1) return -1; if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { return -1; } 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 length = readInt(); if (length < 0) return null; byte[] bytes = new byte[length]; for (int i = 0; i < length; i++) bytes[i] = (byte) read(); try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { return new String(bytes); } } public static 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; } public boolean isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value == -1; } public String next() { return readString(); } public boolean readBoolean() { return readInt() == 1; } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
355a3224ac7bee9f9c57d7ada673c0ad
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.LinkedList; public class Main { static int[] z; static void Z_fun(String s) { char[] c = s.toCharArray(); int L = 0, R = 0; for (int i = 1; i < c.length; i++) { if (i > R) { L = R = i; while (R < c.length && c[R - L] == c[R]) R++; z[i] = (R--) - L; } else { int k = i - L; if (z[k] < R - i + 1) z[i] = z[k]; else { L = i; while (R < c.length && c[R - L] == c[R]) R++; z[i] = (R--) - L; } } } } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); String s; s = br.readLine(); z = new int[s.length()]; Z_fun(s); int maxz = 0, res = 0; int n = s.length(); for (int j = 1; j < n; j++) { if (z[j] == n - j && maxz >= n - j) { res = n - j; break; } maxz = Math.max(maxz, z[j]); } if (res == 0) out.append("Just a legend"); else { for (int j = 0; j < res; j++) out.append(s.charAt(j)); } System.out.print(out); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
78b367764f60317eea48c6d90d74d4d0
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.io.*; import java.util.*; public final class password { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static FastScanner sc=new FastScanner(br); static PrintWriter out=new PrintWriter(System.out); static long[] pow1,pow2,inv1,inv2; static long mod1=(long)(1e9+7),mod2=(long)(1e9+9),base=37; static int maxn=(int)(1e6+1); static List<Integer> list=new ArrayList<Integer>(); static long[] hash1,hash2; static long pow(long a,long b,long mod) { long x=1,y=a; while(b>0) { if(b%2==1) { x=(x*y)%mod; } y=(y*y)%mod; b=b/2; } return x; } static long mod_inv(long a,long mod) { return pow(a,mod-2,mod); } public static void main(String args[]) throws Exception { pow1=new long[maxn];pow2=new long[maxn];pow1[0]=pow2[0]=1;inv1=new long[maxn];inv2=new long[maxn];inv1[0]=inv2[0]=1; for(int i=1;i<maxn;i++) { pow1[i]=(pow1[i-1]*base)%mod1; pow2[i]=(pow2[i-1]*base)%mod2; } inv1[maxn-1]=mod_inv(pow1[maxn-1],mod1);inv2[maxn-1]=mod_inv(pow2[maxn-1],mod2); for(int i=maxn-2;i>=0;i--) { inv1[i]=(inv1[i+1]*base)%mod1; inv2[i]=(inv2[i+1]*base)%mod2; } // finished all preprocessing... char[] a=sc.next().toCharArray();long curr1=0,curr2=0,curr3=0,curr4=0;hash1=new long[a.length];hash2=new long[a.length]; for(int i=0,j=0,k=a.length-1;i<a.length;i++,j++,k--) { curr1=(curr1+((a[i]-'a'+1)*pow1[j]))%mod1; curr1=(curr1%mod1+mod1)%mod1; curr2=(curr2+((a[i]-'a'+1)*pow2[j]))%mod2; curr2=(curr2%mod2+mod2)%mod2; curr3=(curr3*base)%mod1; curr3=(curr3%mod1+mod1)%mod1; curr3=(curr3+(a[k]-'a'+1))%mod1; curr3=(curr3%mod1+mod1)%mod1; curr4=(curr4*base)%mod2; curr4=(curr4%mod2+mod2)%mod2; curr4=(curr4+(a[k]-'a'+1))%mod2; curr4=(curr4%mod2+mod2)%mod2; if(curr1==curr3 && curr2==curr4) { list.add(i+1); } hash1[i]=curr1;hash2[i]=curr2; } if(list.size()>1) { int low=0,high=list.size()-1; while(low<high) { int mid=(low+high+1)>>1,val=list.get(mid);boolean curr=false; long now1=hash1[val-1],now2=hash2[val-1]; for(int i=1;i+val-1<a.length-1;i++) { long ll1=(hash1[i+val-1]-hash1[i-1])%mod1; ll1=(ll1%mod1+mod1)%mod1; ll1=(ll1*inv1[i])%mod1; ll1=(ll1%mod1+mod1)%mod1; long ll2=(hash2[i+val-1]-hash2[i-1])%mod2; ll2=(ll2%mod2+mod2)%mod2; ll2=(ll2*inv2[i])%mod2; ll2=(ll2%mod2+mod2)%mod2; if(ll1==now1 && ll2==now2) { curr=true; break; } } if(curr) { low=mid; } else { high=mid-1; } } int val=list.get(low);boolean b=false; long now1=hash1[val-1],now2=hash2[val-1]; for(int i=1;i+val-1<a.length-1;i++) { long ll1=(hash1[i+val-1]-hash1[i-1])%mod1; ll1=(ll1%mod1+mod1)%mod1; ll1=(ll1*inv1[i])%mod1; ll1=(ll1%mod1+mod1)%mod1; long ll2=(hash2[i+val-1]-hash2[i-1])%mod2; ll2=(ll2%mod2+mod2)%mod2; ll2=(ll2*inv2[i])%mod2; ll2=(ll2%mod2+mod2)%mod2; if(ll1==now1 && ll2==now2) { b=true; break; } } if(b) { for(int i=0;i<list.get(low);i++) { out.print(a[i]); } out.println(""); } else { out.println("Just a legend"); } } else { out.println("Just a legend"); } out.close(); } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public String next() throws Exception { return nextToken().toString(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
897d4fb98fec9ba2a4778d6c1c222984
train_001.jsonl
1320858000
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.
256 megabytes
import java.util.Scanner; public class Password { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); int max = -1; int[] next = new int[s.length()+2]; next[0] = -1; int j = -1; for (int i = 1; i < s.length(); i++) { while (j != -1 && s.charAt(i) != s.charAt(j+1)) j = next[j]; if (s.charAt(i) == s.charAt(j+1)) j++; next[i] = j; if (i < s.length()-1 && j > max) max = j; } j = next[s.length()-1]; while (j > max) j = next[j]; //System.out.println(j + " " + max); if (max >= 0 && j >= 0){ System.out.println(s.substring(0, Math.min(max, j)+1)); } else { System.out.println("Just a legend"); } sc.close(); } }
Java
["fixprefixsuffix", "abcdabc"]
2 seconds
["fix", "Just a legend"]
null
Java 7
standard input
[ "dp", "hashing", "string suffix structures", "binary search", "strings" ]
fd94aea7ca077ee2806653d22d006fb1
You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.
1,700
Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.
standard output
PASSED
0969498ca0e49a056d4f627a444f7f7d
train_001.jsonl
1471698300
Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples.For example, triples (3, 4, 5), (5, 12, 13) and (6, 8, 10) are Pythagorean triples.Here Katya wondered if she can specify the length of some side of right triangle and find any Pythagorean triple corresponding to such length? Note that the side which length is specified can be a cathetus as well as hypotenuse.Katya had no problems with completing this task. Will you do the same?
256 megabytes
import java.util.Scanner; public class PythagoreanTriples { public static void main(String[] args) { Scanner in = new Scanner(System.in); long num = in.nextLong(); if (num <= 2) { System.out.println("-1"); return; } if (num % 2 == 0) { num /= 2; System.out.println(((num * num) - 1) + " " + ((num * num) + 1)); } else { long temp = ((num * num) - 1) / 2; if (temp % 1 == 0) { System.out.println((long)temp + " " + (long)(temp + 1)); } else { System.out.println(-1); } } } }
Java
["3", "6", "1", "17", "67"]
1 second
["4 5", "8 10", "-1", "144 145", "2244 2245"]
NoteIllustration for the first sample.
Java 8
standard input
[ "number theory", "math" ]
df92643983d6866cfe406f2b36bec17f
The only line of the input contains single integer n (1 ≀ n ≀ 109)Β β€” the length of some side of a right triangle.
1,500
Print two integers m and k (1 ≀ m, k ≀ 1018), such that n, m and k form a Pythagorean triple, in the only line. In case if there is no any Pythagorean triple containing integer n, print  - 1 in the only line. If there are many answers, print any of them.
standard output
PASSED
8649b03527716e86e40ba81e2b59506a
train_001.jsonl
1471698300
Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples.For example, triples (3, 4, 5), (5, 12, 13) and (6, 8, 10) are Pythagorean triples.Here Katya wondered if she can specify the length of some side of right triangle and find any Pythagorean triple corresponding to such length? Note that the side which length is specified can be a cathetus as well as hypotenuse.Katya had no problems with completing this task. Will you do the same?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import static java.lang.Math.*; public class Main { private FastScanner scanner = new FastScanner(); public static void main(String[] args) { new Main().solve(); } int p[]; List<List<Integer>> gr = new ArrayList<>(); void dfs(int v, int pr) { p[v] = pr; for (int next: gr.get(v)) { if (pr != next) { dfs(next, v); } } } private void solve() { long n = scanner.nextLong(); if (n == 1 || n == 2) { System.out.print(-1); return; } if (n % 2 == 1) { long b = (n * n - 1) / 2; System.out.print(b + " " + (b + 1)); } else { n = n / 2; if (n % 2 == 0) { System.out.print( n / 2 * 3 + " " + n / 2 * 5); } else { long b = (n * n - 1) / 2; System.out.print(2 * b + " " + 2 * (b + 1)); } } } boolean check(char[] c, int cnt, int k) { if (k < cnt) { return false; } Map<Character, Integer> used = new HashMap<>(); for (int i = 0; i < k; i++) { used.put(c[i], used.getOrDefault(c[i],0) + 1); } if (used.keySet().size() >= cnt) { return true; } cnt -= used.keySet().size(); for (int i = k; i < c.length; i++) { used.put(c[i - k], used.get(c[i - k]) - 1); if (used.get(c[i - k]) == 0) { cnt ++; } if (used.containsKey(c[i]) && used.get(c[i]) > 0) { used.put(c[i], used.get(c[i]) + 1); } else { used.put(c[i], 1); cnt--; } if (cnt == 0) { return true; } } return false; } class FastScanner { BufferedReader reader; StringTokenizer tokenizer; FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(next()); } Integer[] nextA(int n) { Integer a[] = new Integer[n]; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); } return a; } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } } }
Java
["3", "6", "1", "17", "67"]
1 second
["4 5", "8 10", "-1", "144 145", "2244 2245"]
NoteIllustration for the first sample.
Java 8
standard input
[ "number theory", "math" ]
df92643983d6866cfe406f2b36bec17f
The only line of the input contains single integer n (1 ≀ n ≀ 109)Β β€” the length of some side of a right triangle.
1,500
Print two integers m and k (1 ≀ m, k ≀ 1018), such that n, m and k form a Pythagorean triple, in the only line. In case if there is no any Pythagorean triple containing integer n, print  - 1 in the only line. If there are many answers, print any of them.
standard output
PASSED
03526d3a7b3547534ad6cdbd3e9187c0
train_001.jsonl
1471698300
Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples.For example, triples (3, 4, 5), (5, 12, 13) and (6, 8, 10) are Pythagorean triples.Here Katya wondered if she can specify the length of some side of right triangle and find any Pythagorean triple corresponding to such length? Note that the side which length is specified can be a cathetus as well as hypotenuse.Katya had no problems with completing this task. Will you do the same?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top * * @author xwchen */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { long n = in.nextLong(); long m, k; if (n % 2 == 1) { m = (n * n - 1) / 2; k = (n * n + 1) / 2; } else { m = (n * n / 4 - 1); k = (n * n / 4 + 1); } if (m > 0) { out.println(m + " " + k); } else { out.println(-1); } } } }
Java
["3", "6", "1", "17", "67"]
1 second
["4 5", "8 10", "-1", "144 145", "2244 2245"]
NoteIllustration for the first sample.
Java 8
standard input
[ "number theory", "math" ]
df92643983d6866cfe406f2b36bec17f
The only line of the input contains single integer n (1 ≀ n ≀ 109)Β β€” the length of some side of a right triangle.
1,500
Print two integers m and k (1 ≀ m, k ≀ 1018), such that n, m and k form a Pythagorean triple, in the only line. In case if there is no any Pythagorean triple containing integer n, print  - 1 in the only line. If there are many answers, print any of them.
standard output
PASSED
96ae770ec84a5ca52e4f13a0655f301c
train_001.jsonl
1471698300
Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples.For example, triples (3, 4, 5), (5, 12, 13) and (6, 8, 10) are Pythagorean triples.Here Katya wondered if she can specify the length of some side of right triangle and find any Pythagorean triple corresponding to such length? Note that the side which length is specified can be a cathetus as well as hypotenuse.Katya had no problems with completing this task. Will you do the same?
256 megabytes
import java.util.Scanner; public class Tasks { public static void main(String[] args) { Scanner in = new Scanner(System.in); long a = in.nextLong(); if ((a == 2) || (a == 1)) { System.out.println("-1"); return; } long b; if (a % 2 == 1) { System.out.print(a * a / 2); System.out.print(' '); System.out.print(a * a / 2 + 1); return; } if (a % 2 == 0 && a / 2 % 2 == 0) { System.out.print(3 * a / 4); System.out.print(' '); System.out.print(5 * a / 4); return; } if (a % 2 == 0 && a / 2 % 2 == 1) { System.out.print(a/2*a/2/2* 2); System.out.print(' '); System.out.print((a/2*a/2/2 + 1) * 2); return; } } }
Java
["3", "6", "1", "17", "67"]
1 second
["4 5", "8 10", "-1", "144 145", "2244 2245"]
NoteIllustration for the first sample.
Java 8
standard input
[ "number theory", "math" ]
df92643983d6866cfe406f2b36bec17f
The only line of the input contains single integer n (1 ≀ n ≀ 109)Β β€” the length of some side of a right triangle.
1,500
Print two integers m and k (1 ≀ m, k ≀ 1018), such that n, m and k form a Pythagorean triple, in the only line. In case if there is no any Pythagorean triple containing integer n, print  - 1 in the only line. If there are many answers, print any of them.
standard output
PASSED
7a4478a246391b03694a03f80a3b79c3
train_001.jsonl
1471698300
Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples.For example, triples (3, 4, 5), (5, 12, 13) and (6, 8, 10) are Pythagorean triples.Here Katya wondered if she can specify the length of some side of right triangle and find any Pythagorean triple corresponding to such length? Note that the side which length is specified can be a cathetus as well as hypotenuse.Katya had no problems with completing this task. Will you do the same?
256 megabytes
import java.util.*; import java.awt.geom.*; import java.io.*; import java.math.*; public class Main { public static void main(String[] args) { long startTime = System.nanoTime(); int n=in.nextInt(); Long M=0L; Long N=0L; if(n%2==0 && n>2) { n/=2; M=(long)n; N=1L; if(isValid(M,N)) { out.println( (M*M+N*N) + " " + (M*M-N*N)); exit(0); } } else { ArrayList<Integer> div=divisors(n); Long [] data=find(div); M=data[0]; N=data[1]; if(M!=0 && N!=0 && isValid(M,N)) { out.println( (2*M*N) + " " + (M*M+N*N)); exit(0); } } if(M==0 && N==0) { for(int i=1;i<=Math.sqrt(n);i++) { if(isPerfectSquare(n-i*i)) { M=(long) Math.max(i,Math.floor(Math.sqrt(n-i*i))); N=(long) Math.min(i,Math.floor(Math.sqrt(n-i*i))); } } } if(M!=0 && N!=0 && isValid(M,N)) { out.println( (2*M*N) + " " + (M*M-N*N)); } else { out.println("-1"); } long endTime = System.nanoTime(); err.println("Execution Time : +" + (endTime-startTime)/1000000 + " ms"); exit(0); } static boolean isValid(long M,long N) { long a=M*M-N*N; long b=2*M*N; long c=M*M+N*N; if(a*a+b*b!=c*c) return false; if(a+b <= c) return false; return true; } static boolean isPerfectSquare(int n) { return Math.ceil(Math.sqrt(n))==Math.floor(Math.sqrt(n)); } static ArrayList<Integer> divisors(int a) { ArrayList<Integer> div=new ArrayList<Integer> (); div.add(1); for(int i=2;i*i<=a && i*i >0 ;i++) { if(a%i==0) { div.add(i); if(i*i!=a) { div.add(a/i); } } } div.add(a); return div; } static Long [] find(ArrayList<Integer> divisors) { Long [] data=new Long[2]; data[0]=0L;data[1]=0L; for(int i=0;i<divisors.size()/2;i++) { long d1=divisors.get(i)+divisors.get(divisors.size()-i-1); long d2=-divisors.get(i)+divisors.get(divisors.size()-i-1); if(d1%2==0 && d2%2==0) { data[0]=d1/2; data[1]=d2/2; return data; } } return data; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } static void exit(int a) { out.close(); err.close(); System.exit(a); } static InputStream inputStream = System.in; static OutputStream outputStream = System.out; static OutputStream errStream = System.err; static InputReader in = new InputReader(inputStream); static PrintWriter out = new PrintWriter(outputStream); static PrintWriter err = new PrintWriter(errStream); }
Java
["3", "6", "1", "17", "67"]
1 second
["4 5", "8 10", "-1", "144 145", "2244 2245"]
NoteIllustration for the first sample.
Java 8
standard input
[ "number theory", "math" ]
df92643983d6866cfe406f2b36bec17f
The only line of the input contains single integer n (1 ≀ n ≀ 109)Β β€” the length of some side of a right triangle.
1,500
Print two integers m and k (1 ≀ m, k ≀ 1018), such that n, m and k form a Pythagorean triple, in the only line. In case if there is no any Pythagorean triple containing integer n, print  - 1 in the only line. If there are many answers, print any of them.
standard output
PASSED
ebef4c9f228307e9380db92b172f3479
train_001.jsonl
1471698300
Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples.For example, triples (3, 4, 5), (5, 12, 13) and (6, 8, 10) are Pythagorean triples.Here Katya wondered if she can specify the length of some side of right triangle and find any Pythagorean triple corresponding to such length? Note that the side which length is specified can be a cathetus as well as hypotenuse.Katya had no problems with completing this task. Will you do the same?
256 megabytes
import java.util.*; import java.awt.geom.*; import java.io.*; import java.math.*; public class Main { public static void main(String[] args) { long startTime = System.nanoTime(); int n=in.nextInt(); Long M=0L; Long N=0L; if(n%2==0 && n>2) { n/=2; M=(long)n; N=1L; if(isValid(M,N)) { out.println( (M*M+N*N) + " " + (M*M-N*N)); exit(0); } } else { ArrayList<Integer> div=divisors(n); Long [] data=find(div); M=data[0]; N=data[1]; if(M!=0 && N!=0 && isValid(M,N)) { out.println( (2*M*N) + " " + (M*M+N*N)); exit(0); } } if(M==0 && N==0) { for(int i=1;i<=Math.sqrt(n);i++) { if(isPerfectSquare(n-i*i)) { M=(long) Math.max(i,Math.floor(Math.sqrt(n-i*i))); N=(long) Math.min(i,Math.floor(Math.sqrt(n-i*i))); break; } } } if(M!=0 && N!=0 && isValid(M,N)) { out.println( (2*M*N) + " " + (M*M-N*N)); } else { out.println("-1"); } long endTime = System.nanoTime(); err.println("Execution Time : +" + (endTime-startTime)/1000000 + " ms"); exit(0); } static boolean isValid(long M,long N) { long a=M*M-N*N; long b=2*M*N; long c=M*M+N*N; if(a*a+b*b!=c*c) return false; if(a+b <= c) return false; return true; } static boolean isPerfectSquare(int n) { return Math.ceil(Math.sqrt(n))==Math.floor(Math.sqrt(n)); } static ArrayList<Integer> divisors(int a) { ArrayList<Integer> div=new ArrayList<Integer> (); div.add(1); for(int i=2;i*i<=a && i*i >0 ;i++) { if(a%i==0) { div.add(i); if(i*i!=a) { div.add(a/i); } } } div.add(a); return div; } static Long [] find(ArrayList<Integer> divisors) { Long [] data=new Long[2]; data[0]=0L;data[1]=0L; for(int i=0;i<divisors.size()/2;i++) { long d1=divisors.get(i)+divisors.get(divisors.size()-i-1); long d2=-divisors.get(i)+divisors.get(divisors.size()-i-1); if(d1%2==0 && d2%2==0) { data[0]=d1/2; data[1]=d2/2; return data; } } return data; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } static void exit(int a) { out.close(); err.close(); System.exit(a); } static InputStream inputStream = System.in; static OutputStream outputStream = System.out; static OutputStream errStream = System.err; static InputReader in = new InputReader(inputStream); static PrintWriter out = new PrintWriter(outputStream); static PrintWriter err = new PrintWriter(errStream); }
Java
["3", "6", "1", "17", "67"]
1 second
["4 5", "8 10", "-1", "144 145", "2244 2245"]
NoteIllustration for the first sample.
Java 8
standard input
[ "number theory", "math" ]
df92643983d6866cfe406f2b36bec17f
The only line of the input contains single integer n (1 ≀ n ≀ 109)Β β€” the length of some side of a right triangle.
1,500
Print two integers m and k (1 ≀ m, k ≀ 1018), such that n, m and k form a Pythagorean triple, in the only line. In case if there is no any Pythagorean triple containing integer n, print  - 1 in the only line. If there are many answers, print any of them.
standard output
PASSED
9edc1850b400444292d96ba1fe80512d
train_001.jsonl
1471698300
Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples.For example, triples (3, 4, 5), (5, 12, 13) and (6, 8, 10) are Pythagorean triples.Here Katya wondered if she can specify the length of some side of right triangle and find any Pythagorean triple corresponding to such length? Note that the side which length is specified can be a cathetus as well as hypotenuse.Katya had no problems with completing this task. Will you do the same?
256 megabytes
import java.util.*; import java.io.*; public class Main{ /* . . . . . . . some constants . */ /* . . . if any . . */ public static void main(String[] args) throws IOException{ /* . . . . . . */ long n=nl(); long m,k; if(n%2==1){ k=(n*n+1)/2; m=k-1; } else{ k=(n*n)/4 + 1; m=k-2; } if(m==0 || k==0){ sop(-1); return; } sop(m+" "+k); /* . . . . . . . */ } /* temporary functions . . */ /* fuctions . . . . . . . . . . . . . . . . . abcdefghijklmnopqrstuvwxyz . . . . . . */ static int modulo(int j,int m){ if(j<0) return m+j; if(j>=m) return j-m; return j; } static final int mod=1000000007; static final double eps=1e-8; static final long inf=100000000000000000L; static final boolean debug=true; static Reader in=new Reader(); static StringBuilder ansa=new StringBuilder(); static long powm(long a,long b,long m){ long an=1; long c=a; while(b>0){ if(b%2==1) an=(an*c)%m; c=(c*c)%m; b>>=1; } return an; } static Random rn=new Random(); static void sop(Object a){System.out.println(a);} static int ni(){return in.nextInt();} static int[] nia(int n){int a[]=new int[n];for(int i=0;i<n;i++)a[i]=ni();return a;} static long nl(){return in.nextLong();} static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;} static String ns(){return in.next();} static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;} static double nd(){return in.nextDouble();} static double[] nda(int n){double a[]=new double[n];for(int i=0;i<n;i++)a[i]=nd();return a;} static class Reader{ public BufferedReader reader; public StringTokenizer tokenizer; public Reader(){ reader=new BufferedReader(new InputStreamReader(System.in),32768); tokenizer=null; } public String next(){ while(tokenizer==null || !tokenizer.hasMoreTokens()){ try{ tokenizer=new StringTokenizer(reader.readLine()); } catch(IOException e){ throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } }
Java
["3", "6", "1", "17", "67"]
1 second
["4 5", "8 10", "-1", "144 145", "2244 2245"]
NoteIllustration for the first sample.
Java 8
standard input
[ "number theory", "math" ]
df92643983d6866cfe406f2b36bec17f
The only line of the input contains single integer n (1 ≀ n ≀ 109)Β β€” the length of some side of a right triangle.
1,500
Print two integers m and k (1 ≀ m, k ≀ 1018), such that n, m and k form a Pythagorean triple, in the only line. In case if there is no any Pythagorean triple containing integer n, print  - 1 in the only line. If there are many answers, print any of them.
standard output