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
57f9475a263b2ee191e1d23ff0f7c5d2
train_003.jsonl
1605796500
You are given a string $$$s$$$, consisting of brackets of two types: '(', ')', '[' and ']'.A string is called a regular bracket sequence (RBS) if it's of one of the following types: empty string; '(' + RBS + ')'; '[' + RBS + ']'; RBS + RBS. where plus is a concatenation of two strings.In one move you can choose a non-empty subsequence of the string $$$s$$$ (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.What is the maximum number of moves you can perform?
256 megabytes
import java.util.*; import java.io.*; public class C { public static void main(String args[]) throws Exception { BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); Scanner sc = new Scanner (System.in); //int T = sc.nextInt(); int T = Integer.parseInt(br.readLine()); while(T-->0){ int count = 0; String s = br.readLine(); Queue<Character> b1 = new LinkedList<>(); Queue<Character> b2 = new LinkedList<>(); for(int i=0; i<s.length(); i++){ char ch = s.charAt(i); if(ch=='['){ b2.add(ch); } else if(ch=='('){ b1.add(ch); } else if(ch==']'){ if(b2.peek()!=null){ count++; b2.remove(); } } else if(ch==')'){ if(b1.peek()!=null){ count++; b1.remove(); } } } System.out.println(count); } } }
Java
["5\n()\n[]()\n([)]\n)]([\n)[(]"]
1 second
["1\n2\n2\n0\n1"]
NoteIn the first example you can just erase the whole string.In the second example you can first erase the brackets on positions $$$1$$$ and $$$2$$$: "[]()", then "()" is left. After that you can erase it whole. You could erase the whole string from the beginning but you would get one move instead of two.In the third example you can first erase the brackets on positions $$$1$$$ and $$$3$$$: "([)]". They form an RBS "()". Then "[]" is left, so you can erase it whole.In the fourth example there is no subsequence that is an RBS, so you can't perform a move at all.In the fifth example you can erase the brackets on positions $$$2$$$ and $$$4$$$: ")[(]" and get ")(" as a result. You can erase nothing from it.
Java 8
standard input
[ "greedy" ]
db9cec57d8ed5e914818ce9b439eb0f9
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Each of the next $$$t$$$ lines contains a non-empty string, consisting only of characters '(', ')', '[' and ']'. The total length of the strings over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
800
For each testcase print a single integer — the maximum number of moves you can perform on a given string $$$s$$$.
standard output
PASSED
5807777339af0a1bc2b630d56e5fb754
train_003.jsonl
1605796500
You are given a string $$$s$$$, consisting of brackets of two types: '(', ')', '[' and ']'.A string is called a regular bracket sequence (RBS) if it's of one of the following types: empty string; '(' + RBS + ')'; '[' + RBS + ']'; RBS + RBS. where plus is a concatenation of two strings.In one move you can choose a non-empty subsequence of the string $$$s$$$ (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.What is the maximum number of moves you can perform?
256 megabytes
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class C { public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner sc = new Scanner(System.in); int t= sc.nextInt(); while(t-->0) { String s= sc.next(); int count1 =0; int count0 =0; int count =0 ; //Hashmap<Integer, String> map = new Hashmap<Integer, String>(); Stack<Character> stack = new Stack<Character>(); for(int i = 0 ; i < s.length(); i++){ if(s.charAt(i) == '[' ){ count0++; } if(s.charAt(i) == '(' ){ count1++; } if(s.charAt(i) == ')' && count1 > 0){ count++; count1--; } if(s.charAt(i) == ']' && count0 > 0 ){ count++;count0--; } /* if(s.charAt(i) == '[' || s.charAt(i) == '(' ){ stack.push(s.charAt(i)); } else{ if(stack.isEmpty() == false && s.charAt(i) == ']' || s.charAt(i) == ')') continue; if(matching(stack.peek(), s.charAt(i)) == true ){ stack.pop(); count++; } }*/ } System.out.println(count); } } }
Java
["5\n()\n[]()\n([)]\n)]([\n)[(]"]
1 second
["1\n2\n2\n0\n1"]
NoteIn the first example you can just erase the whole string.In the second example you can first erase the brackets on positions $$$1$$$ and $$$2$$$: "[]()", then "()" is left. After that you can erase it whole. You could erase the whole string from the beginning but you would get one move instead of two.In the third example you can first erase the brackets on positions $$$1$$$ and $$$3$$$: "([)]". They form an RBS "()". Then "[]" is left, so you can erase it whole.In the fourth example there is no subsequence that is an RBS, so you can't perform a move at all.In the fifth example you can erase the brackets on positions $$$2$$$ and $$$4$$$: ")[(]" and get ")(" as a result. You can erase nothing from it.
Java 8
standard input
[ "greedy" ]
db9cec57d8ed5e914818ce9b439eb0f9
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Each of the next $$$t$$$ lines contains a non-empty string, consisting only of characters '(', ')', '[' and ']'. The total length of the strings over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
800
For each testcase print a single integer — the maximum number of moves you can perform on a given string $$$s$$$.
standard output
PASSED
0a8efee08b84b45cbab5e5dbce7c5e07
train_003.jsonl
1605796500
You are given a string $$$s$$$, consisting of brackets of two types: '(', ')', '[' and ']'.A string is called a regular bracket sequence (RBS) if it's of one of the following types: empty string; '(' + RBS + ')'; '[' + RBS + ']'; RBS + RBS. where plus is a concatenation of two strings.In one move you can choose a non-empty subsequence of the string $$$s$$$ (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.What is the maximum number of moves you can perform?
256 megabytes
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Scanner; import java.util.function.Function; import java.util.stream.Collectors; public class _C { static public void main(final String[] args) throws IOException { C._main(args); } //begin C.java static private class C extends Solver{public C(){nameIn="C.in";}String s;@Override protected void solve(){int pairs1=0;int sym1=0;int pairs2=0;int sym2=0;for(int i =0;i<s.length();i++){switch(s.charAt(i)){case '(':sym1++;break;case ')':if(sym1> 0){sym1--;pairs1++;}break;case '[':sym2++;break;case ']':if(sym2>0){sym2--;pairs2++ ;}break;}}pw.println(pairs1+pairs2);}@Override public void readInput()throws IOException {s=sc.nextLine().trim();}static public void _main(String[]args)throws IOException {new C().run();}} //end C.java //begin net/leksi/contest/Solver.java static private abstract class Solver{protected String nameIn=null;protected String nameOut=null;protected boolean singleTest=false;protected boolean preprocessDebug =false;protected boolean doNotPreprocess=false;protected Scanner sc=null;protected PrintWriter pw=null;private void process()throws IOException{if(!singleTest){int t=lineToIntArray()[0];while(t-->0){readInput();solve();}}else{readInput();solve( );}}abstract protected void readInput()throws IOException;abstract protected void solve()throws IOException;protected int[]lineToIntArray()throws IOException{return Arrays.stream(sc.nextLine().trim().split("\\s+")).mapToInt(Integer::valueOf).toArray ();}protected long[]lineToLongArray()throws IOException{return Arrays.stream(sc.nextLine ().trim().split("\\s+")).mapToLong(Long::valueOf).toArray();}protected String joinToString (final int[]a){return Arrays.stream(a).mapToObj(Integer::toString).collect(Collectors .joining(" "));}protected String joinToString(final long[]a){return Arrays.stream (a).mapToObj(Long::toString).collect(Collectors.joining(" "));}protected<T>String joinToString(final T[]a){return Arrays.stream(a).map(v->v.toString()).collect(Collectors .joining(" "));}protected<T>String joinToString(final T[]a,final Function<T,String> toString){return Arrays.stream(a).map(v->v.toString()).collect(Collectors.joining (" "));}protected<T>String joinToString(final Collection<T>a){return a.stream().map (v->v.toString()).collect(Collectors.joining(" "));}protected<T>String joinToString (final Collection<T>a,final Function<T,String>toString){return a.stream().map(v-> toString.apply(v)).collect(Collectors.joining(" "));}protected List<Long>intArrayToLongList (final int[]a){return Arrays.stream(a).mapToObj(Long::valueOf).collect(Collectors .toList());}protected List<Integer>toList(final int[]a){return Arrays.stream(a).mapToObj (Integer::valueOf).collect(Collectors.toList());}protected List<Long>toList(final long[]a){return Arrays.stream(a).mapToObj(Long::valueOf).collect(Collectors.toList ());}protected void run()throws IOException{boolean done=false;if(nameIn !=null) {try{try(FileInputStream fis=new FileInputStream(nameIn);PrintWriter pw0=select_output ();){done=true;sc=new Scanner(fis);pw=pw0;process();}}catch(IOException ex){}}if (!done){try(PrintWriter pw0=select_output();){sc=new Scanner(System.in);pw=pw0;process ();}}}private PrintWriter select_output()throws FileNotFoundException{if(nameOut !=null){return new PrintWriter(nameOut);}return new PrintWriter(System.out);}} //end net/leksi/contest/Solver.java }
Java
["5\n()\n[]()\n([)]\n)]([\n)[(]"]
1 second
["1\n2\n2\n0\n1"]
NoteIn the first example you can just erase the whole string.In the second example you can first erase the brackets on positions $$$1$$$ and $$$2$$$: "[]()", then "()" is left. After that you can erase it whole. You could erase the whole string from the beginning but you would get one move instead of two.In the third example you can first erase the brackets on positions $$$1$$$ and $$$3$$$: "([)]". They form an RBS "()". Then "[]" is left, so you can erase it whole.In the fourth example there is no subsequence that is an RBS, so you can't perform a move at all.In the fifth example you can erase the brackets on positions $$$2$$$ and $$$4$$$: ")[(]" and get ")(" as a result. You can erase nothing from it.
Java 8
standard input
[ "greedy" ]
db9cec57d8ed5e914818ce9b439eb0f9
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Each of the next $$$t$$$ lines contains a non-empty string, consisting only of characters '(', ')', '[' and ']'. The total length of the strings over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
800
For each testcase print a single integer — the maximum number of moves you can perform on a given string $$$s$$$.
standard output
PASSED
18eba599aaefa7b210a8d1e8a827c508
train_003.jsonl
1605796500
You are given a string $$$s$$$, consisting of brackets of two types: '(', ')', '[' and ']'.A string is called a regular bracket sequence (RBS) if it's of one of the following types: empty string; '(' + RBS + ')'; '[' + RBS + ']'; RBS + RBS. where plus is a concatenation of two strings.In one move you can choose a non-empty subsequence of the string $$$s$$$ (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.What is the maximum number of moves you can perform?
256 megabytes
//package a; import java.io.*; import java.util.*; public class A{ public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); // BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); // String str[]=br.readLine().trim().split("\\s+"); in:while(t-->0){ // int n=sc.nextInt(); //Stack<Integer>st=new Stack<>(); String s=sc.next(); int left=0,right=0,count=0; for(char c:s.toCharArray()){ if(c=='(')left++; if(c=='[')right++; if(c==')'&&left>0){ left--; count++; } if(c==']'&&right>0){ right--; count++; } } System.out.println(count); }//while }//main }//class
Java
["5\n()\n[]()\n([)]\n)]([\n)[(]"]
1 second
["1\n2\n2\n0\n1"]
NoteIn the first example you can just erase the whole string.In the second example you can first erase the brackets on positions $$$1$$$ and $$$2$$$: "[]()", then "()" is left. After that you can erase it whole. You could erase the whole string from the beginning but you would get one move instead of two.In the third example you can first erase the brackets on positions $$$1$$$ and $$$3$$$: "([)]". They form an RBS "()". Then "[]" is left, so you can erase it whole.In the fourth example there is no subsequence that is an RBS, so you can't perform a move at all.In the fifth example you can erase the brackets on positions $$$2$$$ and $$$4$$$: ")[(]" and get ")(" as a result. You can erase nothing from it.
Java 8
standard input
[ "greedy" ]
db9cec57d8ed5e914818ce9b439eb0f9
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Each of the next $$$t$$$ lines contains a non-empty string, consisting only of characters '(', ')', '[' and ']'. The total length of the strings over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
800
For each testcase print a single integer — the maximum number of moves you can perform on a given string $$$s$$$.
standard output
PASSED
4d8a4f767626aab66ca8b60dbfff952c
train_003.jsonl
1605796500
You are given a string $$$s$$$, consisting of brackets of two types: '(', ')', '[' and ']'.A string is called a regular bracket sequence (RBS) if it's of one of the following types: empty string; '(' + RBS + ')'; '[' + RBS + ']'; RBS + RBS. where plus is a concatenation of two strings.In one move you can choose a non-empty subsequence of the string $$$s$$$ (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.What is the maximum number of moves you can perform?
256 megabytes
import java.io.*; import java.util.*; final public class C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int tst = Integer.parseInt(br.readLine()); while(tst-->0){ char[] arr = br.readLine().toCharArray(); Stack<Character> stk = new Stack<>(); int ans = 0, len = arr.length; for(char c: arr){ if(c == '(' || c == ')'){ if(c == '(') stk.push('('); else if(!stk.isEmpty()){ ans++; stk.pop(); } } } stk.clear(); for(char c: arr){ if(c == '[' || c == ']'){ if(c == '[') stk.push('['); else if(!stk.isEmpty()){ ans++; stk.pop(); } } } sb.append(ans).append('\n'); } System.out.println(sb); } }
Java
["5\n()\n[]()\n([)]\n)]([\n)[(]"]
1 second
["1\n2\n2\n0\n1"]
NoteIn the first example you can just erase the whole string.In the second example you can first erase the brackets on positions $$$1$$$ and $$$2$$$: "[]()", then "()" is left. After that you can erase it whole. You could erase the whole string from the beginning but you would get one move instead of two.In the third example you can first erase the brackets on positions $$$1$$$ and $$$3$$$: "([)]". They form an RBS "()". Then "[]" is left, so you can erase it whole.In the fourth example there is no subsequence that is an RBS, so you can't perform a move at all.In the fifth example you can erase the brackets on positions $$$2$$$ and $$$4$$$: ")[(]" and get ")(" as a result. You can erase nothing from it.
Java 8
standard input
[ "greedy" ]
db9cec57d8ed5e914818ce9b439eb0f9
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Each of the next $$$t$$$ lines contains a non-empty string, consisting only of characters '(', ')', '[' and ']'. The total length of the strings over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
800
For each testcase print a single integer — the maximum number of moves you can perform on a given string $$$s$$$.
standard output
PASSED
5f12878da97536c7e7368d3d25ebb21a
train_003.jsonl
1605796500
You are given a string $$$s$$$, consisting of brackets of two types: '(', ')', '[' and ']'.A string is called a regular bracket sequence (RBS) if it's of one of the following types: empty string; '(' + RBS + ')'; '[' + RBS + ']'; RBS + RBS. where plus is a concatenation of two strings.In one move you can choose a non-empty subsequence of the string $$$s$$$ (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.What is the maximum number of moves you can perform?
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 n = sc.nextInt(); for (int i = 0; i < n; ++i) { String str = sc.next(); char[] cs = str.toCharArray(); int ans = 0; int a = 0, b = 0; for (char c : cs) { if (c == '(') a++; else if (c == '[') b++; else if (c == ')') { if (a > 0) { ans++; a--; } } else if (c == ']') { if (b > 0) { ans++; b--; } } } print(ans); } sc.close(); } private static <T> void print(T str) { System.out.println(str); } }
Java
["5\n()\n[]()\n([)]\n)]([\n)[(]"]
1 second
["1\n2\n2\n0\n1"]
NoteIn the first example you can just erase the whole string.In the second example you can first erase the brackets on positions $$$1$$$ and $$$2$$$: "[]()", then "()" is left. After that you can erase it whole. You could erase the whole string from the beginning but you would get one move instead of two.In the third example you can first erase the brackets on positions $$$1$$$ and $$$3$$$: "([)]". They form an RBS "()". Then "[]" is left, so you can erase it whole.In the fourth example there is no subsequence that is an RBS, so you can't perform a move at all.In the fifth example you can erase the brackets on positions $$$2$$$ and $$$4$$$: ")[(]" and get ")(" as a result. You can erase nothing from it.
Java 8
standard input
[ "greedy" ]
db9cec57d8ed5e914818ce9b439eb0f9
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Each of the next $$$t$$$ lines contains a non-empty string, consisting only of characters '(', ')', '[' and ']'. The total length of the strings over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
800
For each testcase print a single integer — the maximum number of moves you can perform on a given string $$$s$$$.
standard output
PASSED
76ba48d99883ff4f3258d05fc4f2d865
train_003.jsonl
1605796500
You are given a string $$$s$$$, consisting of brackets of two types: '(', ')', '[' and ']'.A string is called a regular bracket sequence (RBS) if it's of one of the following types: empty string; '(' + RBS + ')'; '[' + RBS + ']'; RBS + RBS. where plus is a concatenation of two strings.In one move you can choose a non-empty subsequence of the string $$$s$$$ (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.What is the maximum number of moves you can perform?
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner khar = new Scanner(System.in); int t = khar.nextInt(); for (int j = 0; j <t; j++) { String s = khar.next(); int par = 0; int crosh = 0; int max = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { par++; } if (s.charAt(i) == ')' && par != 0) { par--; max++; } if (s.charAt(i) == '[') { crosh++; } if (s.charAt(i) == ']' && crosh != 0) { crosh--; max++; } } System.out.println(max); } } }
Java
["5\n()\n[]()\n([)]\n)]([\n)[(]"]
1 second
["1\n2\n2\n0\n1"]
NoteIn the first example you can just erase the whole string.In the second example you can first erase the brackets on positions $$$1$$$ and $$$2$$$: "[]()", then "()" is left. After that you can erase it whole. You could erase the whole string from the beginning but you would get one move instead of two.In the third example you can first erase the brackets on positions $$$1$$$ and $$$3$$$: "([)]". They form an RBS "()". Then "[]" is left, so you can erase it whole.In the fourth example there is no subsequence that is an RBS, so you can't perform a move at all.In the fifth example you can erase the brackets on positions $$$2$$$ and $$$4$$$: ")[(]" and get ")(" as a result. You can erase nothing from it.
Java 8
standard input
[ "greedy" ]
db9cec57d8ed5e914818ce9b439eb0f9
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Each of the next $$$t$$$ lines contains a non-empty string, consisting only of characters '(', ')', '[' and ']'. The total length of the strings over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
800
For each testcase print a single integer — the maximum number of moves you can perform on a given string $$$s$$$.
standard output
PASSED
60072f89eb83bdafcae7f4d58f09cdf7
train_003.jsonl
1605796500
You are given a string $$$s$$$, consisting of brackets of two types: '(', ')', '[' and ']'.A string is called a regular bracket sequence (RBS) if it's of one of the following types: empty string; '(' + RBS + ')'; '[' + RBS + ']'; RBS + RBS. where plus is a concatenation of two strings.In one move you can choose a non-empty subsequence of the string $$$s$$$ (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.What is the maximum number of moves you can perform?
256 megabytes
import java.util.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t; t = in.nextInt(); while ((t--) > 0) { String s = in.next(); int openC = 0; int openS = 0; int ans = 0; for(int i = 0 ; i < s.length(); i++){ char ch = s.charAt(i); if(ch == '('){ openC++; } else if(ch=='['){ openS++; } else if(ch==')'){ if(openC > 0){ openC--; ans++; } } else if(ch==']'){ if(openS > 0){ openS--; ans++; } } } System.out.println(ans); } } }
Java
["5\n()\n[]()\n([)]\n)]([\n)[(]"]
1 second
["1\n2\n2\n0\n1"]
NoteIn the first example you can just erase the whole string.In the second example you can first erase the brackets on positions $$$1$$$ and $$$2$$$: "[]()", then "()" is left. After that you can erase it whole. You could erase the whole string from the beginning but you would get one move instead of two.In the third example you can first erase the brackets on positions $$$1$$$ and $$$3$$$: "([)]". They form an RBS "()". Then "[]" is left, so you can erase it whole.In the fourth example there is no subsequence that is an RBS, so you can't perform a move at all.In the fifth example you can erase the brackets on positions $$$2$$$ and $$$4$$$: ")[(]" and get ")(" as a result. You can erase nothing from it.
Java 8
standard input
[ "greedy" ]
db9cec57d8ed5e914818ce9b439eb0f9
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Each of the next $$$t$$$ lines contains a non-empty string, consisting only of characters '(', ')', '[' and ']'. The total length of the strings over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
800
For each testcase print a single integer — the maximum number of moves you can perform on a given string $$$s$$$.
standard output
PASSED
5c9ff2c1ced9fa5000c13ac0e17e4905
train_003.jsonl
1605796500
You are given a string $$$s$$$, consisting of brackets of two types: '(', ')', '[' and ']'.A string is called a regular bracket sequence (RBS) if it's of one of the following types: empty string; '(' + RBS + ')'; '[' + RBS + ']'; RBS + RBS. where plus is a concatenation of two strings.In one move you can choose a non-empty subsequence of the string $$$s$$$ (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.What is the maximum number of moves you can perform?
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class Solution { public static void main(String []args) throws IOException { BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(buf.readLine().trim()); while(t-->0) { String str = buf.readLine().trim(); System.out.println(findSol(str)); } } public static int findSol(String str) { HashMap<Character,Integer> map = new HashMap<>(); int count = 0; map.put('(',0); map.put('[',0); for(int i=0;i<str.length();i++) { char ch = str.charAt(i); if(ch == ')' && map.get('(') != 0) { count++; map.put('(',map.get('(')-1); } else if(ch == ']' && map.get('[') != 0) { count++; map.put('[',map.get('[')-1); } else if(ch == '(' || ch == '[') map.put(ch,map.get(ch)+1); } return count; } }
Java
["5\n()\n[]()\n([)]\n)]([\n)[(]"]
1 second
["1\n2\n2\n0\n1"]
NoteIn the first example you can just erase the whole string.In the second example you can first erase the brackets on positions $$$1$$$ and $$$2$$$: "[]()", then "()" is left. After that you can erase it whole. You could erase the whole string from the beginning but you would get one move instead of two.In the third example you can first erase the brackets on positions $$$1$$$ and $$$3$$$: "([)]". They form an RBS "()". Then "[]" is left, so you can erase it whole.In the fourth example there is no subsequence that is an RBS, so you can't perform a move at all.In the fifth example you can erase the brackets on positions $$$2$$$ and $$$4$$$: ")[(]" and get ")(" as a result. You can erase nothing from it.
Java 8
standard input
[ "greedy" ]
db9cec57d8ed5e914818ce9b439eb0f9
The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Each of the next $$$t$$$ lines contains a non-empty string, consisting only of characters '(', ')', '[' and ']'. The total length of the strings over all testcases doesn't exceed $$$2 \cdot 10^5$$$.
800
For each testcase print a single integer — the maximum number of moves you can perform on a given string $$$s$$$.
standard output
PASSED
5403e86d3e505a8a0d2d3f365aacd29c
train_003.jsonl
1527432600
Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly $$$k$$$ bookshelves. He decided that the beauty of the $$$k$$$ shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $$$k$$$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DBookshelves solver = new DBookshelves(); solver.solve(1, in, out); out.close(); } static class DBookshelves { public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int k = in.scanInt(); long ans = 0; long prefiox[] = new long[n + 1]; for (int i = 1; i <= n; i++) prefiox[i] += (prefiox[i - 1] + in.scanLong()); for (int ii = 63; ii >= 0; ii--) { boolean dp[][] = new boolean[k + 1][n + 1]; dp[0][0] = true; for (int i = 1; i <= k; i++) { for (int j = 0; j <= n; j++) { for (int l = 1; l <= n; l++) { if (l + j <= n) { dp[i][l + j] |= (dp[i - 1][j] && ((prefiox[j + l] - prefiox[j]) & (1l << ii)) != 0 && (((prefiox[j + l] - prefiox[j]) & ans) == ans)); } } } } if (dp[k][n]) ans ^= (1l << ii); } out.println(ans); } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { 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(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } public long scanLong() { long 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(); } } return neg * integer; } } }
Java
["10 4\n9 14 28 1 7 13 15 29 2 31", "7 3\n3 14 15 92 65 35 89"]
1 second
["24", "64"]
NoteIn the first example you can split the books as follows:$$$$$$(9 + 14 + 28 + 1 + 7) \&amp; (13 + 15) \&amp; (29 + 2) \&amp; (31) = 24.$$$$$$In the second example you can split the books as follows:$$$$$$(3 + 14 + 15 + 92) \&amp; (65) \&amp; (35 + 89) = 64.$$$$$$
Java 8
standard input
[ "dp", "bitmasks", "greedy" ]
9862db32dfd8eab8714d17aaaa338acd
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 50$$$) — the number of books and the number of shelves in the new office. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$, ($$$0 &lt; a_i &lt; 2^{50}$$$) — the prices of the books in the order they stand on the old shelf.
1,900
Print the maximum possible beauty of $$$k$$$ shelves in the new office.
standard output
PASSED
de735d60e03d3a0e59478f45b20fc6d3
train_003.jsonl
1527432600
Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly $$$k$$$ bookshelves. He decided that the beauty of the $$$k$$$ shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $$$k$$$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
256 megabytes
import java.awt.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.List; import java.util.Queue; import static java.lang.Math.max; import static java.lang.Math.min; public class D implements Runnable{ // SOLUTION AT THE TOP OF CODE!!! // HACK ME PLEASE IF YOU CAN!!! // PLEASE!!! // PLEASE!!! // PLEASE!!! private final static boolean FIRST_INPUT_STRING = false; private final static boolean MULTIPLE_TESTS = true; private final boolean ONLINE_JUDGE = !new File("input.txt").exists(); // private final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private final static int MAX_STACK_SIZE = 128; private final static boolean OPTIMIZE_READ_NUMBERS = false; ///////////////////////////////////////////////////////////////////// private final static Random rnd = new Random(); private final static String fileName = ""; private final static long MODULO = 1000 * 1000 * 1000 + 7; // THERE SOLUTION STARTS!!! private void solve() { int n = readInt(); int k = readInt(); long[] a = readLongArray(n); long[][] sums = new long[n][n]; for (int start = 0; start < n; ++start) { long sum = 0; for (int end = start; end < n; ++end) { sum += a[end]; sums[start][end] = sum; } } long prefix = 0; for (int bit = 60; bit >= 0; --bit) { long nextPrefix = prefix | (1L << bit); boolean[][] dp = new boolean[n + 1][k + 1]; dp[0][0] = true; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= k; ++j) { for (int last = 0; last < i; ++last) { long sum = sums[last][i - 1]; boolean can = (sum & nextPrefix) == nextPrefix; dp[i][j] |= (dp[last][j - 1] && can); } } } if (dp[n][k]) { prefix = nextPrefix; } } out.println(prefix); } ///////////////////////////////////////////////////////////////////// private static long add(long a, long b) { return (a + b) % MODULO; } private static long subtract(long a, long b) { return add(a, MODULO - b % MODULO); } private static long mult(long a, long b) { return (a * b) % MODULO; } ///////////////////////////////////////////////////////////////////// public void run(){ try{ timeInit(); Locale.setDefault(Locale.US); init(); if (ONLINE_JUDGE) { solve(); } else { do { try { timeInit(); solve(); time(); out.println(); out.flush(); } catch (NumberFormatException e) { break; } catch (NullPointerException e) { if (FIRST_INPUT_STRING) break; else throw e; } } while (MULTIPLE_TESTS); } out.close(); time(); }catch (Exception e){ e.printStackTrace(System.err); System.exit(-1); } } ///////////////////////////////////////////////////////////////////// private BufferedReader in; private OutputWriter out; private StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args){ new Thread(null, new D(), "", MAX_STACK_SIZE * (1L << 20)).start(); } ///////////////////////////////////////////////////////////////////// private void init() throws FileNotFoundException{ Locale.setDefault(Locale.US); if (ONLINE_JUDGE){ if (fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new OutputWriter(System.out); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new OutputWriter(fileName + ".out"); } }else{ in = new BufferedReader(new FileReader("input.txt")); out = new OutputWriter("output.txt"); } } //////////////////////////////////////////////////////////////// private long timeBegin; private void timeInit() { this.timeBegin = System.currentTimeMillis(); } private void time(){ long timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } private void debug(Object... objects){ if (ONLINE_JUDGE){ for (Object o: objects){ System.err.println(o.toString()); } } } ///////////////////////////////////////////////////////////////////// private String delim = " "; private String readLine() { try { return in.readLine(); } catch (IOException e) { throw new RuntimeIOException(e); } } private String readString() { try { while(!tok.hasMoreTokens()){ tok = new StringTokenizer(readLine(), delim); } return tok.nextToken(delim); } catch (NullPointerException e) { return null; } } ///////////////////////////////////////////////////////////////// private final char NOT_A_SYMBOL = '\0'; private char readChar() { try { int intValue = in.read(); if (intValue == -1){ return NOT_A_SYMBOL; } return (char) intValue; } catch (IOException e) { throw new RuntimeIOException(e); } } private char[] readCharArray() { return readLine().toCharArray(); } private char[][] readCharField(int rowsCount) { char[][] field = new char[rowsCount][]; for (int row = 0; row < rowsCount; ++row) { field[row] = readCharArray(); } return field; } ///////////////////////////////////////////////////////////////// private long optimizedReadLong() { int sign = 1; long result = 0; boolean started = false; while (true) { try { int j = in.read(); if (-1 == j) { if (started) return sign * result; throw new NumberFormatException(); } if (j == '-') { if (started) throw new NumberFormatException(); sign = -sign; } if ('0' <= j && j <= '9') { result = result * 10 + j - '0'; started = true; } else if (started) { return sign * result; } } catch (IOException e) { throw new RuntimeIOException(e); } } } private int readInt() { if (!OPTIMIZE_READ_NUMBERS) { return Integer.parseInt(readString()); } else { return (int) optimizedReadLong(); } } private int[] readIntArray(int size) { int[] array = new int[size]; for (int index = 0; index < size; ++index){ array[index] = readInt(); } return array; } private int[] readSortedIntArray(int size) { Integer[] array = new Integer[size]; for (int index = 0; index < size; ++index) { array[index] = readInt(); } Arrays.sort(array); int[] sortedArray = new int[size]; for (int index = 0; index < size; ++index) { sortedArray[index] = array[index]; } return sortedArray; } private int[] readIntArrayWithDecrease(int size) { int[] array = readIntArray(size); for (int i = 0; i < size; ++i) { array[i]--; } return array; } /////////////////////////////////////////////////////////////////// private int[][] readIntMatrix(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArray(columnsCount); } return matrix; } private int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) { int[][] matrix = new int[rowsCount][]; for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) { matrix[rowIndex] = readIntArrayWithDecrease(columnsCount); } return matrix; } /////////////////////////////////////////////////////////////////// private long readLong() { if (!OPTIMIZE_READ_NUMBERS) { return Long.parseLong(readString()); } else { return optimizedReadLong(); } } private long[] readLongArray(int size) { long[] array = new long[size]; for (int index = 0; index < size; ++index){ array[index] = readLong(); } return array; } //////////////////////////////////////////////////////////////////// private double readDouble() { return Double.parseDouble(readString()); } private double[] readDoubleArray(int size) { double[] array = new double[size]; for (int index = 0; index < size; ++index){ array[index] = readDouble(); } return array; } //////////////////////////////////////////////////////////////////// private BigInteger readBigInteger() { return new BigInteger(readString()); } private BigDecimal readBigDecimal() { return new BigDecimal(readString()); } ///////////////////////////////////////////////////////////////////// private Point readPoint() { int x = readInt(); int y = readInt(); return new Point(x, y); } private Point[] readPointArray(int size) { Point[] array = new Point[size]; for (int index = 0; index < size; ++index){ array[index] = readPoint(); } return array; } ///////////////////////////////////////////////////////////////////// @Deprecated private List<Integer>[] readGraph(int vertexNumber, int edgeNumber) { @SuppressWarnings("unchecked") List<Integer>[] graph = new List[vertexNumber]; for (int index = 0; index < vertexNumber; ++index){ graph[index] = new ArrayList<Integer>(); } while (edgeNumber-- > 0){ int from = readInt() - 1; int to = readInt() - 1; graph[from].add(to); graph[to].add(from); } return graph; } private static class GraphBuilder { final int size; final List<Integer>[] edges; static GraphBuilder createInstance(int size) { List<Integer>[] edges = new List[size]; for (int v = 0; v < size; ++v) { edges[v] = new ArrayList<Integer>(); } return new GraphBuilder(edges); } private GraphBuilder(List<Integer>[] edges) { this.size = edges.length; this.edges = edges; } public void addEdge(int from, int to) { addDirectedEdge(from, to); addDirectedEdge(to, from); } public void addDirectedEdge(int from, int to) { edges[from].add(to); } public int[][] build() { int[][] graph = new int[size][]; for (int v = 0; v < size; ++v) { List<Integer> vEdges = edges[v]; graph[v] = castInt(vEdges); } return graph; } } private final static int ZERO_INDEXATION = 0, ONE_INDEXATION = 1; private int[][] readUnweightedGraph(int vertexNumber, int edgesNumber) { return readUnweightedGraph(vertexNumber, edgesNumber, ONE_INDEXATION, false); } private int[][] readUnweightedGraph(int vertexNumber, int edgesNumber, int indexation, boolean directed ) { GraphBuilder graphBuilder = GraphBuilder.createInstance(vertexNumber); for (int i = 0; i < edgesNumber; ++i) { int from = readInt() - indexation; int to = readInt() - indexation; if (directed) graphBuilder.addDirectedEdge(from, to); else graphBuilder.addEdge(from, to); } return graphBuilder.build(); } private static class Edge { int to; int w; Edge(int to, int w) { this.to = to; this.w = w; } } private Edge[][] readWeightedGraph(int vertexNumber, int edgesNumber) { return readWeightedGraph(vertexNumber, edgesNumber, ONE_INDEXATION, false); } private Edge[][] readWeightedGraph(int vertexNumber, int edgesNumber, int indexation, boolean directed) { @SuppressWarnings("unchecked") List<Edge>[] graph = new List[vertexNumber]; for (int v = 0; v < vertexNumber; ++v) { graph[v] = new ArrayList<Edge>(); } while (edgesNumber --> 0) { int from = readInt() - indexation; int to = readInt() - indexation; int w = readInt(); graph[from].add(new Edge(to, w)); if (!directed) graph[to].add(new Edge(from, w)); } Edge[][] graphArrays = new Edge[vertexNumber][]; for (int v = 0; v < vertexNumber; ++v) { graphArrays[v] = graph[v].toArray(new Edge[0]); } return graphArrays; } ///////////////////////////////////////////////////////////////////// private static class IntIndexPair { static Comparator<IntIndexPair> increaseComparator = new Comparator<D.IntIndexPair>() { @Override public int compare(D.IntIndexPair indexPair1, D.IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return value1 - value2; int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; static Comparator<IntIndexPair> decreaseComparator = new Comparator<D.IntIndexPair>() { @Override public int compare(D.IntIndexPair indexPair1, D.IntIndexPair indexPair2) { int value1 = indexPair1.value; int value2 = indexPair2.value; if (value1 != value2) return -(value1 - value2); int index1 = indexPair1.index; int index2 = indexPair2.index; return index1 - index2; } }; static IntIndexPair[] from(int[] array) { IntIndexPair[] iip = new IntIndexPair[array.length]; for (int i = 0; i < array.length; ++i) { iip[i] = new IntIndexPair(array[i], i); } return iip; } int value, index; IntIndexPair(int value, int index) { super(); this.value = value; this.index = index; } int getRealIndex() { return index + 1; } } private IntIndexPair[] readIntIndexArray(int size) { IntIndexPair[] array = new IntIndexPair[size]; for (int index = 0; index < size; ++index) { array[index] = new IntIndexPair(readInt(), index); } return array; } ///////////////////////////////////////////////////////////////////// private static class OutputWriter extends PrintWriter { final int DEFAULT_PRECISION = 12; private int precision; private String format, formatWithSpace; { precision = DEFAULT_PRECISION; format = createFormat(precision); formatWithSpace = format + " "; } OutputWriter(OutputStream out) { super(out); } OutputWriter(String fileName) throws FileNotFoundException { super(fileName); } int getPrecision() { return precision; } void setPrecision(int precision) { precision = max(0, precision); this.precision = precision; format = createFormat(precision); formatWithSpace = format + " "; } String createFormat(int precision){ return "%." + precision + "f"; } @Override public void print(double d){ printf(format, d); } @Override public void println(double d){ print(d); println(); } void printWithSpace(double d){ printf(formatWithSpace, d); } void printAll(double...d){ for (int i = 0; i < d.length - 1; ++i){ printWithSpace(d[i]); } print(d[d.length - 1]); } void printlnAll(double... d){ printAll(d); println(); } void printAll(int... array) { for (int value : array) { print(value + " "); } } void printlnAll(int... array) { printAll(array); println(); } void printAll(long... array) { for (long value : array) { print(value + " "); } } void printlnAll(long... array) { printAll(array); println(); } } ///////////////////////////////////////////////////////////////////// private static class RuntimeIOException extends RuntimeException { /** * */ private static final long serialVersionUID = -6463830523020118289L; RuntimeIOException(Throwable cause) { super(cause); } } ///////////////////////////////////////////////////////////////////// //////////////// Some useful constants andTo functions //////////////// ///////////////////////////////////////////////////////////////////// private static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; private static final int[][] steps8 = { {-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, 1}, {1, -1}, {-1, 1} }; private static boolean checkCell(int row, int rowsCount, int column, int columnsCount) { return checkIndex(row, rowsCount) && checkIndex(column, columnsCount); } private static boolean checkIndex(int index, int lim){ return (0 <= index && index < lim); } ///////////////////////////////////////////////////////////////////// private static int getBit(long mask, int bit) { return (int)((mask >> bit) & 1); } private static boolean checkBit(long mask, int bit){ return getBit(mask, bit) != 0; } ///////////////////////////////////////////////////////////////////// private static long getSum(int[] array) { long sum = 0; for (int value: array) { sum += value; } return sum; } private static Point getMinMax(int[] array) { int min = array[0]; int max = array[0]; for (int index = 0, size = array.length; index < size; ++index, ++index) { int value = array[index]; if (index == size - 1) { min = min(min, value); max = max(max, value); } else { int otherValue = array[index + 1]; if (value <= otherValue) { min = min(min, value); max = max(max, otherValue); } else { min = min(min, otherValue); max = max(max, value); } } } return new Point(min, max); } ///////////////////////////////////////////////////////////////////// private static boolean isPrime(int x) { if (x < 2) return false; for (int d = 2; d * d <= x; ++d) { if (x % d == 0) return false; } return true; } private static int[] getPrimes(int n) { boolean[] used = new boolean[n]; used[0] = used[1] = true; int size = 0; for (int i = 2; i < n; ++i) { if (!used[i]) { ++size; for (int j = 2 * i; j < n; j += i) { used[j] = true; } } } int[] primes = new int[size]; for (int i = 0, cur = 0; i < n; ++i) { if (!used[i]) { primes[cur++] = i; } } return primes; } ///////////////////////////////////////////////////////////////////// int[] getDivisors(int value) { List<Integer> divisors = new ArrayList<Integer>(); for (int divisor = 1; divisor * divisor <= value; ++divisor) { if (value % divisor == 0) { divisors.add(divisor); if (divisor * divisor != value) { divisors.add(value / divisor); } } } return castInt(divisors); } ///////////////////////////////////////////////////////////////////// private static long lcm(long a, long b) { return a / gcd(a, b) * b; } private static long gcd(long a, long b) { return (a == 0 ? b : gcd(b % a, a)); } ///////////////////////////////////////////////////////////////////// private interface MultiSet<ValueType> { int size(); void inc(ValueType value); boolean dec(ValueType value); int count(ValueType value); } private static abstract class MultiSetImpl <ValueType, MapType extends Map<ValueType, Integer>> implements MultiSet<ValueType> { protected final MapType map; protected int size; protected MultiSetImpl(MapType map) { this.map = map; this.size = 0; } public int size() { return size; } public void inc(ValueType value) { int count = count(value); map.put(value, count + 1); ++size; } public boolean dec(ValueType value) { int count = count(value); if (count == 0) return false; if (count == 1) map.remove(value); else map.put(value, count - 1); --size; return true; } public int count(ValueType value) { Integer count = map.get(value); return (count == null ? 0 : count); } } private static class HashMultiSet<ValueType> extends MultiSetImpl<ValueType, Map<ValueType, Integer>> { public static <ValueType> MultiSet<ValueType> createMultiSet() { Map<ValueType, Integer> map = new HashMap<ValueType, Integer>(); return new HashMultiSet<ValueType>(map); } HashMultiSet(Map<ValueType, Integer> map) { super(map); } } ///////////////////////////////////////////////////////////////////// private interface SortedMultiSet<ValueType> extends MultiSet<ValueType> { ValueType min(); ValueType max(); ValueType pollMin(); ValueType pollMax(); ValueType lower(ValueType value); ValueType floor(ValueType value); ValueType ceiling(ValueType value); ValueType higher(ValueType value); } private static abstract class SortedMultiSetImpl<ValueType> extends MultiSetImpl<ValueType, NavigableMap<ValueType, Integer>> implements SortedMultiSet<ValueType> { SortedMultiSetImpl(NavigableMap<ValueType, Integer> map) { super(map); } @Override public ValueType min() { return (size == 0 ? null : map.firstKey()); } @Override public ValueType max() { return (size == 0 ? null : map.lastKey()); } @Override public ValueType pollMin() { ValueType first = min(); if (first != null) dec(first); return first; } @Override public ValueType pollMax() { ValueType last = max(); dec(last); return last; } @Override public ValueType lower(ValueType value) { return map.lowerKey(value); } @Override public ValueType floor(ValueType value) { return map.floorKey(value); } @Override public ValueType ceiling(ValueType value) { return map.ceilingKey(value); } @Override public ValueType higher(ValueType value) { return map.higherKey(value); } } private static class TreeMultiSet<ValueType> extends SortedMultiSetImpl<ValueType> { public static <ValueType> SortedMultiSet<ValueType> createMultiSet() { NavigableMap<ValueType, Integer> map = new TreeMap<ValueType, Integer>(); return new TreeMultiSet<ValueType>(map); } public static <ValueType> SortedMultiSet<ValueType> createMultiSet(Comparator<ValueType> comparator) { NavigableMap<ValueType, Integer> map = new TreeMap<ValueType, Integer>(comparator); return new TreeMultiSet<ValueType>(map); } TreeMultiSet(NavigableMap<ValueType, Integer> map) { super(map); } } ///////////////////////////////////////////////////////////////////// private static class IdMap<KeyType> extends HashMap<KeyType, Integer> { /** * */ private static final long serialVersionUID = -3793737771950984481L; public IdMap() { super(); } int register(KeyType key) { Integer id = super.get(key); if (id == null) { super.put(key, id = size()); } return id; } int getId(KeyType key) { return get(key); } } ///////////////////////////////////////////////////////////////////// private static class SortedIdMapper<ValueType extends Comparable<ValueType>> { private List<ValueType> values; public SortedIdMapper() { this.values = new ArrayList<ValueType>(); } void addValue(ValueType value) { values.add(value); } IdMap<ValueType> build() { Collections.sort(values); IdMap<ValueType> ids = new IdMap<ValueType>(); List<ValueType> uniqueValues = new ArrayList<ValueType>(); for (int index = 0; index < values.size(); ++index) { ValueType value = values.get(index); if (index == 0 || values.get(index - 1).compareTo(value) != 0) { ids.register(value); uniqueValues.add(value); } } values = uniqueValues; return ids; } } ///////////////////////////////////////////////////////////////////// private static int[] castInt(List<Integer> list) { int[] array = new int[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.get(i); } return array; } private static long[] castLong(List<Long> list) { long[] array = new long[list.size()]; for (int i = 0; i < array.length; ++i) { array[i] = list.get(i); } return array; } ///////////////////////////////////////////////////////////////////// /** * Generates list with keys 0..<n * @param n - exclusive limit of sequence */ private static List<Integer> order(int n) { List<Integer> sequence = new ArrayList<Integer>(); for (int i = 0; i < n; ++i) { sequence.add(i); } return sequence; } ///////////////////////////////////////////////////////////////////// interface Rmq { int getMin(int left, int right); int getMinIndex(int left, int right); } private static class SparseTable implements Rmq { private static final int MAX_BIT = 20; int n; int[] array; SparseTable(int[] array) { this.n = array.length; this.array = array; } int[] lengthMaxBits; int[][] table; int getIndexOfLess(int leftIndex, int rightIndex) { return (array[leftIndex] <= array[rightIndex]) ? leftIndex : rightIndex; } SparseTable build() { this.lengthMaxBits = new int[n + 1]; lengthMaxBits[0] = 0; for (int i = 1; i <= n; ++i) { lengthMaxBits[i] = lengthMaxBits[i - 1]; int length = (1 << lengthMaxBits[i]); if (length + length <= i) ++lengthMaxBits[i]; } this.table = new int[MAX_BIT][n]; table[0] = castInt(order(n)); for (int bit = 0; bit < MAX_BIT - 1; ++bit) { for (int i = 0, j = (1 << bit); j < n; ++i, ++j) { table[bit + 1][i] = getIndexOfLess( table[bit][i], table[bit][j] ); } } return this; } @Override public int getMinIndex(int left, int right) { int length = (right - left + 1); int bit = lengthMaxBits[length]; int segmentLength = (1 << bit); return getIndexOfLess( table[bit][left], table[bit][right - segmentLength + 1] ); } @Override public int getMin(int left, int right) { return array[getMinIndex(left, right)]; } } private static Rmq createRmq(int[] array) { return new SparseTable(array).build(); } ///////////////////////////////////////////////////////////////////// interface Lca { Lca build(int root); int lca(int a, int b); int height(int v); } private static class LcaRmq implements Lca { int n; int[][] graph; LcaRmq(int[][] graph) { this.n = graph.length; this.graph = graph; } int time; int[] order; int[] heights; int[] first; Rmq rmq; @Override public LcaRmq build(int root) { this.order = new int[n + n]; this.heights = new int[n]; this.first = new int[n]; Arrays.fill(first, -1); this.time = 0; dfs(root, 0); int[] orderedHeights = new int[n + n]; for (int i = 0; i < order.length; ++i) { orderedHeights[i] = heights[order[i]]; } this.rmq = createRmq(orderedHeights); return this; } void dfs(int from, int height) { first[from] = time; order[time] = from; heights[from] = height; ++time; for (int to : graph[from]) { if (first[to] == -1) { dfs(to, height + 1); order[time] = from; ++time; } } } @Override public int lca(int a, int b) { int aFirst = first[a], bFirst = first[b]; int left = min(aFirst, bFirst), right = max(aFirst, bFirst); int orderIndex = rmq.getMinIndex(left, right); return order[orderIndex]; } @Override public int height(int v) { return heights[v]; } } private static class LcaBinary implements Lca { private static final int MAX_BIT = 20; int n; int[][] graph; int[] h; int[][] parents; LcaBinary(int[][] graph) { this.n = graph.length; this.graph = graph; } @Override public Lca build(int root) { this.h = new int[n]; this.parents = new int[MAX_BIT][n]; Arrays.fill(parents[0], -1); Queue<Integer> queue = new ArrayDeque<Integer>(); queue.add(root); add(root, root); while (queue.size() > 0) { int from = queue.poll(); for (int to : graph[from]) { if (parents[0][to] == -1) { add(from, to); queue.add(to); } } } return this; } void add(int parent, int v) { h[v] = h[parent] + 1; parents[0][v] = parent; for (int bit = 0; bit < MAX_BIT - 1; ++bit) { parents[bit + 1][v] = parents[bit][parents[bit][v]]; } } @Override public int lca(int a, int b) { if (h[a] < h[b]) { int tmp = a; a = b; b = tmp; } int delta = h[a] - h[b]; for (int bit = MAX_BIT - 1; bit >= 0; --bit) { if (delta >= (1 << bit)) { delta -= (1 << bit); a = parents[bit][a]; } } if (a == b) return a; for (int bit = MAX_BIT - 1; bit >= 0; --bit) { int nextA = parents[bit][a], nextB = parents[bit][b]; if (nextA != nextB) { a = nextA; b = nextB; } } return parents[0][a]; } @Override public int height(int v) { return h[v]; } } private static Lca createLca(int[][] graph, int root) { return new LcaRmq(graph).build(root); } ///////////////////////////////////////////////////////////////////// private static class BiconnectedGraph { int n; int[][] graph; BiconnectedGraph(int[][] graph) { this.n = graph.length; this.graph = graph; } int time; int[] tin, up; boolean[] used; BiconnectedGraph build() { calculateTimes(); condensateComponents(); return this; } void calculateTimes() { this.tin = new int[n]; this.up = new int[n]; this.time = 0; this.used = new boolean[n]; timeDfs(0, -1); } void timeDfs(int from, int parent) { used[from] = true; up[from] = tin[from] = time; ++time; for (int to : graph[from]) { if (to == parent) continue; if (used[to]) { up[from] = min(up[from], tin[to]); } else { timeDfs(to, from); up[from] = min(up[from], up[to]); } } } int[] components; int[][] componentsGraph; int component(int v) { return components[v]; } int[][] toGraph() { return componentsGraph; } void condensateComponents() { this.components = new int[n]; Arrays.fill(components, -1); for (int v = 0; v < n; ++v) { if (components[v] == -1) { componentsDfs(v, v); } } GraphBuilder graphBuilder = GraphBuilder.createInstance(n); Set<Point> edges = new HashSet<Point>(); for (int from = 0; from < n; ++from) { int fromComponent = components[from]; for (int to : graph[from]) { int toComponent = components[to]; if (fromComponent == toComponent) continue; Point edge = new Point(fromComponent, toComponent); if (edges.add(edge)) graphBuilder.addDirectedEdge(fromComponent, toComponent); } } this.componentsGraph = graphBuilder.build(); } void componentsDfs(int from, int color) { components[from] = color; for (int to : graph[from]) { if (components[to] != -1) continue; if (tin[from] >= up[to] && tin[to] >= up[from]) { componentsDfs(to, color); } } } } ///////////////////////////////////////////////////////////////////// private static class VertexBiconnectedGraph { static class Edge { int to; int index; Edge(int to, int index) { this.to = to; this.index = index; } } int n, m; List<Edge>[] graph; List<Edge> edges; VertexBiconnectedGraph(int n) { this.n = n; this.m = 0; this.graph = new List[n]; for (int v = 0; v < n; ++v) { graph[v] = new ArrayList<Edge>(); } this.edges = new ArrayList<Edge>(); } void addEdge(int from, int to) { Edge fromToEdge = new Edge(to, m); Edge toFromEdge = new Edge(from, m + 1); edges.add(fromToEdge); edges.add(toFromEdge); graph[from].add(fromToEdge); graph[to].add(toFromEdge); m += 2; } int time; boolean[] used; int[] tin, up; int[] parents; boolean[] isArticulation; boolean[] findArticulationPoints() { this.isArticulation = new boolean[n]; this.used = new boolean[n]; this.parents = new int[n]; Arrays.fill(parents, -1); this.tin = new int[n]; this.up = new int[n]; this.time = 0; for (int v = 0; v < n; ++v) { if (!used[v]) { articulationDfs(v, -1); } } return isArticulation; } void articulationDfs(int from, int parent) { used[from] = true; parents[from] = parent; ++time; up[from] = tin[from] = time; int childrenCount = 0; for (Edge e : graph[from]) { int to = e.to; if (to == parent) continue; if (used[to]) { up[from] = min(up[from], tin[to]); } else { ++childrenCount; articulationDfs(to, from); up[from] = min(up[from], up[to]); if (up[to] >= tin[from] && parent != -1) { isArticulation[from] = true; } } } if (parent == -1 && childrenCount > 1) { isArticulation[from] = true; } } int[] edgeColors; int maxEdgeColor; int[] paintEdges() { this.edgeColors = new int[m]; Arrays.fill(edgeColors, -1); this.maxEdgeColor = -1; this.used = new boolean[n]; for (int v = 0; v < n; ++v) { if (!used[v]) { ++maxEdgeColor; paintDfs(v, maxEdgeColor, -1); } } return edgeColors; } void paintEdge(int edgeIndex, int color) { if (edgeColors[edgeIndex] != -1) return; edgeColors[edgeIndex] = edgeColors[edgeIndex ^ 1] = color; } void paintDfs(int from, int color, int parent) { used[from] = true; for (Edge e : graph[from]) { int to = e.to; if (to == parent) continue; if (!used[to]) { if (up[to] >= tin[from]) { int newColor = ++maxEdgeColor; paintEdge(e.index, newColor); paintDfs(to, newColor, from); } else { paintEdge(e.index, color); paintDfs(to, color, from); } } else if (up[to] <= tin[from]){ paintEdge(e.index, color); } } } Set<Integer>[] collectVertexEdgeColors() { Set<Integer>[] vertexEdgeColors = new Set[n]; for (int v = 0; v < n; ++v) { vertexEdgeColors[v] = new HashSet<Integer>(); for (Edge e : graph[v]) { vertexEdgeColors[v].add(edgeColors[e.index]); } } return vertexEdgeColors; } VertexBiconnectedGraph build() { findArticulationPoints(); paintEdges(); createComponentsGraph(); return this; } int[][] componentsGraph; void createComponentsGraph() { Set<Integer>[] vertexEdgeColors = collectVertexEdgeColors(); int edgeColorShift = vertexEdgeColors.length; int size = vertexEdgeColors.length + maxEdgeColor + 1; GraphBuilder graphBuilder = GraphBuilder.createInstance(size); for (int v = 0; v < vertexEdgeColors.length; ++v) { for (int edgeColor : vertexEdgeColors[v]) { graphBuilder.addEdge(v, edgeColor + edgeColorShift); } } this.componentsGraph = graphBuilder.build(); } int[][] toGraph() { return componentsGraph; } } ///////////////////////////////////////////////////////////////////// private static class DSU { int[] sizes; int[] ranks; int[] parents; static DSU createInstance(int size) { int[] sizes = new int[size]; Arrays.fill(sizes, 1); return new DSU(sizes); } DSU(int[] sizes) { this.sizes = sizes; int size = sizes.length; this.ranks = new int[size]; Arrays.fill(ranks, 1); this.parents = castInt(order(size)); } int get(int v) { if (v == parents[v]) return v; return parents[v] = get(parents[v]); } boolean union(int a, int b) { a = get(a); b = get(b); if (a == b) return false; if (ranks[a] < ranks[b]) { int tmp = a; a = b; b = tmp; } parents[b] = a; sizes[a] += sizes[b]; if (ranks[a] == ranks[b]) ++ranks[a]; return true; } } ///////////////////////////////////////////////////////////////////// static abstract class SegmentTree { int size; boolean lazySupported; boolean[] lazy; long[] values; long[] tree; SegmentTree(int n, boolean lazySupported) { this.size = n; this.lazySupported = lazySupported; int treeSize = size << 2; this.tree = new long[treeSize]; if (lazySupported) { this.lazy = new boolean[treeSize]; this.values = new long[treeSize]; } } SegmentTree(int[] a, boolean lazySupported) { this(a.length, lazySupported); } abstract void updateValue(int v, int left, int right, long value); void setLazyValue(int v, long value) { throw new UnsupportedOperationException(); } void pushVertex(int v, int vLeft, int vRight) { if (lazy[v]) { setLazyValue(vLeft, values[v]); setLazyValue(vRight, values[v]); lazy[v] = false; values[v] = 0; } } abstract void updateVertex(int v, int vLeft, int vRight); int[] a; void buildTree(int[] a) { this.a = a; buildTree(1, 0, size - 1); } void buildTree(int v, int left, int right) { if (left == right) { updateValue(v, left, right, a[left]); } else { int mid = (left + right) >> 1; int vLeft = (v << 1), vRight = (vLeft + 1); buildTree(vLeft, left, mid); buildTree(vRight, mid + 1, right); updateVertex(v, vLeft, vRight); } } long value; int index; void updateIndex(int index, long value) { this.index = index; this.value = value; updateTreeIndex(1, 0, size - 1); } void updateTreeIndex(int v, int left, int right) { if (left == right) { updateValue(v, left, right, value); } else { int mid = (left + right) >> 1; int vLeft = (v << 1), vRight = (vLeft + 1); if (index <= mid) updateTreeIndex(vLeft, left, mid); else updateTreeIndex(vRight, mid + 1, right); updateVertex(v, vLeft, vRight); } } int start, end; void updateSegment(int start, int end, long value) { this.start = start; this.end = end; this.value = value; updateTreeSegment(1, 0, size - 1); } void updateTreeSegment(int v, int left, int right) { if (start <= left && right <= end) { if (lazySupported) { setLazyValue(v, value); } else { updateValue(v, left, right, value); } } else { int mid = (left + right) >> 1; int vLeft = (v << 1), vRight = (vLeft + 1); if (lazySupported) pushVertex(v, vLeft, vRight); if (start <= mid) updateTreeSegment(vLeft, left, mid); if (mid < end) updateTreeSegment(vRight, mid + 1, right); updateVertex(v, vLeft, vRight); } } abstract void initResult(long... initResultValues); abstract void accumulateResult(int v, int left, int right); void accumulateIndexResult(int v, int left, int right) { accumulateResult(v, left, right); } void getIndex(int index, long... initResultValues) { this.index = index; initResult(initResultValues); getTreeIndex(1, 0, size - 1); } void getTreeIndex(int v, int left, int right) { if (lazySupported) { if (left == right) { accumulateIndexResult(v, left, right); } else { int mid = (left + right) >> 1; int vLeft = (v << 1), vRight = (vLeft + 1); pushVertex(v, vLeft, vRight); if (index <= mid) getTreeIndex(vLeft, left, mid); else getTreeIndex(vRight, mid + 1, right); updateVertex(v, vLeft, vRight); } } else { while (left <= right) { accumulateIndexResult(v, left, right); if (left == right) break; int mid = (left + right) >> 1; int vLeft = (v << 1), vRight = (vLeft + 1); if (index <= mid) { v = vLeft; right = mid; } else { v = vRight; left = mid + 1; } } } } void getSegment(int start, int end, long... initResultValues) { this.start = start; this.end = end; initResult(initResultValues); getTreeSegment(1, 0, size - 1); } void getTreeSegment(int v, int left, int right) { if (start <= left && right <= end) { accumulateResult(v, left, right); } else { int mid = (left + right) >> 1; int vLeft = (v << 1), vRight = (vLeft + 1); if (lazySupported) pushVertex(v, vLeft, vRight); if (start <= mid) getTreeSegment(vLeft, left, mid); if (mid < end) getTreeSegment(vRight, mid + 1, right); if (lazySupported) updateVertex(v, vLeft, vRight); } } int[] toArray() { this.a = new int[size]; fillTreeArray(1, 0, size - 1); return a; } void fillTreeArray(int v, int left, int right) { if (left == right) { a[left] = (int)(tree[v]); } else { int mid = (left + right) >> 1; int vLeft = (v << 1), vRight = (vLeft + 1); if (lazySupported) pushVertex(v, vLeft, vRight); fillTreeArray(vLeft, left, mid); fillTreeArray(vRight, mid + 1, right); if (lazySupported) updateVertex(v, vLeft, vRight); } } } ///////////////////////////////////////////////////////////////////// static class Treap { static class Node { static int getCount(Node node) { return (node == null ? 0 : node.count); } static long getValue(Node node) { return (node == null ? 0 : node.value); } static long getSum(Node node) { return (node == null ? 0 : node.sum); } long priority; Node left, right; int count; long value, sum; boolean reversed; Node(long value) { this.priority = rnd.nextLong(); this.count = 1; this.value = value; this.sum = value; this.reversed = false; } void update() { this.count = getCount(left) + getCount(right) + 1; this.sum = getSum(left) + getSum(right) + value; } void push() { if (reversed) { Node tmp = left; left = right; right = tmp; if (left != null) left.reversed ^= true; if (right != null) right.reversed ^= true; reversed = false; } } } Node root; Node[] splitParts; Treap() { this.root = null; this.splitParts = new Node[2]; } void addValue(long value) { Node node = new Node(value); root = merge(root, node); } long getSegmentSum(int startInclusive, int endExclusive) { splitClear(); split(root, endExclusive); Node leftMid = splitParts[0]; Node right = splitParts[1]; splitClear(); split(leftMid, startInclusive); Node left = splitParts[0]; Node mid = splitParts[1]; long result = Node.getSum(mid); root = merge(left, mid); root = merge(root, right); return result; } void updateValue(Node node, int index, long delta) { if (node == null) return; node.push(); int leftCount = Node.getCount(node.left); if (index < leftCount) updateValue(node.left, index, delta); else if (index == leftCount) node.value += delta; else updateValue(node.right, index - leftCount - 1, delta); node.update(); } long getValueByIndex(Node node, int index) { Node result = getNodeByKey(node, index); return Node.getValue(result); } Node getNodeByKey(Node node, int key) { if (node == null) return null; node.push(); int leftCount = Node.getCount(node.left); Node result; if (key < leftCount) result = getNodeByKey(node.left, key); else if (key == leftCount) result = node; else result = getNodeByKey(node.right, key - leftCount - 1); node.update(); return result; } Node merge(Node left, Node right) { if (left == null) return right; if (right == null) return left; left.push(); right.push(); Node result; if (left.priority < right.priority) { left.right = merge(left.right, right); result = left; } else { right.left = merge(left, right.left); result = right; } result.update(); return result; } void splitClear() { splitParts[0] = null; splitParts[1] = null; } void split(Node node, int key) { if (node == null) return; node.push(); int leftCount = Node.getCount(node.left); if (key < leftCount) { split(node.left, key); node.left = splitParts[1]; splitParts[1] = node; } else if (key == leftCount) { splitParts[0] = node.left; splitParts[1] = node; node.left = null; } else { split(node.right, key - leftCount - 1); node.right = splitParts[0]; splitParts[0] = node; } node.update(); } } ///////////////////////////////////////////////////////////////////// }
Java
["10 4\n9 14 28 1 7 13 15 29 2 31", "7 3\n3 14 15 92 65 35 89"]
1 second
["24", "64"]
NoteIn the first example you can split the books as follows:$$$$$$(9 + 14 + 28 + 1 + 7) \&amp; (13 + 15) \&amp; (29 + 2) \&amp; (31) = 24.$$$$$$In the second example you can split the books as follows:$$$$$$(3 + 14 + 15 + 92) \&amp; (65) \&amp; (35 + 89) = 64.$$$$$$
Java 8
standard input
[ "dp", "bitmasks", "greedy" ]
9862db32dfd8eab8714d17aaaa338acd
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 50$$$) — the number of books and the number of shelves in the new office. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$, ($$$0 &lt; a_i &lt; 2^{50}$$$) — the prices of the books in the order they stand on the old shelf.
1,900
Print the maximum possible beauty of $$$k$$$ shelves in the new office.
standard output
PASSED
270f46ede4ecafb1b8874329f92d1a38
train_003.jsonl
1527432600
Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly $$$k$$$ bookshelves. He decided that the beauty of the $$$k$$$ shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $$$k$$$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int k=s.nextInt(); long[] arr=new long[n+1]; for(int i=1;i<n+1;i++) { arr[i]=s.nextLong(); } long[] pre=new long[n+1]; for(int i=1;i<n+1;i++) { pre[i]=pre[i-1]+arr[i]; } long ans=0; for(int i=60;i>=0;i--) { long mask=ans|(1l<<i); int[][] dp=new int[n+1][k+1]; for(int j=0;j<n+1;j++) { Arrays.fill(dp[j], -1); } boolean possi=check(pre,dp,mask,0,k); if(possi) { ans=mask; } } System.out.println(ans); } public static boolean check(long[] arr,int[][] dp,long mask,int pos,int k) { if(pos>=arr.length-1) { if(k==0) { return true; } else { return false; } } if(k==0) return false; if(dp[pos][k]!=-1) { if(dp[pos][k]==1) return true; else return false; } dp[pos][k]=0; for(int i=pos+1;i<arr.length;i++) { if((mask&(arr[i]-arr[pos]))==mask) { boolean ans=check(arr,dp,mask,i,k-1); if(ans) { dp[pos][k]=1; } } } if(dp[pos][k]==1) return true; else return false; } }
Java
["10 4\n9 14 28 1 7 13 15 29 2 31", "7 3\n3 14 15 92 65 35 89"]
1 second
["24", "64"]
NoteIn the first example you can split the books as follows:$$$$$$(9 + 14 + 28 + 1 + 7) \&amp; (13 + 15) \&amp; (29 + 2) \&amp; (31) = 24.$$$$$$In the second example you can split the books as follows:$$$$$$(3 + 14 + 15 + 92) \&amp; (65) \&amp; (35 + 89) = 64.$$$$$$
Java 8
standard input
[ "dp", "bitmasks", "greedy" ]
9862db32dfd8eab8714d17aaaa338acd
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 50$$$) — the number of books and the number of shelves in the new office. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$, ($$$0 &lt; a_i &lt; 2^{50}$$$) — the prices of the books in the order they stand on the old shelf.
1,900
Print the maximum possible beauty of $$$k$$$ shelves in the new office.
standard output
PASSED
f8eab5d987ce4690361052951334b229
train_003.jsonl
1527432600
Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly $$$k$$$ bookshelves. He decided that the beauty of the $$$k$$$ shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $$$k$$$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; import java.lang.StringBuilder; import java.util.Arrays; //maintain: array on vertices //a[i]: public class Test10 { public static void main(String[] Args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int mx = 60; String s = sc.nextLine(); s = sc.nextLine(); String[] s1 = s.split(" "); Long[] a = new Long[n]; Long[] sum = new Long[n + 1]; sum[0] = new Long(0); for (int i = 0; i < n; i++) { a[i] = new Long(s1[i]); sum[i + 1] = sum[i] + a[i]; } long suc = 0; long goal = 1; long huge = goal << mx; boolean[][] dp = new boolean[n + 1][k + 1]; for (int i = mx; i >= 0; i--) { goal = suc + huge; //dp for goal dp = new boolean[n + 1][k + 1]; dp[n][0] = true; for (int j = n - 1; j >= 0; j--) { for (int l = j + 1; l <= n; l++) { if (((sum[l] - sum[j]) & goal) == goal) { for (int o = 1; o <= k; o++) { dp[j][o] = dp[j][o] | dp[l][o - 1]; } } } } if (dp[0][k]) suc = goal; huge /= 2; } System.out.println(suc); } }
Java
["10 4\n9 14 28 1 7 13 15 29 2 31", "7 3\n3 14 15 92 65 35 89"]
1 second
["24", "64"]
NoteIn the first example you can split the books as follows:$$$$$$(9 + 14 + 28 + 1 + 7) \&amp; (13 + 15) \&amp; (29 + 2) \&amp; (31) = 24.$$$$$$In the second example you can split the books as follows:$$$$$$(3 + 14 + 15 + 92) \&amp; (65) \&amp; (35 + 89) = 64.$$$$$$
Java 8
standard input
[ "dp", "bitmasks", "greedy" ]
9862db32dfd8eab8714d17aaaa338acd
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 50$$$) — the number of books and the number of shelves in the new office. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$, ($$$0 &lt; a_i &lt; 2^{50}$$$) — the prices of the books in the order they stand on the old shelf.
1,900
Print the maximum possible beauty of $$$k$$$ shelves in the new office.
standard output
PASSED
2ab6120a808a1477d5361bf5ab70eeb3
train_003.jsonl
1527432600
Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly $$$k$$$ bookshelves. He decided that the beauty of the $$$k$$$ shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $$$k$$$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } long mod=998244353L; void work() { int n=in.nextInt(); int k=in.nextInt(); long[] A=new long[n+1]; for(int i=1;i<=n;i++) { A[i]=in.nextLong(); } long ret=0; for(int i=63;i>=0;i--) { long cur=ret+(1L<<i); boolean[][] dp=new boolean[k+1][n+1]; dp[0][0]=true; for(int j=1;j<=k;j++) { out: for(int p=1;p<=n;p++) { long s=0; for(int q=p;q>0;q--) { s+=A[q]; if((s|cur)==s&&dp[j-1][q-1]) { dp[j][p]=true; continue out; } } } } if(dp[k][n]) { ret=cur; } } out.println(ret); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { if(st==null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["10 4\n9 14 28 1 7 13 15 29 2 31", "7 3\n3 14 15 92 65 35 89"]
1 second
["24", "64"]
NoteIn the first example you can split the books as follows:$$$$$$(9 + 14 + 28 + 1 + 7) \&amp; (13 + 15) \&amp; (29 + 2) \&amp; (31) = 24.$$$$$$In the second example you can split the books as follows:$$$$$$(3 + 14 + 15 + 92) \&amp; (65) \&amp; (35 + 89) = 64.$$$$$$
Java 8
standard input
[ "dp", "bitmasks", "greedy" ]
9862db32dfd8eab8714d17aaaa338acd
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 50$$$) — the number of books and the number of shelves in the new office. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$, ($$$0 &lt; a_i &lt; 2^{50}$$$) — the prices of the books in the order they stand on the old shelf.
1,900
Print the maximum possible beauty of $$$k$$$ shelves in the new office.
standard output
PASSED
e1599cf94b285396bfb0b7f5e7042c0f
train_003.jsonl
1527432600
Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly $$$k$$$ bookshelves. He decided that the beauty of the $$$k$$$ shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $$$k$$$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.InputMismatchException; public class D { InputStream is; PrintWriter out; String INPUT = "7 3\n" + "3 14 15 92 65 35 89\n"; long ans,values[] = new long[55],sum[] = new long[55]; int n,k; boolean vis[][] = new boolean[55][55]; void work(long x) { vis[0][0]=true; for(int i=0;i<n;++i) for(int j=0;j<k;++j) if(vis[i][j]) for(int p=i+1;p<=n;++p) if(((sum[p]-sum[i])&x)==x) vis[p][j+1]=true; } void s() { } private void solve() { n = ni(); k = ni(); for(int i=1;i<=n;++i) { (values[i]) = nl(); sum[i]=sum[i-1]+values[i]; } for(int i=62;i != -1;--i) { for (int j = 0; j < 55; ++j) Arrays.fill(vis[j], false); work(ans+(1L<<i)); if(vis[n][k]) ans+=(1L<<i); } out.println(ans); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new D().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } //private boolean oj = true; private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["10 4\n9 14 28 1 7 13 15 29 2 31", "7 3\n3 14 15 92 65 35 89"]
1 second
["24", "64"]
NoteIn the first example you can split the books as follows:$$$$$$(9 + 14 + 28 + 1 + 7) \&amp; (13 + 15) \&amp; (29 + 2) \&amp; (31) = 24.$$$$$$In the second example you can split the books as follows:$$$$$$(3 + 14 + 15 + 92) \&amp; (65) \&amp; (35 + 89) = 64.$$$$$$
Java 8
standard input
[ "dp", "bitmasks", "greedy" ]
9862db32dfd8eab8714d17aaaa338acd
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 50$$$) — the number of books and the number of shelves in the new office. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$, ($$$0 &lt; a_i &lt; 2^{50}$$$) — the prices of the books in the order they stand on the old shelf.
1,900
Print the maximum possible beauty of $$$k$$$ shelves in the new office.
standard output
PASSED
93e3b6594349803d1850f5b50c0d04dc
train_003.jsonl
1527432600
Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly $$$k$$$ bookshelves. He decided that the beauty of the $$$k$$$ shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $$$k$$$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
256 megabytes
//package que_a; import java.io.*; import java.util.*; public class utkarsh { InputStream is; PrintWriter out; long mod = (long) (1e9 + 7); boolean SHOW_TIME; void solve() { //Enter code here utkarsh //SHOW_TIME = true; int n = ni(); int k = ni(); long a[] = new long[n+1]; for(int i = 1; i <= n; i++) a[i] = nl(); long ans = 0; for(long u = 60; u >= 0; u--) { long x = ans + (1L << u); boolean dp[][] = new boolean[n+1][k+1]; dp[0][0] = true; for(int i = 1; i <= n; i++) { for(int j = 1; j <= k; j++) { if(dp[i-1][j-1]) { long y = 0; for(int l = i; l <= n; l++) { y += a[l]; if((x & y) == x) dp[l][j] = true; } } } } if(dp[n][k]) ans = x; } out.println(ans); } //---------- I/O Template ---------- public static void main(String[] args) { new utkarsh().run(); } void run() { is = System.in; out = new PrintWriter(System.out); long start = System.currentTimeMillis(); solve(); long end = System.currentTimeMillis(); if(SHOW_TIME) out.println("\n" + (end - start) + " ms"); out.flush(); } byte input[] = new byte[1024]; int len = 0, ptr = 0; int readByte() { if(ptr >= len) { ptr = 0; try { len = is.read(input); } catch(IOException e) { throw new InputMismatchException(); } if(len <= 0) { return -1; } } return input[ptr++]; } boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); } int skip() { int b = readByte(); while(b != -1 && isSpaceChar(b)) { b = readByte(); } return b; } char nc() { return (char)skip(); } String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } int ni() { int n = 0, b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } if(b == -1) { return -1; } //no input while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } long nl() { long n = 0L; int b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } double nd() { return Double.parseDouble(ns()); } float nf() { return Float.parseFloat(ns()); } int[] na(int n) { int a[] = new int[n]; for(int i = 0; i < n; i++) { a[i] = ni(); } return a; } char[] ns(int n) { char c[] = new char[n]; int i, b = skip(); for(i = 0; i < n; i++) { if(isSpaceChar(b)) { break; } c[i] = (char)b; b = readByte(); } return i == n ? c : Arrays.copyOf(c,i); } }
Java
["10 4\n9 14 28 1 7 13 15 29 2 31", "7 3\n3 14 15 92 65 35 89"]
1 second
["24", "64"]
NoteIn the first example you can split the books as follows:$$$$$$(9 + 14 + 28 + 1 + 7) \&amp; (13 + 15) \&amp; (29 + 2) \&amp; (31) = 24.$$$$$$In the second example you can split the books as follows:$$$$$$(3 + 14 + 15 + 92) \&amp; (65) \&amp; (35 + 89) = 64.$$$$$$
Java 8
standard input
[ "dp", "bitmasks", "greedy" ]
9862db32dfd8eab8714d17aaaa338acd
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 50$$$) — the number of books and the number of shelves in the new office. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$, ($$$0 &lt; a_i &lt; 2^{50}$$$) — the prices of the books in the order they stand on the old shelf.
1,900
Print the maximum possible beauty of $$$k$$$ shelves in the new office.
standard output
PASSED
ab851780ffba795683d62d111de1c7dc
train_003.jsonl
1527432600
Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly $$$k$$$ bookshelves. He decided that the beauty of the $$$k$$$ shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $$$k$$$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
256 megabytes
import java.io.*; import java.util.*; import java.math.BigInteger; import java.util.Map.Entry; import static java.lang.Math.*; public class D extends PrintWriter { void run() { int n = nextInt(); int k = nextInt(); long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } long ans = 0; for (int bit = 60; bit >= 0; bit--) { long mask = ans | (1L << bit); boolean[][] dp = new boolean[k][n]; for (int p = 0; p < k; p++) { if (p == 0) { long sum = 0; for (int i = 0; i < n; i++) { sum += a[i]; dp[p][i] = (sum & mask) == mask; } } else { for (int r = 1; r < n; r++) { long sum = 0; for (int l = r; l >= 1; l--) { sum += a[l]; dp[p][r] |= dp[p - 1][l - 1] && ((sum & mask) == mask); } } } } if (dp[k - 1][n - 1]) { ans = mask; // println(Long.toBinaryString(ans)); } } println(ans); } boolean skip() { while (hasNext()) { next(); } return true; } int[][] nextMatrix(int n, int m) { int[][] matrix = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) matrix[i][j] = nextInt(); return matrix; } String next() { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } boolean hasNext() { while (!tokenizer.hasMoreTokens()) { String line = nextLine(); if (line == null) { return false; } tokenizer = new StringTokenizer(line); } return true; } int[] nextArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { return reader.readLine(); } catch (IOException err) { return null; } } public D(OutputStream outputStream) { super(outputStream); } static BufferedReader reader; static StringTokenizer tokenizer = new StringTokenizer(""); static Random rnd = new Random(); static boolean OJ; public static void main(String[] args) throws IOException { OJ = System.getProperty("ONLINE_JUDGE") != null; D solution = new D(System.out); if (OJ) { reader = new BufferedReader(new InputStreamReader(System.in)); solution.run(); } else { reader = new BufferedReader(new FileReader(new File(D.class.getName() + ".txt"))); long timeout = System.currentTimeMillis(); while (solution.hasNext()) { solution.run(); solution.println(); solution.println("----------------------------------"); } solution.println("time: " + (System.currentTimeMillis() - timeout)); } solution.close(); reader.close(); } }
Java
["10 4\n9 14 28 1 7 13 15 29 2 31", "7 3\n3 14 15 92 65 35 89"]
1 second
["24", "64"]
NoteIn the first example you can split the books as follows:$$$$$$(9 + 14 + 28 + 1 + 7) \&amp; (13 + 15) \&amp; (29 + 2) \&amp; (31) = 24.$$$$$$In the second example you can split the books as follows:$$$$$$(3 + 14 + 15 + 92) \&amp; (65) \&amp; (35 + 89) = 64.$$$$$$
Java 8
standard input
[ "dp", "bitmasks", "greedy" ]
9862db32dfd8eab8714d17aaaa338acd
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 50$$$) — the number of books and the number of shelves in the new office. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$, ($$$0 &lt; a_i &lt; 2^{50}$$$) — the prices of the books in the order they stand on the old shelf.
1,900
Print the maximum possible beauty of $$$k$$$ shelves in the new office.
standard output
PASSED
7a1a57133955eff844ac4f3fd68b1e3e
train_003.jsonl
1527432600
Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly $$$k$$$ bookshelves. He decided that the beauty of the $$$k$$$ shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $$$k$$$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
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 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int k = in.readInt(); long[] a = IOUtils.readLongArray(in, n); long[][] sums = new long[n][n]; for (int L = 0; L < n; L++) { for (int R = L; R < n; R++) { long s = 0; for (int i = L; i <= R; i++) { s += a[i]; } sums[L][R] = s; } } long ans = 0; for (int bit = 62; bit >= 0; bit--) { long andMask = 1L << bit; long[][] dp = new long[k + 1][n + 1]; dp[0][0] = andMask; for (int curK = 0; curK < k; curK++) { for (int curN = 0; curN < n; curN++) { long curVal = dp[curK][curN]; for (int addN = 1; addN + curN <= n; addN++) { long newVal = sums[curN][curN + addN - 1] & andMask; dp[curK + 1][curN + addN] = Math.max(dp[curK + 1][curN + addN], curVal & newVal); } } } long curAns = dp[k][n]; // System.err.println("bit = " + bit + ", curAns = " + curAns); if (curAns != 0) { if (curAns != andMask) { throw new AssertionError(); } ans |= andMask; for (int L = 0; L < n; L++) { for (int R = L; R < n; R++) { if ((sums[L][R] & andMask) == 0) { sums[L][R] = 0; } } } } } out.printLine(ans); } } static class IOUtils { public static long[] readLongArray(InputReader in, int size) { long[] array = new long[size]; for (int i = 0; i < size; i++) { array[i] = in.readLong(); } return array; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 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
["10 4\n9 14 28 1 7 13 15 29 2 31", "7 3\n3 14 15 92 65 35 89"]
1 second
["24", "64"]
NoteIn the first example you can split the books as follows:$$$$$$(9 + 14 + 28 + 1 + 7) \&amp; (13 + 15) \&amp; (29 + 2) \&amp; (31) = 24.$$$$$$In the second example you can split the books as follows:$$$$$$(3 + 14 + 15 + 92) \&amp; (65) \&amp; (35 + 89) = 64.$$$$$$
Java 8
standard input
[ "dp", "bitmasks", "greedy" ]
9862db32dfd8eab8714d17aaaa338acd
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 50$$$) — the number of books and the number of shelves in the new office. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$, ($$$0 &lt; a_i &lt; 2^{50}$$$) — the prices of the books in the order they stand on the old shelf.
1,900
Print the maximum possible beauty of $$$k$$$ shelves in the new office.
standard output
PASSED
903415d32636ab6b21eb985294869f10
train_003.jsonl
1527432600
Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly $$$k$$$ bookshelves. He decided that the beauty of the $$$k$$$ shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $$$k$$$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
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.Random; import java.util.StringTokenizer; public class D { static int N, K; static long[] values; static long target; static int[][] posible; static boolean can(long t) { target = t; for (int i = 0; i < posible.length; i++) { Arrays.fill(posible[i], -1); } return calc(0,K) > 0; } static int calc(int pos, int rem) { int ret = posible[pos][rem]; if (ret != -1) return ret; if (pos == N) return posible[pos][rem] = rem == 0 ? 1 : 0; if (rem == 0) return posible[pos][rem] = 0; ret = 0; long sum = 0; for (int i = pos; i < N && ret == 0; i++) { sum += values[i]; if ((sum & target) == target && calc(i + 1, rem - 1) > 0) ret = 1; } return posible[pos][rem] = ret; } public static void main(String[] args) throws IOException { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(System.out); N = sc.nextInt(); K = sc.nextInt(); values = new long[N]; for (int i = 0; i < values.length; i++) { values[i] = sc.nextLong(); } posible = new int[N + 1][K+1]; long ans = 0; long curbit = 1L << 60; while (curbit > 0) { long newAns = ans | curbit; if (can(newAns)) { ans = newAns; } curbit /= 2; } out.println(ans); out.flush(); } static class MyScanner { private BufferedReader br; private StringTokenizer tokenizer; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["10 4\n9 14 28 1 7 13 15 29 2 31", "7 3\n3 14 15 92 65 35 89"]
1 second
["24", "64"]
NoteIn the first example you can split the books as follows:$$$$$$(9 + 14 + 28 + 1 + 7) \&amp; (13 + 15) \&amp; (29 + 2) \&amp; (31) = 24.$$$$$$In the second example you can split the books as follows:$$$$$$(3 + 14 + 15 + 92) \&amp; (65) \&amp; (35 + 89) = 64.$$$$$$
Java 8
standard input
[ "dp", "bitmasks", "greedy" ]
9862db32dfd8eab8714d17aaaa338acd
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 50$$$) — the number of books and the number of shelves in the new office. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$, ($$$0 &lt; a_i &lt; 2^{50}$$$) — the prices of the books in the order they stand on the old shelf.
1,900
Print the maximum possible beauty of $$$k$$$ shelves in the new office.
standard output
PASSED
c639dfd7721550758defe43b01ba7daa
train_003.jsonl
1527432600
Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly $$$k$$$ bookshelves. He decided that the beauty of the $$$k$$$ shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $$$k$$$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
256 megabytes
/* * Author Ayub Subhaniya * Institute DA-IICT */ import java.io.*; import java.math.*; import java.util.*; public class Tester { InputStream in; PrintWriter out; long mod=(long)1e9+7; int MAX=(int)1e5+7; double eps=1e-6; int n,k; long a[]; void solve() { n=ni(); k=ni(); a=new long[n+1]; for (int i=1;i<=n;i++) a[i]=a[i-1]+nl(); long mask=0; for (int bit=61;bit>=0;bit--) { mask+=(1l<<bit); if (!check(mask)) mask-=(1l<<bit); } out.println(mask); } boolean check(long mask) { boolean dp[][]=new boolean[k+1][n+1]; dp[0][0]=true; for (int bs=1;bs<=k;bs++) for (int i=bs-1;i<=n;i++) for (int j=1;j+i<=n;j++) if (((a[i+j]-a[i])&mask)==mask) dp[bs][i+j]|=dp[bs-1][i]; return dp[k][n]; } class Pair implements Comparable<Pair> { int x; int y; int z; Pair(int a,int b,int c) { x=a; y=b; z=c; } @Override public boolean equals(Object o) { Pair other = (Pair)o; return x == other.x && y == other.y; } public String toString() { return x+" "+y+" "+z; } @Override public int compareTo(Pair o) { if (x==o.x) return Integer.compare(y, o.y); else return Integer.compare(x, o.x); } @Override public int hashCode() { return Objects.hash(x, y); } } long pow(long x, long n, long M) { x%=M; long result = 1; while (n > 0) { if (n % 2 == 1) result = (result * x) % M; x = (x * x) % M; n = n / 2; } return result; } long modInverse(long A, long M) { extendedEuclid(A, M); return (EEx % M + M) % M; } long EEd, EEx, EEy; void extendedEuclid(long A, long B) { if (B == 0) { EEd = A; EEx = 1; EEy = 0; } else { extendedEuclid(B, A % B); long temp = EEx; EEx = EEy; EEy = temp - (A / B) * EEy; } } int max(int a,int b) { if(a>b) return a; else return b; } int min(int a,int b) { if(a>b) return b; else return a; } long max(long a,long b) { if(a>b) return a; else return b; } long min(long a,long b) { if(a>b) return b; else return a; } long add(long a,long b) { long x=(a+b); while(x>=mod) x-=mod; return x; } long sub(long a,long b) { long x=(a-b); while(x<0) x+=mod; return x; } long mul(long a,long b) { a%=mod; b%=mod; long x=(a*b); return x%mod; } void run() throws Exception { String INPUT = "/Users/ayubsubhaniya/IdeaProjects/Test/src/input.txt"; in = oj ? System.in : new FileInputStream(INPUT); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Tester().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = in.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean inSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && inSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(inSpaceChar(b))) { // when nextLine, (inSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(inSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } }
Java
["10 4\n9 14 28 1 7 13 15 29 2 31", "7 3\n3 14 15 92 65 35 89"]
1 second
["24", "64"]
NoteIn the first example you can split the books as follows:$$$$$$(9 + 14 + 28 + 1 + 7) \&amp; (13 + 15) \&amp; (29 + 2) \&amp; (31) = 24.$$$$$$In the second example you can split the books as follows:$$$$$$(3 + 14 + 15 + 92) \&amp; (65) \&amp; (35 + 89) = 64.$$$$$$
Java 8
standard input
[ "dp", "bitmasks", "greedy" ]
9862db32dfd8eab8714d17aaaa338acd
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 50$$$) — the number of books and the number of shelves in the new office. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$, ($$$0 &lt; a_i &lt; 2^{50}$$$) — the prices of the books in the order they stand on the old shelf.
1,900
Print the maximum possible beauty of $$$k$$$ shelves in the new office.
standard output
PASSED
2efc3c9dd68460697e062499c3e64832
train_003.jsonl
1527432600
Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly $$$k$$$ bookshelves. He decided that the beauty of the $$$k$$$ shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $$$k$$$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
256 megabytes
import java.util.*; import java.io.*; public class Main { class Node { int id; long mask; public Node(int id,long mask){ this.id=id; this.mask=mask; } public boolean equals(Node t1){ if(t1 instanceof Node){ return id==t1.id && mask==t1.mask; }else return false; } } void solve() { int n=ni(),k=ni(); a=new long[n+1]; sum=new long[n+1]; for(int i=1;i<=n;i++){ a[i]=nl(); sum[i]=sum[i-1]+a[i]; } dp=new boolean[n+1][k+1]; long ans=0; mp=new HashMap<>(); long pow[]=new long[61]; pow[0]=1; for(int i=1;i<=60;i++) pow[i]=(pow[i-1]*2); // pw.println(pow[60]); for(int i=60;i>=0;i--){ ans+=pow[i]; if(!check(ans,n,k)) ans -= pow[i]; } pw.println(ans); } long a[]; boolean dp[][]; long sum[]; boolean check(long ans,int n,int k){ for(int i=0;i<=n;i++) Arrays.fill(dp[i],false); dp[0][0]=true; for(int i=1;i<=n;i++){ for(int j=1;j<=k;j++){ for(int len=1;len<=i;len++){ dp[i][j]=dp[i][j] || ((((sum[i]-sum[i-len])&ans)==ans) && dp[i-len][j-1]); } } } return dp[n][k]; } HashMap<Node,Integer> mp; int go(int i,long mask,long xr,int j,long sum,int n,int k,long ans){ if(i>n){ if(j==k && (sum&ans)==ans) return 1; else return 0; } if(j>k){ return 0; } if(mp.containsKey(new Node(i,mask))) return mp.get(new Node(i,mask)); int cc=0; int id=i; long sum2=sum; while(id<=n) { sum2+=a[id]; id++; if((sum2&ans)==ans) cc = go(id, mask, xr, j, sum2, n, k, ans); if (cc == 1) { mp.put(new Node(i,mask),cc); return 1; } } if(j<k) { id=i; sum2=0; while(id<=n) { sum2+=a[id]; id++; if ((sum2 & ans) == ans) { cc = go(id, mask + (1 << (i - 1)), xr == -1 ? sum : xr & sum, j + 1, sum2, n, k, ans); if(cc==1){ mp.put(new Node(i,mask),cc); return cc; } } } } mp.put(new Node(i,mask),cc); return cc; } long M=(long)1e9+7; InputStream is; PrintWriter pw; String INPUT = ""; void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); pw = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); pw.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); } }
Java
["10 4\n9 14 28 1 7 13 15 29 2 31", "7 3\n3 14 15 92 65 35 89"]
1 second
["24", "64"]
NoteIn the first example you can split the books as follows:$$$$$$(9 + 14 + 28 + 1 + 7) \&amp; (13 + 15) \&amp; (29 + 2) \&amp; (31) = 24.$$$$$$In the second example you can split the books as follows:$$$$$$(3 + 14 + 15 + 92) \&amp; (65) \&amp; (35 + 89) = 64.$$$$$$
Java 8
standard input
[ "dp", "bitmasks", "greedy" ]
9862db32dfd8eab8714d17aaaa338acd
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 50$$$) — the number of books and the number of shelves in the new office. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$, ($$$0 &lt; a_i &lt; 2^{50}$$$) — the prices of the books in the order they stand on the old shelf.
1,900
Print the maximum possible beauty of $$$k$$$ shelves in the new office.
standard output
PASSED
3a13840a7d1d01bde9c11ae65b63ce27
train_003.jsonl
1527432600
Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly $$$k$$$ bookshelves. He decided that the beauty of the $$$k$$$ shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $$$k$$$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
256 megabytes
import java.io.*; import java.math.*; import java.security.KeyStore.Entry; import java.util.*; /* yash jobanputra DA-IICT */ public class yash { private static InputStream stream; private static byte[] buf = new byte[1024]; private static int curChar; private static int numChars; private static SpaceCharFilter filter; private static PrintWriter pw; private static long mod = 1000000000 + 7; private static long mod1 = 1000000000 + 9; private static int MAX=1000001; private static int block; private static long[] suma; private static long[] cost; private static int times; private static int n,k; private static int max=51; private static boolean[] vis; private static boolean[] vis2; private static long[] sa; private static long count; private static boolean ff; //private static long[] dist; public static void soln() { n=ni();k=ni(); long[] arr=nla(n); sa=new long[n+1]; sa[0]=0; for(int i=1;i<=n;i++) sa[i]=sa[i-1]+arr[i-1]; long ans=0;long l=1; for(long i=55;i>=0;i--) { long p=~((l<<i)-1); if(fun(ans|(l<<i),p)) ans|=(l<<i); } pw.print(ans); } public static boolean fun(long tar,long mask) { boolean[][] ts=new boolean[51][51]; ts[0][0]=true; for(int i=1;i<=n;i++) { for(int j=0;j<i;j++) { if(((sa[i]-sa[j])&tar&mask)==tar) { for(int k=0;k<max;k++) { if(ts[j][k]) ts[i][k+1]=true; } } } } return ts[n][k]; } public static class lca{ int[] e; int[] l; int[] h; int[] level; boolean[] vis; int time; int[] tree=new int[10000000]; int[] lazy=new int[10000000]; int n; public lca(ArrayList<Integer>[] g) { n=g.length-1; pw.println(n); e=new int[2*n]; l=new int[2*n]; h=new int[n+1]; vis=new boolean[n+1]; level=new int[n+1]; level[1]=0; dfs(g,1); Arrays.fill(lazy, 0); build(l,0,0,2*n-1); } public int lf(int u,int v) { int a=h[u];int b=h[v]; if(h[u]>h[v]) {a=h[v];b=h[u];} int p=query(l,0,0,2*n-1,a,b); return e[p]; } public void dfs(ArrayList<Integer>[] gr,int v) { vis[v]=true; time++; e[time]=v; l[time]=level[v]; h[v]=time; ArrayList<Integer> arr=gr[v]; for(int i=0;i<arr.size();i++) { if(!vis[arr.get(i)]) { level[arr.get(i)]=level[v]+1; dfs(gr,arr.get(i)); time++;e[time]=v;l[time]=level[v]; } } } public void build(int[] arr,int node,int l,int r) { if(l==r) { tree[node]=l; } else { int m=(l+r)/2; build(arr,(2*node)+1,l,m); build(arr,(2*node)+2,m+1,r); if(arr[tree[2*node+1]]<arr[tree[2*node+2]]) tree[node]=tree[2*node+1]; else tree[node]=tree[2*node+2]; } } public int query(int[] arr,int node,int l,int r,int s,int e) { if(e<l || r<s) return -1; if(s<=l && e>=r) return tree[node]; int m=(l+r)/2; int p1=query(arr,(2*node+1),l,m,s,e); int p2=query(arr,(2*node+2),m+1,r,s,e); if(p1==-1) return p2; else if(p2==-1) return p1; else { if(arr[p1]<arr[p2]) return p1; else return p2; } } } public static long[] reverse(long[] arr, int l, int r) { int d = (r-l+1)/2; for(int i=0;i<d;i++) { long t = arr[l+i]; arr[l+i] = arr[r-i]; arr[r-i] = t; } return arr; } private static class graph{ public static void dfs(ArrayList<Integer>[] gr,int v) { vis[v]=true; ArrayList<Integer> arr=gr[v]; if(gr[v].size()==1) count++; for(int i=0;i<arr.size();i++) { if(!vis[arr.get(i)]) { dfs(gr,arr.get(i)); } } } public static void arti(boolean[] ap,int[] parent,int[] disc,int[] low,ArrayList<Integer>[] gr,boolean[] vis,int ver) { int child=0; vis[ver]=true; ArrayList<Integer> arr=gr[ver]; times++; disc[ver]=low[ver]=times; for(int i=0;i<arr.size();i++) { if(!vis[arr.get(i)]) { child++; parent[arr.get(i)]=ver; arti(ap,parent,disc,low,gr,vis,arr.get(i)); low[ver]=Math.min(low[ver], low[arr.get(i)]); if(parent[ver]!=0 && low[arr.get(i)]>=disc[ver]) ap[ver]=true; if(parent[ver]==0 && child>1) ap[ver]=true; } else if(parent[ver]!=arr.get(i)) low[ver]=Math.min(low[ver], disc[arr.get(i)]); } } public static void floyd(Pair[] arr,int n,int m,int[][] dist) { for(int i=0;i<=n;i++) { Arrays.fill(dist[i], Integer.MAX_VALUE); } for(int c=0;c<m;c++) { int w=arr[c].v; int a=arr[c].j.v; int b=arr[c].j.i; dist[a][b]=w; } for(int i=0;i<=n;i++) dist[i][i]=0; for(int k=1;k<=n;k++) { for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { if(dist[i][k]!=Integer.MAX_VALUE && dist[k][j]!=Integer.MAX_VALUE) dist[i][j]=Math.min(dist[i][j], dist[i][k]+dist[k][j]); } } } } public static boolean bfs(ArrayList<Integer>[] gr,int v,int n) { boolean[] vis=new boolean[n+1]; int c2=0; Queue<Integer> q=new LinkedList<>(); q.add(v); while(!q.isEmpty()) { int x=q.poll(); Iterator<Integer> it=gr[x].iterator(); while(it.hasNext()) { int p=it.next(); if(!vis[p]) { q.add(p); c2++; vis[p]=true; } } } return c2==n; } public static ArrayList<Pair> MSTP(int n,int m,ArrayList<Pair>[] arr,int[][] arr2) { ArrayList<Pair> pp=new ArrayList<>(); int[] par=new int[n+1]; int[] key=new int[n+1]; vis=new boolean[n+1]; Arrays.fill(key, Integer.MAX_VALUE); key[1]=0; PriorityQueue<Integer> dis=new PriorityQueue<>(n+1, new Comparator<Integer>() { public int compare(Integer p,Integer q) { return key[p]-key[q]; } } ); dis.add(1); vis[1]=true; while(!dis.isEmpty()) { //pw.println(dis); int u=dis.poll(); ArrayList<Pair> p=arr[u]; for(int i=0;i<p.size();i++) { if(key[u]+p.get(i).i<key[p.get(i).v]) { key[p.get(i).v]=key[u]+p.get(i).i; par[p.get(i).v]=u; if(!vis[p.get(i).v]) { dis.add(p.get(i).v); vis[p.get(i).v]=true; } } } } for(int i=1;i<=n;i++) pp.add(new Pair(i,par[i])); return pp; } public static ArrayList<Pair> MSTK(int n,int m,Pair[] arr) { ArrayList<Pair> pp=new ArrayList<>(); long sum=0; Arrays.sort(arr); DSU x=new DSU(n+1); for(int c=0;(c<m);c++) { Pair p=arr[c]; //int a=p.v; //int b=p.i; int a=p.j.v; int b=p.j.i; int w=p.v; if(x.find(a)!=x.find(b)) { pp.add(new Pair(w,new Pair(a,b))); x.Union(a, b); } } return pp; } public static int[] dijkstras(ArrayList<Pair>[] gr) { int n=gr.length-1; int[] dist=new int[n+1]; Arrays.fill(dist, Integer.MAX_VALUE); PriorityQueue<Integer> dis=new PriorityQueue<>(n+1, new Comparator<Integer>() { public int compare(Integer p,Integer q) { return dist[p]-dist[q]; } } ); boolean[] vis=new boolean[n+1]; Arrays.fill(vis, false); int s=1; dist[s]=0; dis.add(s); vis[s]=true; while(!dis.isEmpty()) { int p=dis.poll(); for(int i=0;i<gr[p].size();i++) { int y=gr[p].get(i).v; int w=gr[p].get(i).i; if(!vis[y]) { dist[y]=dist[p]+w; dis.add(y); vis[y]=true; } else { if(dist[p]+w<dist[y]) { dist[y]=dist[p]+w; } } } } return dist; } } public static class sieve{ public static ArrayList<Integer> sieves(int n) { ArrayList<Integer> arr=new ArrayList<>(); boolean[] bol=new boolean[n+1]; Arrays.fill(bol, true); //arr.add(1); for(int i=2;i<=n;i++) { if(bol[i]) { arr.add(i); for(int j=2;j*i<=n;j++) { bol[i*j]=false; } } } return arr; } } public static class isprime{ public static boolean check(int n) { if(n==2) return true; else if(n==3) return true; else if(n%2==0) return false; else if(n%3==0) return false; else { for(int i=6;;i+=6) { if(i>Math.sqrt(n)) break; if(n%(i-1)==0) { return false; } else if(n%(i+1)==0) return false; } return true; } } } private static class DSU{ int[] parent; int[] rank; int cnt; public DSU(int n){ parent=new int[n]; rank=new int[n]; for(int i=0;i<n;i++){ parent[i]=i; rank[i]=1; } cnt=n; } int find(int i){ while(parent[i] !=i){ parent[i]=parent[parent[i]]; i=parent[i]; } return i; } int Union(int x, int y){ int xset = find(x); int yset = find(y); if(xset!=yset) cnt--; if(rank[xset]<rank[yset]){ parent[xset] = yset; rank[yset]+=rank[xset]; rank[xset]=0; return yset; }else{ parent[yset]=xset; rank[xset]+=rank[yset]; rank[yset]=0; return xset; } } } private static class Pair implements Comparable<Pair>{ int v,i;Pair j; public Pair(int a,int b){ v=a; i=b; } public Pair(int a,Pair b) { v=a; j=b; } @Override public int compareTo(Pair arg0) { { return this.v-arg0.v; } } } private static class Pairl implements Comparable<Pairl>{ long v,i;Pairl j; public Pairl(long a,long b){ v=a; i=b; } public Pairl(long a,Pairl b) { v=a; j=b; } @Override public int compareTo(Pairl arg0) { { if(this.v>arg0.v) return 1; else return -1; } } } public static long f(long number,long m) { if (number <= 1) return 1; else return (number * f(number - 1,m))%m; } public static long mmi(long a, long m) { long m0 = m; long y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient long q = a / m; long t = m; // m is remainder now, process same as // Euclid's algo m = a % m; a = t; t = y; // Update y and x y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x; } public static class segtree{ static int[] tree=new int[10000000]; static int[] lazy=new int[10000000]; public static void initial() { Arrays.fill(lazy, 0); } public static void build(int[] arr,int node,int l,int r) { if(l==r) { tree[node]=arr[l]; } else { int m=(l+r)/2; build(arr,(2*node)+1,l,m); build(arr,(2*node)+2,m+1,r); tree[node]=tree[2*node+1]+tree[(2*node)+2]; } } public static void updater(int[] arr,int node,int l,int r,int s,int e,int val) { if(lazy[node]!=0) { tree[node]+=(r-l+1)*lazy[node]; if(l!=r) { lazy[2*node+1]+=lazy[node]; lazy[2*node+2]+=lazy[node]; } lazy[node]=0; } if(s<=l && e>=r) { tree[node]+=(r-l+1)*val; if(l!=r) { lazy[2*node+1]+=val; lazy[2*node+2]+=val; } } else if(!(e<l || r<s)) { int m=(l+r)/2; updater(arr,2*node+1,l,m,s,e,val); updater(arr,2*node+2,m+1,r,s,e,val); tree[node]=tree[2*node+1]+tree[2*node+2]; } } public static void update(int[] arr,int node,int l,int r,int ind,int val) { if(l==r) { arr[ind]+=val; tree[node]+=val; } else { int m=(l+r)/2; if(l<=ind && ind<=m) { update(arr,(2*node+1),l,m,ind,val); } else { update(arr,(2*node+2),m+1,r,ind,val); } tree[node]=tree[2*node+1]+tree[2*node+2]; } } public static int query(int node,int l,int r,int s,int e) { if(lazy[node]!=0) { tree[node]+=(r-l+1)*lazy[node]; if(l!=r) { lazy[2*node+1]+=lazy[node]; lazy[2*node+2]+=lazy[node]; } lazy[node]=0; } if(e<l || r<s) return 0; if(s<=l && e>=r) return tree[node]; int m=(l+r)/2; int p1=query((2*node+1),l,m,s,e); int p2=query((2*node+2),m+1,r,s,e); return (p1+p2); } } private static long pow(long a, long b, long c) { if (b == 0) return 1; long p = pow(a, b / 2, c); p = (p * p) % c; return (b % 2 == 0) ? p : (a * p) % c; } private static long gcd(long n, long l) { if (l == 0) return n; return gcd(l, n % l); } private static int gcd(int n, int l) { if (l == 0) return n; return gcd(l, n % l); } private static long max(long a, long b) { if (a > b) return a; return b; } private static long min(long a, long b) { if (a < b) return a; return b; } public static void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int [n1]; int R[] = new int [n2]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } public static void sort(int arr[]) { sort(arr,0,arr.length-1); } public static void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } public static void main(String[] args) throws Exception { new Thread(null,new Runnable(){ @Override public void run() { /* try { InputReader(new FileInputStream("input.txt")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ InputReader(System.in); pw = new PrintWriter(System.out); /*try { pw=new PrintWriter(new FileOutputStream("output.txt")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ soln(); pw.close(); } },"1",1<<26).start(); } public static void InputReader(InputStream stream1) { stream = stream1; } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private static boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } private static 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++]; } private static int ni() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private static long nl() { 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; } private static double nd() { double ret = 0, div = 1; int c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private static String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private static String nli() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } private static int[] nia(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } private static long[] nla(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nl(); } return arr; } private static void pa(int[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static void pa(long[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } private static char nc() { int c = read(); while (isSpaceChar(c)) c = read(); char c1=(char)c; while(!isSpaceChar(c)) c=read(); return c1; } public String ns() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["10 4\n9 14 28 1 7 13 15 29 2 31", "7 3\n3 14 15 92 65 35 89"]
1 second
["24", "64"]
NoteIn the first example you can split the books as follows:$$$$$$(9 + 14 + 28 + 1 + 7) \&amp; (13 + 15) \&amp; (29 + 2) \&amp; (31) = 24.$$$$$$In the second example you can split the books as follows:$$$$$$(3 + 14 + 15 + 92) \&amp; (65) \&amp; (35 + 89) = 64.$$$$$$
Java 8
standard input
[ "dp", "bitmasks", "greedy" ]
9862db32dfd8eab8714d17aaaa338acd
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 50$$$) — the number of books and the number of shelves in the new office. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$, ($$$0 &lt; a_i &lt; 2^{50}$$$) — the prices of the books in the order they stand on the old shelf.
1,900
Print the maximum possible beauty of $$$k$$$ shelves in the new office.
standard output
PASSED
fa78806aa395581101ccf799bb492e23
train_003.jsonl
1527432600
Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly $$$k$$$ bookshelves. He decided that the beauty of the $$$k$$$ shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $$$k$$$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
256 megabytes
import java.io.*; import java.math.*; import java.security.KeyStore.Entry; import java.util.*; /* yash jobanputra DA-IICT */ public class yash { private static InputStream stream; private static byte[] buf = new byte[1024]; private static int curChar; private static int numChars; private static SpaceCharFilter filter; private static PrintWriter pw; private static long mod = 1000000000 + 7; private static long mod1 = 1000000000 + 9; private static int MAX=1000001; private static int block; private static long[] suma; private static long[] cost; private static int times; private static int n,k; private static int max=51; private static boolean[] vis; private static boolean[] vis2; private static long[] sa; private static long count; private static boolean ff; //private static long[] dist; public static void soln() { n=ni();k=ni(); long[] arr=nla(n); sa=new long[n+1]; sa[0]=0; for(int i=1;i<=n;i++) sa[i]=sa[i-1]+arr[i-1]; long ans=0;long l=1; for(long i=55;i>=0;i--) { long p=~((l<<i)-1); if(fun(ans|(l<<i))) ans|=(l<<i); } pw.print(ans); } public static boolean fun(long tar) { boolean[][] ts=new boolean[51][51]; ts[0][0]=true; for(int i=1;i<=n;i++) { for(int j=0;j<i;j++) { if(((sa[i]-sa[j])&tar)==tar) { for(int k=0;k<max;k++) { if(ts[j][k]) ts[i][k+1]=true; } } } } return ts[n][k]; } public static class lca{ int[] e; int[] l; int[] h; int[] level; boolean[] vis; int time; int[] tree=new int[10000000]; int[] lazy=new int[10000000]; int n; public lca(ArrayList<Integer>[] g) { n=g.length-1; pw.println(n); e=new int[2*n]; l=new int[2*n]; h=new int[n+1]; vis=new boolean[n+1]; level=new int[n+1]; level[1]=0; dfs(g,1); Arrays.fill(lazy, 0); build(l,0,0,2*n-1); } public int lf(int u,int v) { int a=h[u];int b=h[v]; if(h[u]>h[v]) {a=h[v];b=h[u];} int p=query(l,0,0,2*n-1,a,b); return e[p]; } public void dfs(ArrayList<Integer>[] gr,int v) { vis[v]=true; time++; e[time]=v; l[time]=level[v]; h[v]=time; ArrayList<Integer> arr=gr[v]; for(int i=0;i<arr.size();i++) { if(!vis[arr.get(i)]) { level[arr.get(i)]=level[v]+1; dfs(gr,arr.get(i)); time++;e[time]=v;l[time]=level[v]; } } } public void build(int[] arr,int node,int l,int r) { if(l==r) { tree[node]=l; } else { int m=(l+r)/2; build(arr,(2*node)+1,l,m); build(arr,(2*node)+2,m+1,r); if(arr[tree[2*node+1]]<arr[tree[2*node+2]]) tree[node]=tree[2*node+1]; else tree[node]=tree[2*node+2]; } } public int query(int[] arr,int node,int l,int r,int s,int e) { if(e<l || r<s) return -1; if(s<=l && e>=r) return tree[node]; int m=(l+r)/2; int p1=query(arr,(2*node+1),l,m,s,e); int p2=query(arr,(2*node+2),m+1,r,s,e); if(p1==-1) return p2; else if(p2==-1) return p1; else { if(arr[p1]<arr[p2]) return p1; else return p2; } } } public static long[] reverse(long[] arr, int l, int r) { int d = (r-l+1)/2; for(int i=0;i<d;i++) { long t = arr[l+i]; arr[l+i] = arr[r-i]; arr[r-i] = t; } return arr; } private static class graph{ public static void dfs(ArrayList<Integer>[] gr,int v) { vis[v]=true; ArrayList<Integer> arr=gr[v]; if(gr[v].size()==1) count++; for(int i=0;i<arr.size();i++) { if(!vis[arr.get(i)]) { dfs(gr,arr.get(i)); } } } public static void arti(boolean[] ap,int[] parent,int[] disc,int[] low,ArrayList<Integer>[] gr,boolean[] vis,int ver) { int child=0; vis[ver]=true; ArrayList<Integer> arr=gr[ver]; times++; disc[ver]=low[ver]=times; for(int i=0;i<arr.size();i++) { if(!vis[arr.get(i)]) { child++; parent[arr.get(i)]=ver; arti(ap,parent,disc,low,gr,vis,arr.get(i)); low[ver]=Math.min(low[ver], low[arr.get(i)]); if(parent[ver]!=0 && low[arr.get(i)]>=disc[ver]) ap[ver]=true; if(parent[ver]==0 && child>1) ap[ver]=true; } else if(parent[ver]!=arr.get(i)) low[ver]=Math.min(low[ver], disc[arr.get(i)]); } } public static void floyd(Pair[] arr,int n,int m,int[][] dist) { for(int i=0;i<=n;i++) { Arrays.fill(dist[i], Integer.MAX_VALUE); } for(int c=0;c<m;c++) { int w=arr[c].v; int a=arr[c].j.v; int b=arr[c].j.i; dist[a][b]=w; } for(int i=0;i<=n;i++) dist[i][i]=0; for(int k=1;k<=n;k++) { for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { if(dist[i][k]!=Integer.MAX_VALUE && dist[k][j]!=Integer.MAX_VALUE) dist[i][j]=Math.min(dist[i][j], dist[i][k]+dist[k][j]); } } } } public static boolean bfs(ArrayList<Integer>[] gr,int v,int n) { boolean[] vis=new boolean[n+1]; int c2=0; Queue<Integer> q=new LinkedList<>(); q.add(v); while(!q.isEmpty()) { int x=q.poll(); Iterator<Integer> it=gr[x].iterator(); while(it.hasNext()) { int p=it.next(); if(!vis[p]) { q.add(p); c2++; vis[p]=true; } } } return c2==n; } public static ArrayList<Pair> MSTP(int n,int m,ArrayList<Pair>[] arr,int[][] arr2) { ArrayList<Pair> pp=new ArrayList<>(); int[] par=new int[n+1]; int[] key=new int[n+1]; vis=new boolean[n+1]; Arrays.fill(key, Integer.MAX_VALUE); key[1]=0; PriorityQueue<Integer> dis=new PriorityQueue<>(n+1, new Comparator<Integer>() { public int compare(Integer p,Integer q) { return key[p]-key[q]; } } ); dis.add(1); vis[1]=true; while(!dis.isEmpty()) { //pw.println(dis); int u=dis.poll(); ArrayList<Pair> p=arr[u]; for(int i=0;i<p.size();i++) { if(key[u]+p.get(i).i<key[p.get(i).v]) { key[p.get(i).v]=key[u]+p.get(i).i; par[p.get(i).v]=u; if(!vis[p.get(i).v]) { dis.add(p.get(i).v); vis[p.get(i).v]=true; } } } } for(int i=1;i<=n;i++) pp.add(new Pair(i,par[i])); return pp; } public static ArrayList<Pair> MSTK(int n,int m,Pair[] arr) { ArrayList<Pair> pp=new ArrayList<>(); long sum=0; Arrays.sort(arr); DSU x=new DSU(n+1); for(int c=0;(c<m);c++) { Pair p=arr[c]; //int a=p.v; //int b=p.i; int a=p.j.v; int b=p.j.i; int w=p.v; if(x.find(a)!=x.find(b)) { pp.add(new Pair(w,new Pair(a,b))); x.Union(a, b); } } return pp; } public static int[] dijkstras(ArrayList<Pair>[] gr) { int n=gr.length-1; int[] dist=new int[n+1]; Arrays.fill(dist, Integer.MAX_VALUE); PriorityQueue<Integer> dis=new PriorityQueue<>(n+1, new Comparator<Integer>() { public int compare(Integer p,Integer q) { return dist[p]-dist[q]; } } ); boolean[] vis=new boolean[n+1]; Arrays.fill(vis, false); int s=1; dist[s]=0; dis.add(s); vis[s]=true; while(!dis.isEmpty()) { int p=dis.poll(); for(int i=0;i<gr[p].size();i++) { int y=gr[p].get(i).v; int w=gr[p].get(i).i; if(!vis[y]) { dist[y]=dist[p]+w; dis.add(y); vis[y]=true; } else { if(dist[p]+w<dist[y]) { dist[y]=dist[p]+w; } } } } return dist; } } public static class sieve{ public static ArrayList<Integer> sieves(int n) { ArrayList<Integer> arr=new ArrayList<>(); boolean[] bol=new boolean[n+1]; Arrays.fill(bol, true); //arr.add(1); for(int i=2;i<=n;i++) { if(bol[i]) { arr.add(i); for(int j=2;j*i<=n;j++) { bol[i*j]=false; } } } return arr; } } public static class isprime{ public static boolean check(int n) { if(n==2) return true; else if(n==3) return true; else if(n%2==0) return false; else if(n%3==0) return false; else { for(int i=6;;i+=6) { if(i>Math.sqrt(n)) break; if(n%(i-1)==0) { return false; } else if(n%(i+1)==0) return false; } return true; } } } private static class DSU{ int[] parent; int[] rank; int cnt; public DSU(int n){ parent=new int[n]; rank=new int[n]; for(int i=0;i<n;i++){ parent[i]=i; rank[i]=1; } cnt=n; } int find(int i){ while(parent[i] !=i){ parent[i]=parent[parent[i]]; i=parent[i]; } return i; } int Union(int x, int y){ int xset = find(x); int yset = find(y); if(xset!=yset) cnt--; if(rank[xset]<rank[yset]){ parent[xset] = yset; rank[yset]+=rank[xset]; rank[xset]=0; return yset; }else{ parent[yset]=xset; rank[xset]+=rank[yset]; rank[yset]=0; return xset; } } } private static class Pair implements Comparable<Pair>{ int v,i;Pair j; public Pair(int a,int b){ v=a; i=b; } public Pair(int a,Pair b) { v=a; j=b; } @Override public int compareTo(Pair arg0) { { return this.v-arg0.v; } } } private static class Pairl implements Comparable<Pairl>{ long v,i;Pairl j; public Pairl(long a,long b){ v=a; i=b; } public Pairl(long a,Pairl b) { v=a; j=b; } @Override public int compareTo(Pairl arg0) { { if(this.v>arg0.v) return 1; else return -1; } } } public static long f(long number,long m) { if (number <= 1) return 1; else return (number * f(number - 1,m))%m; } public static long mmi(long a, long m) { long m0 = m; long y = 0, x = 1; if (m == 1) return 0; while (a > 1) { // q is quotient long q = a / m; long t = m; // m is remainder now, process same as // Euclid's algo m = a % m; a = t; t = y; // Update y and x y = x - q * y; x = t; } // Make x positive if (x < 0) x += m0; return x; } public static class segtree{ static int[] tree=new int[10000000]; static int[] lazy=new int[10000000]; public static void initial() { Arrays.fill(lazy, 0); } public static void build(int[] arr,int node,int l,int r) { if(l==r) { tree[node]=arr[l]; } else { int m=(l+r)/2; build(arr,(2*node)+1,l,m); build(arr,(2*node)+2,m+1,r); tree[node]=tree[2*node+1]+tree[(2*node)+2]; } } public static void updater(int[] arr,int node,int l,int r,int s,int e,int val) { if(lazy[node]!=0) { tree[node]+=(r-l+1)*lazy[node]; if(l!=r) { lazy[2*node+1]+=lazy[node]; lazy[2*node+2]+=lazy[node]; } lazy[node]=0; } if(s<=l && e>=r) { tree[node]+=(r-l+1)*val; if(l!=r) { lazy[2*node+1]+=val; lazy[2*node+2]+=val; } } else if(!(e<l || r<s)) { int m=(l+r)/2; updater(arr,2*node+1,l,m,s,e,val); updater(arr,2*node+2,m+1,r,s,e,val); tree[node]=tree[2*node+1]+tree[2*node+2]; } } public static void update(int[] arr,int node,int l,int r,int ind,int val) { if(l==r) { arr[ind]+=val; tree[node]+=val; } else { int m=(l+r)/2; if(l<=ind && ind<=m) { update(arr,(2*node+1),l,m,ind,val); } else { update(arr,(2*node+2),m+1,r,ind,val); } tree[node]=tree[2*node+1]+tree[2*node+2]; } } public static int query(int node,int l,int r,int s,int e) { if(lazy[node]!=0) { tree[node]+=(r-l+1)*lazy[node]; if(l!=r) { lazy[2*node+1]+=lazy[node]; lazy[2*node+2]+=lazy[node]; } lazy[node]=0; } if(e<l || r<s) return 0; if(s<=l && e>=r) return tree[node]; int m=(l+r)/2; int p1=query((2*node+1),l,m,s,e); int p2=query((2*node+2),m+1,r,s,e); return (p1+p2); } } private static long pow(long a, long b, long c) { if (b == 0) return 1; long p = pow(a, b / 2, c); p = (p * p) % c; return (b % 2 == 0) ? p : (a * p) % c; } private static long gcd(long n, long l) { if (l == 0) return n; return gcd(l, n % l); } private static int gcd(int n, int l) { if (l == 0) return n; return gcd(l, n % l); } private static long max(long a, long b) { if (a > b) return a; return b; } private static long min(long a, long b) { if (a < b) return a; return b; } public static void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int [n1]; int R[] = new int [n2]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } public static void sort(int arr[]) { sort(arr,0,arr.length-1); } public static void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } public static void main(String[] args) throws Exception { new Thread(null,new Runnable(){ @Override public void run() { /* try { InputReader(new FileInputStream("input.txt")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ InputReader(System.in); pw = new PrintWriter(System.out); /*try { pw=new PrintWriter(new FileOutputStream("output.txt")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ soln(); pw.close(); } },"1",1<<26).start(); } public static void InputReader(InputStream stream1) { stream = stream1; } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private static boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } private static 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++]; } private static int ni() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private static long nl() { 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; } private static double nd() { double ret = 0, div = 1; int c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private static String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private static String nli() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } private static int[] nia(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } private static long[] nla(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nl(); } return arr; } private static void pa(int[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static void pa(long[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } private static char nc() { int c = read(); while (isSpaceChar(c)) c = read(); char c1=(char)c; while(!isSpaceChar(c)) c=read(); return c1; } public String ns() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["10 4\n9 14 28 1 7 13 15 29 2 31", "7 3\n3 14 15 92 65 35 89"]
1 second
["24", "64"]
NoteIn the first example you can split the books as follows:$$$$$$(9 + 14 + 28 + 1 + 7) \&amp; (13 + 15) \&amp; (29 + 2) \&amp; (31) = 24.$$$$$$In the second example you can split the books as follows:$$$$$$(3 + 14 + 15 + 92) \&amp; (65) \&amp; (35 + 89) = 64.$$$$$$
Java 8
standard input
[ "dp", "bitmasks", "greedy" ]
9862db32dfd8eab8714d17aaaa338acd
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 50$$$) — the number of books and the number of shelves in the new office. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$, ($$$0 &lt; a_i &lt; 2^{50}$$$) — the prices of the books in the order they stand on the old shelf.
1,900
Print the maximum possible beauty of $$$k$$$ shelves in the new office.
standard output
PASSED
b820e2b122789cdacfadfffc26cb575c
train_003.jsonl
1527432600
Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly $$$k$$$ bookshelves. He decided that the beauty of the $$$k$$$ shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $$$k$$$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
256 megabytes
/** * Created by Baelish on 5/27/2018. */ import java.io.*; import java.util.*; import static java.lang.Math.*; public class D_3 { public static void main(String[] args)throws Exception { FastReader in = new FastReader(System.in); PrintWriter pw = new PrintWriter(System.out); n = in.nextInt(); k = in.nextInt(); arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextLong(); } long max = 0; for(int x = 55; x >= 0; x--){ bit[x] = 1; ++tc; long tmp = solve(0, k); if(tmp > 0){ max = max(max, tmp); } else bit[x] = 0; } pw.println(max); pw.close(); } static long arr[], dp[][] = new long[60][60], inf = (1l<<56)-1; static int n, k, tc, bit[] = new int[60], vis[][] = new int[60][60]; static long solve(int pos, int rem){ if(pos >= n){ return rem == 0 ? inf : 0; } if(rem <= 0) return 0; if(vis[pos][rem] == tc) return dp[pos][rem]; vis[pos][rem] = tc; long sum = 0, max = 0; for (int i = pos; i < n; i++) { sum += arr[i]; boolean ok = true; for(int x = 55; ok && x >= 0; x--){ if(bit[x] == 1) ok &= check(sum, x); } if(ok) max = max(max, sum & solve(i+1, rem-1)); } return dp[pos][rem] = max; } static boolean check(long N,long pos){return (N & (1l<<pos)) != 0;} static void debug(Object...obj) { System.err.println(Arrays.deepToString(obj)); } static class FastReader { InputStream is; private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; static final int ints[] = new int[128]; public FastReader(InputStream is){ for(int i='0';i<='9';i++) ints[i]=i-'0'; this.is = is; } public int readByte(){ if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } public boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } public int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } public String next(){ int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt(){ int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = (num<<3) + (num<<1) + ints[b]; }else{ return minus ? -num : num; } b = readByte(); } } public long nextLong() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = (num<<3) + (num<<1) + ints[b]; }else{ return minus ? -num : num; } b = readByte(); } } public double nextDouble() { return Double.parseDouble(next()); } /* public char nextChar() { return (char)skip(); }*/ public char[] next(int n){ char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } /*private char buff[] = new char[1005]; public char[] nextCharArray(){ int b = skip(), p = 0; while(!(isSpaceChar(b))){ buff[p++] = (char)b; b = readByte(); } return Arrays.copyOf(buff, p); }*/ } }
Java
["10 4\n9 14 28 1 7 13 15 29 2 31", "7 3\n3 14 15 92 65 35 89"]
1 second
["24", "64"]
NoteIn the first example you can split the books as follows:$$$$$$(9 + 14 + 28 + 1 + 7) \&amp; (13 + 15) \&amp; (29 + 2) \&amp; (31) = 24.$$$$$$In the second example you can split the books as follows:$$$$$$(3 + 14 + 15 + 92) \&amp; (65) \&amp; (35 + 89) = 64.$$$$$$
Java 8
standard input
[ "dp", "bitmasks", "greedy" ]
9862db32dfd8eab8714d17aaaa338acd
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 50$$$) — the number of books and the number of shelves in the new office. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$, ($$$0 &lt; a_i &lt; 2^{50}$$$) — the prices of the books in the order they stand on the old shelf.
1,900
Print the maximum possible beauty of $$$k$$$ shelves in the new office.
standard output
PASSED
8beede907baf1ee8a501e300d98731d5
train_003.jsonl
1527432600
Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly $$$k$$$ bookshelves. He decided that the beauty of the $$$k$$$ shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $$$k$$$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
256 megabytes
import java.util.Scanner; public class BOOKSHELVES { public static void main(String args[]) throws Exception { long[] a ; Scanner sc= new Scanner(System.in); int n=sc.nextInt(); int parts=sc.nextInt(); a=new long[n+1]; for(int i=1;i<=n;i++) { a[i]=sc.nextLong(); } long res=0; int count=0; for(long bit=60;bit>=0;bit--) { count++; boolean[][] dp=new boolean[n+1][parts+1]; dp[0][0]=true; for(int i=1;i<=n;i++) { for(int j=1;j<=parts;j++) { long set=res+(1L<<bit); long sum=0; //System.out.println(set); for(int k=i;k>=1;k--) { sum+=a[k]; if(dp[k-1][j-1] && (sum&set)==set) { dp[i][j]=true; } } } } if(dp[n][parts]) { //System.out.println(bit+" "+count); res+=(1L<<bit); } } System.out.println(res); } }
Java
["10 4\n9 14 28 1 7 13 15 29 2 31", "7 3\n3 14 15 92 65 35 89"]
1 second
["24", "64"]
NoteIn the first example you can split the books as follows:$$$$$$(9 + 14 + 28 + 1 + 7) \&amp; (13 + 15) \&amp; (29 + 2) \&amp; (31) = 24.$$$$$$In the second example you can split the books as follows:$$$$$$(3 + 14 + 15 + 92) \&amp; (65) \&amp; (35 + 89) = 64.$$$$$$
Java 8
standard input
[ "dp", "bitmasks", "greedy" ]
9862db32dfd8eab8714d17aaaa338acd
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 50$$$) — the number of books and the number of shelves in the new office. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$, ($$$0 &lt; a_i &lt; 2^{50}$$$) — the prices of the books in the order they stand on the old shelf.
1,900
Print the maximum possible beauty of $$$k$$$ shelves in the new office.
standard output
PASSED
4a93188a275d24ce6699934463437705
train_003.jsonl
1527432600
Mr Keks is a typical white-collar in Byteland.He has a bookshelf in his office with some books on it, each book has an integer positive price.Mr Keks defines the value of a shelf as the sum of books prices on it. Miraculously, Mr Keks was promoted and now he is moving into a new office.He learned that in the new office he will have not a single bookshelf, but exactly $$$k$$$ bookshelves. He decided that the beauty of the $$$k$$$ shelves is the bitwise AND of the values of all the shelves.He also decided that he won't spend time on reordering the books, so he will place several first books on the first shelf, several next books on the next shelf and so on. Of course, he will place at least one book on each shelf. This way he will put all his books on $$$k$$$ shelves in such a way that the beauty of the shelves is as large as possible. Compute this maximum possible beauty.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class AvitoD { static Map<Integer, Long> get_sum = new HashMap<Integer, Long>(); static long[] books; static int n; static int totalShelves; public static void main(String[] args) { FastScanner sc = new FastScanner(); StringBuilder sb = new StringBuilder(); n = sc.nextInt(); totalShelves = sc.nextInt(); books = sc.readLongArray(n); // right side is exclusive. lengths: for (int length = 1; length<= n; length++) { long sum = 0L; for (int i = 0; i < length; i++) { // sum up length things sum += books[i]; } for (int start = 0; start < n; start ++) { if (start + length > n) continue lengths; setSum(start, length, sum); /// SUM IS START, LENGTH if (start + length < n) { sum -= books[start]; sum += books[start + length]; } } } long ans = 0L; for (int maxBit = 63; maxBit >= 0; maxBit--) { if (works(ans | (1L<<maxBit), 0, 0)) { ans |= (1L<<maxBit); } } sb.append(ans); System.out.print(sb); } static class State { long a; int b, c; public State(long x, int y, int z) { a = x; b = y; c = z; } public int hashCode() { return (int) a + b * 123412 + c * 9875643; } @Override public boolean equals(Object other) { State o = (State) other; return a == o.a && b == o.b && c == o.c; } } static Map<State, Boolean> cache = new HashMap<State, Boolean>(); static boolean works(long x, int currShelf, int bookIndex) { // need to use all the books!!!!!!! State myState = new State(x, currShelf, bookIndex); if (cache.get(myState) != null) return cache.get(myState); boolean ans = false; if ((totalShelves - currShelf) > (n - bookIndex)) {// if we don't have enough books left } else if (currShelf == totalShelves-1) { // if we're at the last shelf, give all the remaining books to that shelf. ans = (x&getSum(bookIndex, n - bookIndex))==x; } else { for (int length = 1; length + bookIndex <= n; length++) { if ((x & getSum(bookIndex, length)) == x && works(x, currShelf + 1, bookIndex + length)) { ans = true; break; } } } cache.put(myState, ans); return ans; } static Long getSum(int l, int r) { return get_sum.get(l * 100 + r); } static void setSum(int l, int r, long sum) { get_sum.put(l*100+r, sum); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } }
Java
["10 4\n9 14 28 1 7 13 15 29 2 31", "7 3\n3 14 15 92 65 35 89"]
1 second
["24", "64"]
NoteIn the first example you can split the books as follows:$$$$$$(9 + 14 + 28 + 1 + 7) \&amp; (13 + 15) \&amp; (29 + 2) \&amp; (31) = 24.$$$$$$In the second example you can split the books as follows:$$$$$$(3 + 14 + 15 + 92) \&amp; (65) \&amp; (35 + 89) = 64.$$$$$$
Java 8
standard input
[ "dp", "bitmasks", "greedy" ]
9862db32dfd8eab8714d17aaaa338acd
The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq k \leq n \leq 50$$$) — the number of books and the number of shelves in the new office. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots a_n$$$, ($$$0 &lt; a_i &lt; 2^{50}$$$) — the prices of the books in the order they stand on the old shelf.
1,900
Print the maximum possible beauty of $$$k$$$ shelves in the new office.
standard output
PASSED
d33fcc081f169282d76c3012207df084
train_003.jsonl
1595601300
Note that the only difference between String Transformation 1 and String Transformation 2 is in the move Koa does. In this version the letter $$$y$$$ Koa selects must be strictly greater alphabetically than $$$x$$$ (read statement for better understanding). You can make hacks in these problems independently.Koa the Koala has two strings $$$A$$$ and $$$B$$$ of the same length $$$n$$$ ($$$|A|=|B|=n$$$) consisting of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t).In one move Koa: selects some subset of positions $$$p_1, p_2, \ldots, p_k$$$ ($$$k \ge 1; 1 \le p_i \le n; p_i \neq p_j$$$ if $$$i \neq j$$$) of $$$A$$$ such that $$$A_{p_1} = A_{p_2} = \ldots = A_{p_k} = x$$$ (ie. all letters on this positions are equal to some letter $$$x$$$). selects a letter $$$y$$$ (from the first $$$20$$$ lowercase letters in English alphabet) such that $$$y&gt;x$$$ (ie. letter $$$y$$$ is strictly greater alphabetically than $$$x$$$). sets each letter in positions $$$p_1, p_2, \ldots, p_k$$$ to letter $$$y$$$. More formally: for each $$$i$$$ ($$$1 \le i \le k$$$) Koa sets $$$A_{p_i} = y$$$. Note that you can only modify letters in string $$$A$$$.Koa wants to know the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or to determine that there is no way to make them equal. Help her!
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) { FastReader input=new FastReader(); PrintWriter out=new PrintWriter(System.out); int T=input.nextInt(); while(T-->0) { int n=input.nextInt(); String a=input.next(); String b=input.next(); int flag=0; ArrayList<Integer> adj[]=new ArrayList[20]; for(int i=0;i<20;i++) { adj[i]=new ArrayList<>(); } for(int i=0;i<n;i++) { if(b.charAt(i)<a.charAt(i)) { flag=1; } else { adj[(int)a.charAt(i)-97].add((int)b.charAt(i)-97); adj[(int)b.charAt(i)-97].add((int)a.charAt(i)-97); } } if(flag==1) { out.println(-1); } else { ArrayList<ArrayList<Integer>> list=connectedComponents(adj); int c=0; for(int i=0;i<list.size();i++) { c+=list.get(i).size()-1; } out.println(c); } } out.close(); } static void DFSUtil(int v, boolean[] visited,ArrayList<Integer> adj[],ArrayList<Integer> l) { visited[v] = true; l.add(v); for (int x : adj[v]) { if (!visited[x]) DFSUtil(x, visited,adj,l); } } static ArrayList<ArrayList<Integer>> connectedComponents(ArrayList<Integer> adj[]) { ArrayList<ArrayList<Integer>> list=new ArrayList<>(); boolean[] visited = new boolean[20]; for (int v = 0; v < 20; ++v) { if (!visited[v]) { ArrayList<Integer> l=new ArrayList<>(); DFSUtil(v, visited,adj,l); list.add(l); } } return list; } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["5\n3\naab\nbcc\n4\ncabc\nabcb\n3\nabc\ntsr\n4\naabd\ncccd\n5\nabcbd\nbcdda"]
1 second
["2\n-1\n3\n2\n-1"]
Note In the $$$1$$$-st test case Koa: selects positions $$$1$$$ and $$$2$$$ and sets $$$A_1 = A_2 = $$$ b ($$$\color{red}{aa}b \rightarrow \color{blue}{bb}b$$$). selects positions $$$2$$$ and $$$3$$$ and sets $$$A_2 = A_3 = $$$ c ($$$b\color{red}{bb} \rightarrow b\color{blue}{cc}$$$). In the $$$2$$$-nd test case Koa has no way to make string $$$A$$$ equal $$$B$$$. In the $$$3$$$-rd test case Koa: selects position $$$1$$$ and sets $$$A_1 = $$$ t ($$$\color{red}{a}bc \rightarrow \color{blue}{t}bc$$$). selects position $$$2$$$ and sets $$$A_2 = $$$ s ($$$t\color{red}{b}c \rightarrow t\color{blue}{s}c$$$). selects position $$$3$$$ and sets $$$A_3 = $$$ r ($$$ts\color{red}{c} \rightarrow ts\color{blue}{r}$$$).
Java 8
standard input
[ "greedy", "graphs", "two pointers", "dsu", "sortings", "trees", "strings" ]
7c6e8bc160a17dbc6d55c6dc40fe0988
Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$A$$$ and $$$B$$$. The second line of each test case contains string $$$A$$$ ($$$|A|=n$$$). The third line of each test case contains string $$$B$$$ ($$$|B|=n$$$). Both strings consists of the first $$$20$$$ lowercase English alphabet letters (ie. from a to t). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,700
For each test case: Print on a single line the smallest number of moves she has to do to make strings equal to each other ($$$A = B$$$) or $$$-1$$$ if there is no way to make them equal.
standard output
PASSED
47bd2e706b5df49b0a7c4b921ec27913
train_003.jsonl
1440261000
In this task you need to process a set of stock exchange orders and use them to create order book.An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price pi, direction di — buy or sell, and integer qi. This means that the participant is ready to buy or sell qi stocks at price pi for one stock. A value qi is also known as a volume of an order.All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders.An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book.You are given n stock exhange orders. Your task is to print order book of depth s for these orders.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); HashMap<Integer,Integer> mapB = new HashMap<>(); HashMap<Integer,Integer> mapS = new HashMap<>(); int n = sc.nextInt(); int s = sc.nextInt(); sc.nextLine(); for (int i = 0; i < n; i++) { String[] parsedString = sc.nextLine().split(" "); int value = Integer.parseInt(parsedString[1]); int count = Integer.parseInt(parsedString[2]); if(parsedString[0].equals("B")){ if(mapB.containsKey(value)){ mapB.replace(value,mapB.get(value) + count); } else{ mapB.put(value,count); } } else if(parsedString[0].equals("S")){ if(mapS.containsKey(value)){ mapS.replace(value,mapS.get(value) + count); } else{ mapS.put(value,count); } } } ArrayList<Integer> keysB = new ArrayList<>(mapB.keySet()); ArrayList<Integer> keysS = new ArrayList<>(mapS.keySet()); Collections.sort(keysB); Collections.sort(keysS); if(keysS.size() != 0) { for (int i = Math.min(s - 1, keysS.size() - 1); i >= 0; i--) { System.out.println("S " + keysS.get(i) + " " + mapS.get(keysS.get(i))); } } if(keysB.size() != 0) { for (int i = 0; i < Math.min(s,keysB.size()) ; i++) { System.out.println("B " + keysB.get(keysB.size() - i - 1) + " " + mapB.get(keysB.get(keysB.size() - i - 1))); } } } }
Java
["6 2\nB 10 3\nS 50 2\nS 40 1\nS 50 6\nB 20 4\nB 25 10"]
2 seconds
["S 50 8\nS 40 1\nB 25 10\nB 20 4"]
NoteDenote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two sell orders (50, 8), (40, 1) in the sample.You need to print no more than two best orders for each direction, so you shouldn't print the order (10 3) having the worst price among buy orders.
Java 11
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
267c04c77f97bbdf7697dc88c7bfa4af
The input starts with two positive integers n and s (1 ≤ n ≤ 1000, 1 ≤ s ≤ 50), the number of orders and the book depth. Next n lines contains a letter di (either 'B' or 'S'), an integer pi (0 ≤ pi ≤ 105) and an integer qi (1 ≤ qi ≤ 104) — direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order.
1,300
Print no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input.
standard output
PASSED
633f7acb12fa164165f97a3f49a24797
train_003.jsonl
1440261000
In this task you need to process a set of stock exchange orders and use them to create order book.An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price pi, direction di — buy or sell, and integer qi. This means that the participant is ready to buy or sell qi stocks at price pi for one stock. A value qi is also known as a volume of an order.All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders.An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book.You are given n stock exhange orders. Your task is to print order book of depth s for these orders.
256 megabytes
import java.io.*; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.StringTokenizer; public class B { public static void main(String[] args) { HashMap<Long, Long> buy = new HashMap<>(); HashMap<Long, Long> sell = new HashMap<>(); int n = io.nextInt(), d = io.nextInt(); final long l = 0; for (int i = 0; i < n; i++) { char direction = io.next().charAt(0); long price = io.nextInt(), quantity = io.nextInt(); if (direction == 'B') buy.put(price, buy.getOrDefault(price, l) + quantity); else sell.put(price, sell.getOrDefault(price, l) + quantity); } Long[] skeys = sell.keySet().toArray(new Long[0]); Long[] bkeys = buy.keySet().toArray(new Long[0]); Arrays.sort(skeys, Comparator.reverseOrder()); Arrays.sort(bkeys, Comparator.reverseOrder()); for (int i = Math.max(skeys.length - d, 0); i < skeys.length; i++) io.printf("S %d %d\n", skeys[i], sell.get(skeys[i])); for (int i = 0; i < Math.min(bkeys.length, d); i++) io.printf("B %d %d\n", bkeys[i], buy.get(bkeys[i])); io.flush(); io.close(); } static FastIO io = new FastIO(System.in); static class FastIO extends PrintWriter { private BufferedReader br; private StringTokenizer tk; private FileReader fr; FastIO(InputStream in) { this(); br = new BufferedReader(new InputStreamReader(in)); } FastIO(String location) { this(); try {br = new BufferedReader(new FileReader(location));} catch (IOException e) {println(e); flush();} } private FastIO() { super(System.out); tk = new StringTokenizer(""); } String nextLine() { try { return br.readLine(); } catch (IOException ignored) { } return nextLine(); } String next() { if (hasNext()) return tk.nextToken(); else tk = new StringTokenizer(nextLine()); return next(); } boolean hasNext() { return tk.hasMoreTokens(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } int[] nextIntArray(int length) { int[] array = new int[length]; for (int i = 0; i < array.length; i++) { array[i] = nextInt(); } return array; } void exit() { try { super.close(); br.close(); } catch (IOException ignored) { } } } }
Java
["6 2\nB 10 3\nS 50 2\nS 40 1\nS 50 6\nB 20 4\nB 25 10"]
2 seconds
["S 50 8\nS 40 1\nB 25 10\nB 20 4"]
NoteDenote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two sell orders (50, 8), (40, 1) in the sample.You need to print no more than two best orders for each direction, so you shouldn't print the order (10 3) having the worst price among buy orders.
Java 11
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
267c04c77f97bbdf7697dc88c7bfa4af
The input starts with two positive integers n and s (1 ≤ n ≤ 1000, 1 ≤ s ≤ 50), the number of orders and the book depth. Next n lines contains a letter di (either 'B' or 'S'), an integer pi (0 ≤ pi ≤ 105) and an integer qi (1 ≤ qi ≤ 104) — direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order.
1,300
Print no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input.
standard output
PASSED
76f3c1caeb91975ed56e1325d5adc285
train_003.jsonl
1440261000
In this task you need to process a set of stock exchange orders and use them to create order book.An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price pi, direction di — buy or sell, and integer qi. This means that the participant is ready to buy or sell qi stocks at price pi for one stock. A value qi is also known as a volume of an order.All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders.An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book.You are given n stock exhange orders. Your task is to print order book of depth s for these orders.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class r3p1 { public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); int a = sc.nextInt(); int[] s = new int[100002]; int[] b = new int[100002]; for (int i = 0; i < n; i++) { String str = sc.next(); int x = sc.nextInt(); int y = sc.nextInt(); if (str.equals("S")) { s[x] += y; } else { b[x] += y; } } int l = a; ArrayList<Integer> ans = new ArrayList<>(); for (int i = 0; i <= 100000 && a > 0; i++) { if (s[i] > 0) { ans.add(i); a--; } } Collections.reverse(ans); for (Integer i : ans) { System.out.println("S " + i + " " + s[i]); } a = l; for (int i = 100000; i >= 0 && a > 0; i--) { if (b[i] > 0) { System.out.println("B " + i + " " + b[i]); a--; } } pw.close(); } static class FastScanner { private boolean finished = false; private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastScanner(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 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 String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') { buf.appendCodePoint(c); } c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) { s = readLine0(); } return s; } public String readLine(boolean ignoreEmptyLines) { if (ignoreEmptyLines) { return readLine(); } else { return readLine0(); } } public BigInteger readBigInteger() { try { return new BigInteger(nextString()); } catch (NumberFormatException e) { throw new InputMismatchException(); } } public char nextCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } 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 isExhausted() { int value; while (isSpaceChar(value = peek()) && value != -1) { read(); } return value == -1; } public String next() { return nextString(); } public SpaceCharFilter getFilter() { return filter; } public void setFilter(SpaceCharFilter filter) { this.filter = filter; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public int[] nextIntArray(int n){ int[] array=new int[n]; for(int i=0;i<n;++i)array[i]=nextInt(); return array; } public int[] nextSortedIntArray(int n){ int array[]=nextIntArray(n); PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); for(int i = 0; i < n; i++){ pq.add(array[i]); } int[] out = new int[n]; for(int i = 0; i < n; i++){ out[i] = pq.poll(); } return out; } public int[] nextSumIntArray(int n){ int[] array=new int[n]; array[0]=nextInt(); for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt(); return array; } public ArrayList<Integer>[] nextGraph(int n, int m){ ArrayList<Integer>[] adj = new ArrayList[n]; for(int i = 0; i < n; i++){ adj[i] = new ArrayList<Integer>(); } for(int i = 0; i < m; i++){ int u = nextInt(); int v = nextInt(); u--; v--; adj[u].add(v); adj[v].add(u); } return adj; } public ArrayList<Integer>[] nextTree(int n){ return nextGraph(n, n-1); } public long[] nextLongArray(int n){ long[] array=new long[n]; for(int i=0;i<n;++i)array[i]=nextLong(); return array; } public long[] nextSumLongArray(int n){ long[] array=new long[n]; array[0]=nextInt(); for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt(); return array; } public long[] nextSortedLongArray(int n){ long array[]=nextLongArray(n); Arrays.sort(array); return array; } } static void shuffle(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffle(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } }
Java
["6 2\nB 10 3\nS 50 2\nS 40 1\nS 50 6\nB 20 4\nB 25 10"]
2 seconds
["S 50 8\nS 40 1\nB 25 10\nB 20 4"]
NoteDenote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two sell orders (50, 8), (40, 1) in the sample.You need to print no more than two best orders for each direction, so you shouldn't print the order (10 3) having the worst price among buy orders.
Java 11
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
267c04c77f97bbdf7697dc88c7bfa4af
The input starts with two positive integers n and s (1 ≤ n ≤ 1000, 1 ≤ s ≤ 50), the number of orders and the book depth. Next n lines contains a letter di (either 'B' or 'S'), an integer pi (0 ≤ pi ≤ 105) and an integer qi (1 ≤ qi ≤ 104) — direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order.
1,300
Print no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input.
standard output
PASSED
31d12ee79c2137bb74b7990b06853f68
train_003.jsonl
1440261000
In this task you need to process a set of stock exchange orders and use them to create order book.An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price pi, direction di — buy or sell, and integer qi. This means that the participant is ready to buy or sell qi stocks at price pi for one stock. A value qi is also known as a volume of an order.All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders.An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book.You are given n stock exhange orders. Your task is to print order book of depth s for these orders.
256 megabytes
import java.util.ArrayDeque; import java.util.Scanner; import java.util.TreeMap; public class Main { public static void main(String[] args) throws Exception{ OrderBook res = new OrderBook(); res.resolve(); } static class OrderBook { public void resolve () { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int size = scan.nextInt(); TreeMap<Integer, Integer> buy = new TreeMap<>(); TreeMap<Integer, Integer> sell = new TreeMap<>(); for (int i = 0; i < n; i++) { char d = scan.next().charAt(0); int p = scan.nextInt(); int q = scan.nextInt(); TreeMap<Integer, Integer> T = (d == 'B') ? buy : sell; Integer value = T.get(p); value = (value == null) ? 0 : value; T.put(p, value + q); } StringBuilder sb = new StringBuilder(); ArrayDeque<String> Q = new ArrayDeque<>(); sell.entrySet().stream().limit(size).forEach(s -> Q.addFirst(String.format("S %d %d\n", s.getKey(), s.getValue()))); Q.forEach(s -> sb.append(s)); buy.descendingMap().entrySet().stream().limit(size).forEach(s -> sb.append(String.format("B %d %d\n", s.getKey(), s.getValue()))); System.out.println(sb); } } }
Java
["6 2\nB 10 3\nS 50 2\nS 40 1\nS 50 6\nB 20 4\nB 25 10"]
2 seconds
["S 50 8\nS 40 1\nB 25 10\nB 20 4"]
NoteDenote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two sell orders (50, 8), (40, 1) in the sample.You need to print no more than two best orders for each direction, so you shouldn't print the order (10 3) having the worst price among buy orders.
Java 11
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
267c04c77f97bbdf7697dc88c7bfa4af
The input starts with two positive integers n and s (1 ≤ n ≤ 1000, 1 ≤ s ≤ 50), the number of orders and the book depth. Next n lines contains a letter di (either 'B' or 'S'), an integer pi (0 ≤ pi ≤ 105) and an integer qi (1 ≤ qi ≤ 104) — direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order.
1,300
Print no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input.
standard output
PASSED
8232b9739dc2b80b2516f0f71a3202ad
train_003.jsonl
1440261000
In this task you need to process a set of stock exchange orders and use them to create order book.An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price pi, direction di — buy or sell, and integer qi. This means that the participant is ready to buy or sell qi stocks at price pi for one stock. A value qi is also known as a volume of an order.All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders.An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book.You are given n stock exhange orders. Your task is to print order book of depth s for these orders.
256 megabytes
import javafx.util.Pair; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int glubina = in.nextInt(); ArrayList<Pair<Integer, Integer>> buys = new ArrayList<>(); ArrayList<Pair<Integer, Integer>> sells = new ArrayList<>(); in.nextLine(); int idx = 0; for (int i = 0; i < n; i++) { String s = in.nextLine(); int key = Integer.parseInt(s.split(" ")[1].trim()); int value = Integer.parseInt(s.split(" ")[2].trim()); if (s.trim().toLowerCase().charAt(0) == 'b') { if ((idx = contain(buys, key)) > -1) { Pair add = new Pair(buys.get(idx).getKey(), buys.get(idx).getValue() + value); buys.set(idx, add); } else { buys.add(new Pair<>(key, value)); } } else { if ((idx = contain(sells, key)) > -1) { Pair add = new Pair(sells.get(idx).getKey(), sells.get(idx).getValue() + value); sells.set(idx, add); } else { sells.add(new Pair<>(key, value)); } } } Collections.sort(buys, (o1, o2) -> o2.getKey() - o1.getKey()); Collections.sort(sells, (o1, o2) -> o1.getKey() - o2.getKey()); if (sells.size() < glubina) { for (int i = sells.size() - 1; i >= 0; i--) { System.out.println("S " + sells.get(i).getKey() + " " + sells.get(i).getValue()); } } else { for (int i = glubina - 1; i >= 0; i--) { System.out.println("S " + sells.get(i).getKey() + " " + sells.get(i).getValue()); } } if (buys.size() < glubina) { for (Pair<Integer, Integer> buy : buys) { System.out.println("B " + buy.getKey() + " " + buy.getValue()); } } else { for (int i = 0; i < glubina; i++) { System.out.println("B " + buys.get(i).getKey() + " " + buys.get(i).getValue()); } } } public static int contain(ArrayList<Pair<Integer, Integer>> arr, Integer el){ for(int i = 0; i < arr.size(); i++){ if(arr.get(i).getKey().equals(el)) return i; } return -1; } }
Java
["6 2\nB 10 3\nS 50 2\nS 40 1\nS 50 6\nB 20 4\nB 25 10"]
2 seconds
["S 50 8\nS 40 1\nB 25 10\nB 20 4"]
NoteDenote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two sell orders (50, 8), (40, 1) in the sample.You need to print no more than two best orders for each direction, so you shouldn't print the order (10 3) having the worst price among buy orders.
Java 11
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
267c04c77f97bbdf7697dc88c7bfa4af
The input starts with two positive integers n and s (1 ≤ n ≤ 1000, 1 ≤ s ≤ 50), the number of orders and the book depth. Next n lines contains a letter di (either 'B' or 'S'), an integer pi (0 ≤ pi ≤ 105) and an integer qi (1 ≤ qi ≤ 104) — direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order.
1,300
Print no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input.
standard output
PASSED
69e0ba218e8e48a2fc0a41a9fc75f705
train_003.jsonl
1440261000
In this task you need to process a set of stock exchange orders and use them to create order book.An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price pi, direction di — buy or sell, and integer qi. This means that the participant is ready to buy or sell qi stocks at price pi for one stock. A value qi is also known as a volume of an order.All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders.An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book.You are given n stock exhange orders. Your task is to print order book of depth s for these orders.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class OrderBook { public static void r(int arr[],int l,int m,int r) { int n1=m-l+1; int n2=r-m; int L[]=new int[n1]; int R[]=new int[n2]; for(int i=0;i<n1;i++) { L[i]=arr[l+i]; } for(int j=0;j<n2;j++) { R[j]=arr[m+1+j]; } int i=0; int j=0; int k=l; while(i<n1 && j<n2) { if(L[i]<=R[j]) { arr[k]=L[i]; ++i; } else{ arr[k]=R[j]; ++j; } ++k; } while(i<n1) { arr[k]=L[i]; ++i; ++k; } while(j<n2) { arr[k]=R[j]; ++j; ++k; } } public static void r2(int arr[],int l,int r) { if(l<r) { int m=(l+r)/2; r2(arr,l,m); r2(arr,m+1,r); r(arr,l,m,r); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } public static void main(String args[]) throws Exception { // try { // // FileOutputStream output=new FileOutputStream("C:\\Users\\icons\\Desktop\\java\\output.txt"); // // PrintStream out=new PrintStream(output); // // Diverting the output stream into file "temp.out".Comment the below line to use console // // System.setOut(out); // InputStream input=new FileInputStream("C:\\Users\\icons\\Desktop\\java\\input.txt"); // //Diverting the input stream into file "temp.in".Comment the below line to use console // System.setIn(input); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } FastReader sc = new FastReader(); Scanner input = new Scanner(System.in); int numberOfOrders = input.nextInt(); int bookDepth = input.nextInt(); input.nextLine(); String[] ordersDirection = new String[numberOfOrders]; int[] priceArray = new int[numberOfOrders]; int[] volumeArray = new int[numberOfOrders]; for(int a = 0; a < numberOfOrders; a++){ ordersDirection[a] = input.next(); priceArray[a] = input.nextInt(); volumeArray[a] = input.nextInt(); input.nextLine(); } // make the book int[] buyArray = new int[100002]; int[] sellArray = new int[100002]; for(int a = 0; a < numberOfOrders; a++){ if(ordersDirection[a].charAt(0) == 'B'){ buyArray[priceArray[a]] += volumeArray[a]; } else{ sellArray[priceArray[a]] += volumeArray[a]; } } //we have a complete book; now to print //print sales int countS = 0; int indexS = 0; int tempIndexS = -1; while(countS < bookDepth && indexS <= 100001){ if(sellArray[indexS] != 0){ countS++; } indexS++; } if(indexS != 0){ indexS--; } //we found the lowest one to print. while(indexS >= 0){ if(sellArray[indexS] != 0){ System.out.println("S " + indexS + " " + sellArray[indexS]); } indexS--; } //print buys int count = 0; int index = 100001; int tempIndex = -1; while(count < bookDepth && index >= 0){ if(buyArray[index] != 0){ count++; } index--; } if(index != 100001){ index++; } tempIndex = index; index = 100001; //we found the lowest one to print. while(tempIndex <= index){ if(buyArray[index] != 0){ System.out.println("B " + index + " " + buyArray[index]); } index--; } } }
Java
["6 2\nB 10 3\nS 50 2\nS 40 1\nS 50 6\nB 20 4\nB 25 10"]
2 seconds
["S 50 8\nS 40 1\nB 25 10\nB 20 4"]
NoteDenote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two sell orders (50, 8), (40, 1) in the sample.You need to print no more than two best orders for each direction, so you shouldn't print the order (10 3) having the worst price among buy orders.
Java 11
standard input
[ "data structures", "implementation", "sortings", "greedy" ]
267c04c77f97bbdf7697dc88c7bfa4af
The input starts with two positive integers n and s (1 ≤ n ≤ 1000, 1 ≤ s ≤ 50), the number of orders and the book depth. Next n lines contains a letter di (either 'B' or 'S'), an integer pi (0 ≤ pi ≤ 105) and an integer qi (1 ≤ qi ≤ 104) — direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order.
1,300
Print no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input.
standard output
PASSED
818c3c295792552750d22b956fe3be4d
train_003.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
// Main Code at the Bottom import java.util.*; import java.lang.*; import java.io.*; import java.math.BigInteger; public class Main { //Fast IO class static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { boolean env=System.getProperty("ONLINE_JUDGE") != null; if(!env) { try { br=new BufferedReader(new FileReader("src\\input.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } } else br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static long MOD=1000000000+7; //debug static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } // Pair static class pair{ long x,y; pair(long a,long b){ this.x=a; this.y=b; } public boolean equals(Object obj) { if(obj == null || obj.getClass()!= this.getClass()) return false; pair p = (pair) obj; return (this.x==p.x && this.y==p.y); } public int hashCode() { return Objects.hash(x,y); } } static FastReader sc=new FastReader(); static PrintWriter out=new PrintWriter(System.out); //Main function(The main code starts from here) public static void main (String[] args) throws java.lang.Exception { int test=1; //test=sc.nextInt(); while(test-->0){ int n=sc.nextInt(),p=sc.nextInt(); char s[]=sc.nextLine().toCharArray(); char ans[]=new char[n]; int ok=0; for(int i=n-1;i>=0;i--) { for(int j=s[i]-'a'+1;j<p;j++) { char tmp[]=Arrays.copyOf(s, n); if(i-1>=0 && j==s[i-1]-'a') continue; if(i-2>=0 && j==s[i-2]-'a') continue; int flag=0; tmp[i]=(char)(j+'a'); for(int k=i+1;k<n;k++) { int f=0; for(int pos=0;pos<p;pos++) { if(pos==tmp[k-1]-'a') continue; if(k-2>=0 && pos==tmp[k-2]-'a') continue; f=1; tmp[k]=(char)(pos+'a'); break; } if(f==0) { flag=1; break; } } if(flag==0) { ans=tmp; ok=1; break; } } if(ok==1) break; } if(ok==0) out.println("NO"); else { for(char c: ans) out.print(c); } } out.flush(); out.close(); } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 11
standard input
[ "brute force" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≤ n ≤ 1000; 1 ≤ p ≤ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
9855015c0c670e630e9254cc7bca3f9f
train_003.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.util.*; import java.io.*; public class NotoPalindromes { // https://codeforces.com/contest/465/problem/C public static void main(String[] args) throws IOException, FileNotFoundException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader in = new BufferedReader(new FileReader("NotoPalindromes")); StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); int p = Integer.parseInt(st.nextToken()); char[] s = in.readLine().toCharArray(); if (n == 1) { if (p == 1) { System.out.println("NO"); return; } else { s[0] = (char)(s[s.length-1] +1); if (s[0] - 'a' + 1 > p) { System.out.println("NO"); return; } else { System.out.print(s[0]); return; } } } int pointer=s.length-1; s[s.length-1] = (char)(s[s.length-1] +1); while (s[pointer] - 'a' + 1 > p) { s[pointer] = 'a'; pointer--; if (pointer>=0) { s[pointer] = (char)(s[pointer] +1); } else { System.out.println("NO"); return; } } pointer=1; while (palindromic(s) && !allmax(s, p)) { outerloop: for (int i=pointer; i<s.length; i++) { if (i <= 0) continue; while ( (i == 1 && s[i] == s[i-1]) || (i >=2 && (s[i] == s[i-1] || s[i] == s[i-2]))) { s[i] = (char)(s[i] +1); while (s[i] - 'a' + 1 > p) { s[i] = 'a'; i--; if (i>=0) { s[i] = (char)(s[i] +1); pointer= i; } else { System.out.println("NO"); return; } } } pointer = i; } } if (palindromic(s) || allmax(s, p)) { System.out.println("NO"); } else { for (int i=0; i<s.length; i++) { System.out.print(s[i]); } } } public static boolean allmax(char[] s, int p) { boolean found=false; for (int i=0; i<s.length; i++) { if (s[i] -'a' + 1 <= p ) found= true; if (s[i] -'a' + 1 > p ) return true; } return !found; } public static boolean palindromic(char[] s) { if (s[1] == s[0]) return true; for (int i=2; i<s.length; i++) { if (s[i] == s[i-1] || s[i] == s[i-2]) return true; } return false; } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 11
standard input
[ "brute force" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≤ n ≤ 1000; 1 ≤ p ≤ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
fafc6e2ea72d41d5e2bb22b4e61c906e
train_003.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
256 megabytes
import java.util.Scanner; public class Main { static int arr[][], dp[][], N, K, p; static long s[][]; public static void main(String[] args) { Scanner input = new Scanner(System.in); int n = input.nextInt(); p = input.nextInt() - 1 + 'a'; input.nextLine(); String str = input.nextLine(); StringBuilder s = new StringBuilder(str); if(n==1 && s.charAt(0) == p) { System.out.println("NO"); return; } int i = s.length()-1; boolean back = true; while (i != s.length() && i!= -1) { if(back) { if (s.charAt(i) < p) s.setCharAt(i, (char) (s.charAt(i) + 1)); else { s.setCharAt(i, 'a'); i--; continue; } } if ( i!=0 && s.charAt(i) == s.charAt(i - 1) || i >= 2 && s.charAt(i) == s.charAt(i - 2)) { back = true; continue; }else { i++; back = false; } } if(i==-1) System.out.println("NO"); else System.out.println(s); } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 11
standard input
[ "brute force" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≤ n ≤ 1000; 1 ≤ p ≤ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
70726987d1c9f2cee2b411de854e4e30
train_003.jsonl
1410103800
Paul hates palindromes. He assumes that string s is tolerable if each its character is one of the first p letters of the English alphabet and s doesn't contain any palindrome contiguous substring of length 2 or more.Paul has found a tolerable string s of length n. Help him find the lexicographically next tolerable string of the same length or else state that such string does not exist.
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.Random; import java.util.StringTokenizer; public class Contest { static PrintWriter out = new PrintWriter(System.out); static final Random random = new Random(); public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int p = sc.nextInt(); char[] a = sc.next().toCharArray(); char[] b; boolean res = false; for(int i = n - 1;i >= 0;i--) { if(res) break; for(char candidate = (char)(a[i]+1); candidate < (char)('a'+p); candidate++) { if(!check(a, n, i, candidate)) continue; b = new char[a.length]; System.arraycopy(a, 0, b, 0, a.length); b[i] = candidate; boolean pos = true; for(int j = i + 1;j < n;j++) { boolean found = false; for(char replace = 'a';replace <= 'z';replace++) { if(!check(b, n, j, replace)) continue; b[j] = replace; found = true; break; } if(!found) { pos = false; break; } } if(pos) { for(char x : b) System.out.print(x); System.out.println(); res = true; break; } } } if(!res) System.out.println("NO"); out.flush(); } static boolean check(char[] a, int n, int i, char candidate) { if (i - 1 >= 0 && candidate == a[i - 1]) return false; // if (i + 1 < n && candidate == a[i + 1]) // return false; if (i - 2 >= 0 && candidate == a[i - 2]) return false; // if (i + 2 < n && candidate == a[i + 2]) // return false; return true; } static void ruffleSort(int[] a) { int n = a.length;// shuffle, then sort for (int i = 0; i < n; i++) { int oi = random.nextInt(n), temp = a[oi]; a[oi] = a[i]; a[i] = temp; } java.util.Arrays.sort(a); } private static class Scanner { public BufferedReader reader; public StringTokenizer st; public Scanner(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { String line = reader.readLine(); if (line == null) return null; st = new StringTokenizer(line); } catch (Exception e) { throw (new RuntimeException()); } } 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() throws IOException { return reader.readLine(); } } }
Java
["3 3\ncba", "3 4\ncba", "4 4\nabcd"]
1 second
["NO", "cbd", "abda"]
NoteString s is lexicographically larger (or simply larger) than string t with the same length, if there is number i, such that s1 = t1, ..., si = ti, si + 1 &gt; ti + 1.The lexicographically next tolerable string is the lexicographically minimum tolerable string which is larger than the given one.A palindrome is a string that reads the same forward or reversed.
Java 11
standard input
[ "brute force" ]
788ae500235ca7b7a7cd320f745d1070
The first line contains two space-separated integers: n and p (1 ≤ n ≤ 1000; 1 ≤ p ≤ 26). The second line contains string s, consisting of n small English letters. It is guaranteed that the string is tolerable (according to the above definition).
1,700
If the lexicographically next tolerable string of the same length exists, print it. Otherwise, print "NO" (without the quotes).
standard output
PASSED
65c80c0ae031e15604fa9e024d129a8a
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.InputMismatchException; public class B { Scanner sc = new Scanner(System.in); void doIt() { int ans = -1; int N = sc.nextInt(); int [] a = new int[N]; for(int i = 0; i < N; i++) a[i] = sc.nextInt(); int down_cnt = 0; int down_pos = 0; for(int i = 0; i < N; i++) { if(a[i] > a[(i+1)%N]) { down_cnt++; down_pos = (i + 1) % N; } } if(down_cnt <= 1) { ans = (N - down_pos) % N; } System.out.println(ans); } public static void main(String[] args) { // TODO Auto-generated method stub new B().doIt(); } // thanks to wata class Scanner { InputStream in; byte[] buf = new byte[1 << 10]; int p, m; boolean[] isSpace = new boolean[128]; Scanner(InputStream in) { this.in = in; isSpace[' '] = isSpace['\n'] = isSpace['\r'] = isSpace['\t'] = true; } int read() { if (m == -1) return -1; if (p >= m) { p = 0; try { m = in.read(buf); } catch (IOException e) { throw new RuntimeException(e); } if (m <= 0) return -1; } return buf[p++]; } boolean hasNext() { int c = read(); while (c >= 0 && isSpace[c]) c = read(); if (c == -1) return false; p--; return true; } int nextInt() { if (!hasNext()) throw new InputMismatchException(); int 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 (c >= 0 && !isSpace[c]); return res * sgn; } } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
7149f700afb4d44fb00549541ff88503
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] a = new int[n]; int[] c = new int[n]; boolean b = true; int ind = -1, min = 100001; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); c[i] = a[i]; if(i!=0&&c[i]<=min && c[i] != c[i-1]){ min = c[i]; ind = i; } } Arrays.sort(c); if(Arrays.equals(a, c)) System.out.println(0); else{ for (int i = 0; i < n; i++) { if(c[i] == a[(ind+i)%n]) continue; else{ b = false; break; } } if(b) System.out.println(n-ind); else System.out.println("-1"); } } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
2b1eb8e964480670942663238ed0734d
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class B259 { InputStream is; PrintWriter out; /** * Go to Sublime, copy & pase the input Use Ctrl+A, Ctrl+Shift+L, Ctrl+Enter * to create this string */ // String INPUT = "2\n2 1"; // String INPUT = "3\n1 3 2"; // String INPUT = "7\n2 3 3 1 1 1 2"; // String INPUT = "3\n1 2 3"; // String INPUT = "4\n5 1 2 3"; // String INPUT = "5\n1 2 3 4 5"; String INPUT = "5\n5 4 3 2 1"; void solve() { int n = ni(); int[] ar = na(n); int i = n - 1; for (i = n - 1; i >= 1; i--) { // debug("checking " + i + " " + ar[i-1] + " " + ar[i]); if (ar[i - 1] > ar[i]) { break; } } for(int j = 0 ; j < i - 1; j++) { if(ar[j] > ar[j+1]) { out.println(-1); return; } } if(i == 0) { if(ar[0] <= ar[1]) { out.println(0); return; } } int rs = n-1 - i + 1; if(rs > 0 && ar[0] < ar[n - 1]) {; out.println(-1); return; } out.println(rs); } /** * Built using CHelper plug-in Actual solution is at the top */ static final int INF = (int) 1e9; private static boolean oj = System.getProperty("ONLINE_JUDGE") != null; private static void debug(Object... o) { if (!oj) System.out.println(Arrays.deepToString(o)); } static int[][] packD(int n, int[] from, int[] to) { int[][] result = new int[n][]; int[] goOutCount = new int[n]; for (int f : from) goOutCount[f]++; for (int i = 0; i < n; i++) result[i] = new int[goOutCount[i]]; for (int i = 0; i < from.length; i++) { --goOutCount[from[i]]; result[from[i]][goOutCount[from[i]]] = to[i]; } return result; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); debug(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new B259().run(); } private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } /** * Next Double. */ private double nd() { return Double.parseDouble(ns()); } /** * Next Char. */ private char nc() { return (char) skip(); } /** * Next String. */ private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != // ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } /** * Next Char array. */ private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } /** * Next Matrix. */ private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } /** * Next Array. */ private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } /** * Next Integer. */ private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } /** * Next Long. */ private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
414468761824467ae6cd31e9a743641d
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new PrintWriter(System.out)); int n = Integer.parseInt(br.readLine()); String[] ln1 = br.readLine().split(" "); int[] a = new int[n]; //wraps round if(n==1) bw.append("0"+"\n"); else{ int index=0; for(int i=0;i<n;i++){ a[i] = Integer.parseInt(ln1[i]); if(a[i]>a[index]) index=i; } int acnt = 0; while(true){ if(acnt == n-1) break; int rindex = index==n-1 ? 0 : index+1; if(a[rindex]<a[index]) {index=rindex;break;} else if(a[rindex]==a[index] && rindex==n-1) index=0; else if(a[rindex]==a[index]) index=rindex; acnt+=1; } int use = index; int cnt=0; boolean good = true; while(true){ if(cnt>=n-1) break; int bindex = index==n-1 ? 0 : index+1; if(a[bindex]<a[index]){ good=false;break; }else{ index=bindex; } cnt+=1; } if(good){ bw.append((n-use)%n+"\n"); }else{ bw.append("-1"+"\n"); } } bw.close(); } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
3cb68263c30bbb1b448474be5a671157
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Main { private static boolean sameset(int a, int b, int[] uf) { return find(a,uf) == find(b,uf); } private static void union(int a, int b, int[] uf) { uf[find(a,uf)] = find(b,uf); } private static int find(int a, int[] uf) { if(a == uf[a]) return a; int root = find(uf[a],uf); uf[a] = root; return root; } private static void BFS(int i, int[][] G, int[][] path) { // System.out.println("source vertex "+i); int[] v = new int[G.length]; // current maximum dist in u---v path ArrayDeque<Integer> A = new ArrayDeque(); A.add(i); while(A.isEmpty() == false){ int u = A.pop(); //System.out.println("for node "+u); for(int a=0;a<v.length;a++){ if(G[u][a] > 0 && v[a]==0 && a!=i){//edge in MST, later make faster //System.out.println(a+" is and edge from "+u); if(G[u][a] > v[u]){ //System.out.println(" and it incrases the sub path max "); v[a] = G[u][a]; } else v[a] = v[u]; path[i][a] = v[a]; path[a][i] = v[a]; // System.out.println("finally path from "+i+" to "+a+" is "+path[i][a]); A.add(a); } } } } static class Node{ int idf; int idr; int d=-1; int num; public Node(int c,int a){ this.idf = a; this.num = c; } } static class Edge{ int x; int y;//ids of nodes int w; public Edge( int x1, int y1, int w){ this.x = x1; this.y = y1; this.w = w; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new PrintWriter(System.out)); int n = Integer.parseInt(br.readLine()); String[] _x = br.readLine().split(" "); int[] d = new int[n]; int[] s = new int[n]; int k = -1; int min = Integer.MAX_VALUE; for(int i=0;i<n;i++){ d[i] = Integer.parseInt(_x[i]); s[i] = d[i]; } Arrays.sort(s); for(int i=n-1;i>=1;i--){ if(d[i]==s[0] && d[i-1]!=s[0]){ k=i; min=k; //System.out.println("saw min at "+k); break; } } if(k==-1){ k=0;min=0; } // k = n-k; boolean bad = false;; for(int i=0;i<n;i++){ if(s[i] != d[k]){ bad = true;break; } if(k==n-1) k=0; else k+=1; } if(bad) bw.append("-1\n"); else bw.append((n-min)%n+"\n"); bw.close(); } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
712b22d17615a1b733e100d95482e859
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class B_259 { public static void main(String[] args) throws IOException { InputStreamReader input = new InputStreamReader(System.in); BufferedReader br=new BufferedReader(input); int n = Integer.parseInt(br.readLine()); int current=0; int next=0; int index = 0; String tokens[] = br.readLine().split(" "); ArrayList<Integer> list = new ArrayList<Integer>(); for(int i = 0;i < n; i++) list.add(Integer.parseInt(tokens[i])); /*n = 99998; list = new ArrayList<Integer>(); list.add(99997); for(int i = 0; i < 99997; i ++) list.add(i); list.add(99996);*/ int start = 0; int end = n-1; while(start >=0 && start < n && end >=0 && end <n && list.get(start) >= list.get(end) && index < n){ start = end; end--; index++; } boolean isIncreasing = true; for(int i = 0 ; i < n-1; i++){ if(i != n - 1 - index && list.get(i) > list.get(i+1)){ isIncreasing= false; break; } } if(index == n) index = 0; //System.out.println(index+" "+isIncreasing); if(isIncreasing) System.out.println(index); else System.out.println("-1"); } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
a75ecd4621bbe55e8a2e5bb7175413d8
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.io.*; import java.util.*; public class b1 { public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int ind = 0; while (ind < n - 1 && (a[ind + 1] > a[ind] || a[ind] == a[ind + 1])){ ind++; } if (ind == n - 1){ out.print(0); } else{ if (a[ind + 1] > a[0]){ out.print(-1); } else{ int ind1 = ind; ind++; while (ind < n - 1 && (a[ind + 1] > a[ind] || a[ind] == a[ind + 1])){ ind++; } if (ind == n - 1 && a[n - 1] <= a[0]){ out.print(n - ind1 - 1); } else{ out.print(-1); } } } out.close(); } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
266c5bb8c92917dd72c3f6cada1909d9
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class LittlePonyandSortbyShift { public static void main(String[] args) throws IOException { Init(System.in); int n = nextInt(); int a[] = new int[n]; boolean check = true; int count = 0; int position = 0; for (int i = 0; i < n; ++i) { a[i] = nextInt(); if (i > 0 && a[i] < a[i - 1]) { count++; position = i; } } if (count > 1) { System.out.println(-1); } else if (count == 0) { System.out.println(0); } else { if (a[n - 1] > a[0]) { System.out.println(-1); } else { System.out.println(n - position); } } } static BufferedReader reader; static StringTokenizer tokenizer; static void Init(InputStream input) { reader = new BufferedReader(new InputStreamReader(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 Integer.parseInt(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } static Double NextDouble() throws IOException { return Double.parseDouble(next()); } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
3ebda1fd7f340b26d2ac3db7f414b205
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
/** * Created by Phillip on 8/9/2014. */ import java.io.*; import java.util.*; public class Main { public static void main(String[] args)throws IOException{ Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] input = new int[n]; for(int i=0;i<n;i++) input[i] = in.nextInt(); int[] differences = new int[n+1]; int numberof = 0; int stor = 0; for(int i=0;i<n-1;i++){ if(input[i+1]-input[i]<0){ differences[i] = 0; numberof++; stor = i; } else{ differences[i] = 1; } } if(input[0]-input[n-1]<0){ differences[n-1] = 0; stor = n-1; numberof++; } else{ differences[n-1] = 1; } if(numberof>1){ System.out.println(-1); } else if(numberof==0){ System.out.println(0); } else{ System.out.println(n-1-stor); } } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
5f9b3fd2af672f4b757d307b5a942054
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.util.Scanner; public class so { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); sc.nextLine(); int a[]=new int[n]; a[0]=sc.nextInt(); int k=0; int j=0; for(int i=1;i<n;i++) { a[i]=sc.nextInt(); if(a[i]<a[i-1]) {k++; j=i; } } if(a[0]<a[n-1] && k!=0) { k=5; } if(k==1) { System.out.println(n-(j)); } else if(k==0) System.out.println(0); else System.out.println(-1); } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
074c7e1838e087e25b7092b7e8fbc7c5
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
/* ID: sharnob1 PROG: ride LANG: JAVA */ import java.io.*; import java.util.*; public class ride { public static void main(String[] args) { FastScanner scanner = new FastScanner(); int n = scanner.nextInt(); int[] arr = new int[n]; int index = n-1; boolean sw = false; for (int i = 0; i < n; i++) { arr[i] = scanner.nextInt(); } for (int i = 0; i < n; i++) { if (arr[i] > arr[(i+1)%n]) { if (sw) { System.out.println(-1); return; } else { sw = true; index = i; } } } System.out.println(n-index-1); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(String f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
a6b78dd435dc639c96e1aa2b8eaa0b9b
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.util.Scanner; public class B_Little_Pony_and_Sort_by_Shift { static public void main(String arr[]) { Scanner x = new Scanner(System.in); int n = x.nextInt(), eq1, sq1, eq2 = 0, sq2 = 0 , temp , count = 0; boolean flag = true, one = true , first = true; eq1 = sq1 = x.nextInt(); for (int i = 1; i < n; i++) { temp = x.nextInt(); if (temp >= eq1 && first) eq1 = temp; else if (temp <= sq1) { if (one) { first = one = false; eq2 = sq2 = temp; count = n - i; continue; } if (temp >= eq2) eq2 = temp; else flag = false; } else flag = false; } if (flag) System.out.print(count); else System.out.print(-1); } } /* * int n = x.nextInt(), a; Queue<Integer> list = new LinkedList<Integer>(); * boolean flag = true; for (int i = 0; i < n; i++) { list.a(x.nextInt()); if (i * != 0) if (list.get(i) < list.get(i - 1)) flag = false; } if (flag) * System.out.println(0); else { int min = 0 , temp; for (int i = 0 ; i < n ; * i++) { min++; list.add(0, list.get(n-1)); list = list.subList(0, * n-1);//(list.get(n-1)); for (int i1 = 0 ; i1 < n ; i1++) * System.out.print(list.get(i1)+" "); if (ch(list)) { System.out.println(min); * return; } } * * * System.out.println(-1); } } static boolean ch (java.util.List<Integer> list) * { for (int i = 0; i < list.size(); i++) { { * * if (i != 0) * * if (list.get(i) < list.get(i - 1)) return false; }} return true; } } */
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
1252ed78407674c45b594aa54daf7eba
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.util.*; import java.io.*; public class Cf259b { public static void main(String[] args) throws IOException { InputStreamReader fin = new InputStreamReader(System.in); StreamTokenizer scr = new StreamTokenizer(fin); scr.nextToken(); int n = (int)scr.nval; int [] a = new int [n]; for (int i = 0; i < n; i++) { scr.nextToken(); a[i] = (int)scr.nval; } PrintWriter fout = new PrintWriter(System.out); fout.print(min(n, a)); fout.flush(); fout.close(); } static int sort(int n, int [] a) { for (int i = 1; i < n; i++) { if (a[i] < a[i-1]) { return i; } } return 0; } static int min (int n, int [] a) { int k = sort(n, a); if (k == 0) { return 0; } if (k != 0) { int [] b = new int [n]; int j = 0; for (int i = k; i < n; i++) { b[j] = a[i]; j++; } for (int i = 0; i < k; i++) { b[j] = a[i]; j++; } for (int i = 1; i < n; i++) { if (b[i] < b[i-1]) { return -1; } } } return n-k; } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
756e385395aa5e0d4e14ad47e55120bf
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { int n; Scanner s = new Scanner(System.in); n = s.nextInt(); int[] a = new int[n]; boolean pico = false; for(int i = 0 ; i<n ; i++) { a[i] = s.nextInt(); } boolean baje,subi; baje=false; boolean tr = true; int aux = a[0]; int pos=0; int menor = a[0]; for(int i = 1 ; i < n ; i++) { if(a[i]<aux) { if(!baje) { if(a[i] <= menor) { baje = true; pos = n-i; } else tr = false; } else tr = false; } aux=a[i]; } if(baje) { if(a[n-1]>menor) tr = false; } if(tr) { System.out.println(pos); } else System.out.println(-1); } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
5d31e958a34ed2fc7c10e85d83d45302
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.util.*; public class _454B_Little_Pony_and_Sort_by_Shift { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] a = new int[n]; int[] c = new int[n]; int start = 0; for (int i = 0; i < n; i++) a[i] = in.nextInt(); for (int i = 1; i < n; i++) if (a[i] < a[i - 1]) { start = i; break; } for (int i = 0; i < c.length; i++) c[i] = a[(i + start) % n]; if (isSorted(c)) System.out.println((n - start)%n); else System.out.println(-1); } private static boolean isSorted(int[] a) { for (int i = 1; i < a.length; i++) if (a[i - 1] > a[i]) return false; return true; } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
593063cfce289363e35bfc00d8b5bca8
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.util.Scanner; public class Little_Pony_and_Sort_by_Shift { public static void main(String args[]){ Scanner in = new Scanner(System.in); int a = in.nextInt(); int b[] =new int[a]; for( int i=0 ; i< a; i++) b[i] = in.nextInt(); int min = b[0] ,ind =0 , count = 0 , max = b[0] , ind_max=0; for(int i=0;i<a;i++){ if(b[i]<min){ ind=i; min=b[i]; } if(b[i]>=max){ max=b[i]; ind_max=i; } } if(ind!=0){ for(int i=ind;;i++){ if(i==a-1){ if(b[a-1]<=b[0]) count++; i=-1; }else if(i==ind-1){ if(b[i]<=b[i+1]) count++; break; }else{ if(b[i]<=b[i+1]) count++; } } }else if(ind==0){ for(int i=0;i<a-1;i++) if(b[i]<=b[i+1]) count++; if(b[a-1]<=b[0]) count++; } count++; if(count == b.length || count > b.length){ if(ind!=0) System.out.println(count-ind); else{ if(ind_max==a-1) System.out.println(0); else{ System.out.println(count-ind_max-1); } } }else{ System.out.println(-1); } } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
5f1163fa3f48ef933660557bb1f8b6b7
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.io.*; import java.util.*; public class B { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); public void run() { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int cnt = 0, cur = 0; for (int i = 1; i < n; i++) { if (a[i] < a[i-1]) { cnt++; cur = i; } } if (cnt == 0) { System.out.println(0); } else if (cnt == 1 && a[n-1] <= a[0]) { System.out.println(n - cur); } else { System.out.println(-1); } out.close(); } public static void main(String[] args) { new B().run(); } public void mapDebug(int[][] a) { System.out.println("--------map display---------"); for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { System.out.printf("%3d ", a[i][j]); } System.out.println(); } System.out.println("----------------------------"); System.out.println(); } public void debug(Object... obj) { System.out.println(Arrays.deepToString(obj)); } class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; //stream = new FileInputStream(new File("dec.in")); } 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++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } 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(); } String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
5621ff5bf2546bd945ba057a1ff9b1cf
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class B259 { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); String[] s=br.readLine().split(" "); int[] arr=new int[n]; for(int i=0;i<n;i++){ arr[i]=Integer.parseInt(s[i]); } int index=-1; boolean sorted=true; for(int i=1;i<n;i++){ if(arr[i]<arr[i-1]){ if(index==-1) index=i; else{ sorted=false; break; } } } if(sorted){ if(index==-1){ System.out.println(0); return; }else{ if(arr[n-1]<=arr[0]) System.out.println(n-index); else System.out.println(-1); } }else System.out.println(-1); } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
039669b51d0d769fae85bc1056aadb7f
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * Created by DELL on 30-Jan-16. */ public class Main { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static void main(String ar[]) throws IOException { Main demo = new Main(); demo.solve(); } public void solve() throws IOException { br.readLine(); String tokens[] = br.readLine().split(" "); int a[] = new int[tokens.length]; for (int i = 0; i < a.length; i++) { a[i] = Integer.parseInt(tokens[i]); } int index = -1; for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { index = i + 1; } } if (index == -1) { System.out.println(0); return; } for (int i = index, count = 0; count < a.length - 1; i = (i + 1) % a.length, count++) { if (a[i] > a[(i + 1) % a.length]) { System.out.println(-1); return; } } System.out.println(a.length - index); } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
4353d7dfee5e69776aae5bd5bf6190b6
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class SortByShift { public static void main(String[] args) throws IOException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { String input; while ((input = reader.readLine()) != null && input.length() > 0) { int n = Integer.parseInt(input.trim()); int[] array = new int[n]; StringTokenizer data = new StringTokenizer(reader.readLine()); for (int i = 0; i < n; i++) { array[i] = Integer.parseInt(data.nextToken()); } int stepsToSort = 0; if (!isSorted(array)) { int min = array[0]; int minIndex = 0; for (int i = 1; i < n; i++) { if (array[i] < array[i - 1]) { minIndex = i; break; } } if (array[minIndex] <= min) { ++stepsToSort; for (int i = minIndex + 1; i < n; i++) { if (array[i] >= array[i - 1] && array[i] <= min) { ++stepsToSort; } else { stepsToSort = -1; break; } } } else { stepsToSort = -1; } } System.out.println(stepsToSort); } } } private static boolean isSorted(int[] array) { for (int i = 1; i < array.length; i++) { if (array[i] < array[i - 1]) { return false; } } return true; } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
10809cd89a9c306770dd69eb695944db
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.util.*; import java.io.*; public class Test { public static void main(String[] args){ Scanner cin = new Scanner(System.in); int n = cin.nextInt(); int a[] = new int[n]; for(int i = 0; i < n;i++){ a[i] = cin.nextInt(); } int flag = 0; int pos = -1; for(int i = 1; i < n; i++){ if(a[i-1] > a[i]){ flag++; if(flag == 1){ pos = i; } } } if(flag == 0){ System.out.println("0"); } else if(flag > 1){ System.out.println("-1"); } else { if(a[n-1] > a[0]){ System.out.println("-1"); } else{ System.out.println(n-pos); } } } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
d444b8df7d96867ed017e5e88912ba3c
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
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) { int n = in.readInt(); int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = in.readInt(); int minIdx = 0; for(int i = 1; i < n; i++) if(a[i] < a[i - 1]) minIdx = i; boolean ok = true; for(int i = 0; i < n - 1; i++) if(a[(minIdx + i + 1) % n] < a[(minIdx + i) % n]) ok = false; if(ok) out.printLine((n - minIdx) % n); else out.printLine(-1); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } 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(); } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
6c719759f2885c7b0178d26a7b9d20a7
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; import java.util.Arrays; /** * Built using CHelper plug-in * Actual solution is at the top */ public class MainB { 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 shift(int[] a) { int next = a[a.length - 1]; for (int i = a.length - 1; i > 0; i--) a[i] = a[i - 1]; a[0] = next; } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] input = new int[n]; for (int i = 0; i < n; i++) { input[i] = in.nextInt(); } int count = 0; int frontSort = 1; for (int i = 1; i < n; i++) { if (input[i] < input[i - 1]) break; frontSort++; } int backSort = 1; for (int i = input.length - 2; i >= 0; i--) { if (input[i + 1] < input[i]) break; backSort++; } // out.println(backSort + " " + frontSort); if (frontSort == n || backSort == n) { out.print(0); return; } if (frontSort + backSort != n) { out.print("-1"); return; } if (input[n - 1] > input[0]) { out.print("-1"); return; } out.print(backSort); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
05aa0aa0c6936bc10971fef725cc5115
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public final class LittlePonyandSortbyShift { private static BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] args) { try { int seq[] = new int[Integer.valueOf(r.readLine()).intValue()]; StringTokenizer st = new StringTokenizer(r.readLine()); int index = 0; while (st.hasMoreTokens()) { seq[index++] = Integer.valueOf(st.nextToken()).intValue(); } int moves = 0; for(int i=1; i<seq.length; i++) { if(seq[i-1] > seq[i]) if(moves == 0) moves = seq.length - i; else moves = -1; } if(moves != 0 && seq[seq.length-1] > seq[0]) moves = -1; System.out.println(moves); } catch (IOException e) { e.printStackTrace(); } } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
8d94b36e73944db2aa59d29a10bed22c
train_003.jsonl
1406907000
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.StringTokenizer; public class Solution { static class Escanner { BufferedReader in; StringTokenizer st; Escanner() throws Throwable { in = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); } Escanner(FileReader file) throws Throwable { in = new BufferedReader(file); st = new StringTokenizer(""); } int nextInt() throws Throwable { if (st.hasMoreTokens()) return Integer.parseInt(st.nextToken()); st = new StringTokenizer(in.readLine()); return nextInt(); } long nextLong() throws Throwable { if (st.hasMoreTokens()) return Long.parseLong(st.nextToken()); st = new StringTokenizer(in.readLine()); return nextLong(); } BigInteger nextBigInt() throws Throwable { if (st.hasMoreTokens()) return new BigInteger(st.nextToken()); st = new StringTokenizer(in.readLine()); return nextBigInt(); } double nextDouble() throws Throwable { if (st.hasMoreTokens()) return Double.parseDouble(st.nextToken()); st = new StringTokenizer(in.readLine()); return nextDouble(); } String nextStr() throws Throwable { if (st.hasMoreTokens()) return st.nextToken(); st = new StringTokenizer(in.readLine()); return nextStr(); } } static int getStart(int[] arr) { int min = 0; for (int i = 0; i < arr.length; i++) if (arr[i] < arr[min]) min = i; if(min==0){ for(int i=arr.length-1; i>=0; i--) if(arr[i]!=arr[min]) break; else min = i; } return min; } static boolean isSortable(int idx, int[] arr) { int n = arr.length; for (int i = idx; i != (idx - 1 + n) % n; i = (i + 1) % n) if (arr[i] > arr[(i + 1) % n]) return false; return true; } public static void main(String[] args) throws Throwable { Escanner sc = new Escanner(); int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); int s = getStart(arr); System.out.println(isSortable(s, arr) ? ((n - s) % n) : "-1"); } }
Java
["2\n2 1", "3\n1 3 2", "2\n1 2"]
1 second
["1", "-1", "0"]
null
Java 7
standard input
[ "implementation" ]
c647e36495fb931ac72702a12c6bfe58
The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
1,200
If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.
standard output
PASSED
7a9e1381e5706c678eb3027abb8079d4
train_003.jsonl
1561905900
The letters shop showcase is a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $$$s$$$.There are $$$m$$$ friends, the $$$i$$$-th of them is named $$$t_i$$$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount. For example, for $$$s$$$="arrayhead" and $$$t_i$$$="arya" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="harry" $$$6$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="ray" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="r" $$$2$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="areahydra" all $$$9$$$ letters have to be bought ("arrayhead"). It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
256 megabytes
/* 9 2 1 1 1 1 1 0 0 0 0 1 2 1 5 5 6 5 7 2 3 2 4 3 8 3 9 */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; public class Question { static boolean[] v1; static boolean[] v2; static LinkedList<Integer> adj[]; static int[] d1; static int[] d2; static int[] dp; static int[][] next; public static void main(String[] args) throws IOException { Reader.init(System.in); /*int n = Reader.nextInt(); adj = new LinkedList[n+1]; for (int i = 0 ; i < n+1 ; i++){ adj[i] = new LinkedList<>(); } int[] destroy = new int[n+1]; for (int i = 0 ; i < n-1 ; i++){ int n1 = Reader.nextInt(); int n2 = Reader.nextInt(); int n3 = Reader.nextInt(); adj[n1].addLast(n2); adj[n2].addLast(n1); destroy[n1] = n3; destroy[n2] = n3; } LinkedList<Integer> list = new LinkedList<>(); LinkedList<Integer> q = new LinkedList<>(); for (int i = 0 ; i < n+1 ; i++){ if (i!=1){ if (adj[i].size()==1){ q.addLast(i); //System.out.println(i); } } } boolean visited[] = new boolean[n+1]; int cnt = 0; while (q.isEmpty()==false){ int child = q.removeFirst(); int flag = 0; if (destroy[child]==1){ flag = 1; cnt++; list.add(child); System.out.println("child " + child ); destroy[child] = 0; } Iterator i = adj[child].iterator(); while (i.hasNext()){ int node = (int)i.next(); if ((!visited[node])){ visited[node] = true; if (flag==0&&destroy[node]==1){ flag =1; cnt++; System.out.println("He " + child + " " + node); list.add(node); } i = adj[node].iterator(); } else{ break; } } } System.out.println(cnt); while (list.isEmpty()==false){ System.out.print(list.removeFirst()+ " "); } System.out.println();*/ int n = Reader.nextInt(); String s = Reader.next(); int[][] pre = new int[s.length()+1][26]; int[][] table = new int[s.length()+1][26]; //Arrays.fill(table,-1); //char[] arr = s.toCharArray(); for (int i = 1 ; i < s.length()+1 ; i++){ for (int j = 0 ; j < 26 ; j++){ pre[i][j] = pre[i-1][j]; } pre[i][s.charAt(i-1)-'a']++; table[pre[i][s.charAt(i-1)-'a']][s.charAt(i-1)-'a'] = i; } //System.out.println(Arrays.deepToString(pre)); int q = Reader.nextInt(); while (q-->0){ String que = Reader.next(); //char[] qarr = que.toCharArray(); int[] cnt = new int[26]; for (int i = 0 ; i < que.length(); i++){ cnt[que.charAt(i)-'a']++; } //System.out.println(Arrays.toString(cnt)); int max = -1; for (int i = 0 ; i <26 ; i++ ){ max = Math.max(max,table[cnt[i]][i]); } System.out.println(max); } } static int fun1(int i , int j , int t1 , int t2){ Arrays.fill(dp,-1); return fun(i,j,t1,t2); } static int fun(int i , int j,int t1,int t2){ if (i>=j){ return 0; } else if (dp[i]!=-1){ //System.out.println(dp[i] + " " + i); return dp[i]; } dp[i] = Math.min(t1 + fun(next[i][0]+1,j,t1,t2),t2 + fun(next[i][1]+1,j,t1,t2)); return dp[i]; } static void rowSwap(int[][] arr , int x , int y,int m , int n){ for (int i = 0 ; i < m ; i++){ int temp = arr[x][i]; arr[x][i] = arr[y][i]; arr[y][i] = temp; } } static void colSwap(int[][] arr , int x , int y,int m , int n){ for (int i = 0 ; i < n ; i++){ int temp = arr[i][x]; arr[i][x] = arr[i][y]; arr[i][y] = temp; } } static void dfsA(int v,int dis){ //System.out.println(v); //System.out.println(v1.length); v1[v] = true; d1[v] = dis; Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()){ int n = i.next(); if (!v1[n]){ dfsA(n,dis+1); } } } static void dfsB(int v,int dis){ v2[v] = true; d2[v] = dis; Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()){ int n = i.next(); if (!v2[n]){ dfsB(n,dis+1); } } } public static void sortbyColumn(int arr[][], int col) { // Using built-in sort function Arrays.sort Arrays.sort(arr, new Comparator<int[]>() { @Override // Compare values according to columns public int compare(final int[] entry1, final int[] entry2) { // To sort in descending order revert // the '>' Operator if (entry1[col] > entry2[col]) return 1; else return -1; } }); // End of function call sort(). } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } } class MergeSort { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int [n1]; int R[] = new int [n2]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() void sort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves sort(arr, l, m); sort(arr , m+1, r); // Merge the sorted halves merge(arr, l, m, r); } } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i=0; i<n; ++i) System.out.print(arr[i] + " "); System.out.println(); } // Driver method } class Node{ int data; int freq; public Node(int data, int freq) { this.data = data; this.freq = freq; } } class GFG { // limit for array size static int N = 1000000; static int n; // array size // Max size of tree static int []tree = new int[2 * N]; // function to build the tree static void build( char []arr,int n) { // insert leaf nodes in tree for (int i = 0; i < n-1; i++) { if (arr[i]!=arr[i+1]) { System.out.println(i); tree[n + i] = 1; } } // build the tree by calculating // parents for (int i = n - 1; i > 0; --i) tree[i] = tree[i << 1] + tree[i << 1 | 1]; } static int query(int l, int r) { int res = 0; // loop to find the sum in the range for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if ((l & 1) > 0) res += tree[l++]; if ((r & 1) > 0) res += tree[--r]; } return res; } // driver program to test the // above function }
Java
["9\narrayhead\n5\narya\nharry\nray\nr\nareahydra"]
2 seconds
["5\n6\n5\n2\n9"]
null
Java 8
standard input
[ "binary search", "implementation", "strings" ]
8736df815ea0fdf390cc8d500758bf84
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of showcase string $$$s$$$. The second line contains string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains one integer $$$m$$$ ($$$1 \le m \le 5 \cdot 10^4$$$) — the number of friends. The $$$i$$$-th of the next $$$m$$$ lines contains $$$t_i$$$ ($$$1 \le |t_i| \le 2 \cdot 10^5$$$) — the name of the $$$i$$$-th friend. It is guaranteed that $$$\sum \limits_{i=1}^m |t_i| \le 2 \cdot 10^5$$$.
1,300
For each friend print the length of the shortest prefix of letters from $$$s$$$ s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount. It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.
standard output
PASSED
fe1f5151cfcaaa27957c8f14cff13b95
train_003.jsonl
1561905900
The letters shop showcase is a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $$$s$$$.There are $$$m$$$ friends, the $$$i$$$-th of them is named $$$t_i$$$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount. For example, for $$$s$$$="arrayhead" and $$$t_i$$$="arya" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="harry" $$$6$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="ray" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="r" $$$2$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="areahydra" all $$$9$$$ letters have to be bought ("arrayhead"). It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
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.StringTokenizer; public class B { void solve() { int n = readInt(); char[] a = readString().toCharArray(); int[][] b = new int[200][n]; int[] help = new int[200]; for(int i = 0;i<a.length;i++){ b[a[i]][help[a[i]]] = i + 1; help[a[i]]++; } int m = readInt(); for(int i = 0;i<m;i++){ Arrays.fill(help, 0); char[] q = readString().toCharArray(); int max = 0; for(int j = 0;j<q.length;j++){ max = Math.max(max, b[q[j]][help[q[j]]]); help[q[j]]++; } out.println(max); } } public static void main(String[] args) { new B().run(); } private void run() { try { init(); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } private BufferedReader in; private StringTokenizer tok = new StringTokenizer(""); private PrintWriter out; private void init() { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); // try { // in = new BufferedReader(new FileReader("absum.in")); // out = new PrintWriter(new File("absum.out")); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } } private String readLine() { try { return in.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } private String readString() { while (!tok.hasMoreTokens()) { String nextLine = readLine(); if (nextLine == null) return null; tok = new StringTokenizer(nextLine); } return tok.nextToken(); } private int readInt() { return Integer.parseInt(readString()); } private long readLong() { return Long.parseLong(readString()); } }
Java
["9\narrayhead\n5\narya\nharry\nray\nr\nareahydra"]
2 seconds
["5\n6\n5\n2\n9"]
null
Java 8
standard input
[ "binary search", "implementation", "strings" ]
8736df815ea0fdf390cc8d500758bf84
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of showcase string $$$s$$$. The second line contains string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains one integer $$$m$$$ ($$$1 \le m \le 5 \cdot 10^4$$$) — the number of friends. The $$$i$$$-th of the next $$$m$$$ lines contains $$$t_i$$$ ($$$1 \le |t_i| \le 2 \cdot 10^5$$$) — the name of the $$$i$$$-th friend. It is guaranteed that $$$\sum \limits_{i=1}^m |t_i| \le 2 \cdot 10^5$$$.
1,300
For each friend print the length of the shortest prefix of letters from $$$s$$$ s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount. It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.
standard output
PASSED
e80a88d02de344d3694c328e5ec03c27
train_003.jsonl
1561905900
The letters shop showcase is a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $$$s$$$.There are $$$m$$$ friends, the $$$i$$$-th of them is named $$$t_i$$$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount. For example, for $$$s$$$="arrayhead" and $$$t_i$$$="arya" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="harry" $$$6$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="ray" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="r" $$$2$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="areahydra" all $$$9$$$ letters have to be bought ("arrayhead"). It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
256 megabytes
import java.util.*; public class CFE67B { public static void main(String[] args) { Scanner scanny = new Scanner(System.in); int len = scanny.nextInt(); scanny.nextLine(); char[] s = scanny.nextLine().toCharArray(); int[][] arr = new int[26][len]; int[] at = new int[26]; for(int i = 0; i < len; i++) { int aaaa = s[i]-'a'; arr[aaaa][at[aaaa]++] = i+1; } int x = scanny.nextInt(); for(int i = 0; i < x; i++) { char[] name = scanny.next().toCharArray(); int[] bluh = new int[26]; for(int j = 0; j < name.length; j++) bluh[name[j]-'a']++; int ans = 0; for(int j = 0; j < 26; j++) { if(bluh[j]>0) ans = Math.max(ans, arr[j][bluh[j]-1]); } System.out.println(ans); } } } /* 10 aaaaaaaaaa 5 a aa aaa aaaa aaaaa 26 abcdefghijklmnopqrstuvwxyz 1 qwertyuiopasdfghjklzxcvbnm 10 aabbccddee 1 abcde */
Java
["9\narrayhead\n5\narya\nharry\nray\nr\nareahydra"]
2 seconds
["5\n6\n5\n2\n9"]
null
Java 8
standard input
[ "binary search", "implementation", "strings" ]
8736df815ea0fdf390cc8d500758bf84
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of showcase string $$$s$$$. The second line contains string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains one integer $$$m$$$ ($$$1 \le m \le 5 \cdot 10^4$$$) — the number of friends. The $$$i$$$-th of the next $$$m$$$ lines contains $$$t_i$$$ ($$$1 \le |t_i| \le 2 \cdot 10^5$$$) — the name of the $$$i$$$-th friend. It is guaranteed that $$$\sum \limits_{i=1}^m |t_i| \le 2 \cdot 10^5$$$.
1,300
For each friend print the length of the shortest prefix of letters from $$$s$$$ s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount. It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.
standard output
PASSED
21df2da7db37ff1568248c340cc2c432
train_003.jsonl
1561905900
The letters shop showcase is a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $$$s$$$.There are $$$m$$$ friends, the $$$i$$$-th of them is named $$$t_i$$$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount. For example, for $$$s$$$="arrayhead" and $$$t_i$$$="arya" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="harry" $$$6$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="ray" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="r" $$$2$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="areahydra" all $$$9$$$ letters have to be bought ("arrayhead"). It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public final class CF { public static void main(String[]args)throws IOException { //int K=(int)Math.pow(10,9)+7; FastReader ob=new FastReader(); StringBuffer sb=new StringBuffer(); int n=ob.nextInt(); String s=ob.nextLine(); HashMap<Character,ArrayList<Integer>> hm=new HashMap<>(); for(int i=0;i<n;i++) { ArrayList<Integer> ts=new ArrayList<>(); if(hm.containsKey(s.charAt(i))) ts=hm.get(s.charAt(i)); ts.add(i); hm.put(s.charAt(i),ts); } int T=ob.nextInt(); while(T-->0) { String s1=ob.nextLine(); int max=-1; TreeSet<Integer> ts=new TreeSet<>(); for(int i=0;i<s1.length();i++) { ArrayList<Integer> a=hm.get(s1.charAt(i)); int x=0,y=a.size(); while(x<=y) { int mid=(x+y)/2; if(ts.contains(a.get(mid))) x=mid+1; else y=mid-1; } //System.out.println(a.get(x)); ts.add(a.get(x)); max=Math.max(max,a.get(x)); } sb.append((max+1)+"\n"); } System.out.println(sb); } } class Pair { int x,y; Pair(int x,int y) { this.x=x; this.y=y; } } class PairComparator implements Comparator<Pair> { public int compare(Pair a,Pair b) { return a.x-b.x; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public String nextLine() { String s=""; try { s=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["9\narrayhead\n5\narya\nharry\nray\nr\nareahydra"]
2 seconds
["5\n6\n5\n2\n9"]
null
Java 8
standard input
[ "binary search", "implementation", "strings" ]
8736df815ea0fdf390cc8d500758bf84
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of showcase string $$$s$$$. The second line contains string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains one integer $$$m$$$ ($$$1 \le m \le 5 \cdot 10^4$$$) — the number of friends. The $$$i$$$-th of the next $$$m$$$ lines contains $$$t_i$$$ ($$$1 \le |t_i| \le 2 \cdot 10^5$$$) — the name of the $$$i$$$-th friend. It is guaranteed that $$$\sum \limits_{i=1}^m |t_i| \le 2 \cdot 10^5$$$.
1,300
For each friend print the length of the shortest prefix of letters from $$$s$$$ s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount. It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.
standard output
PASSED
3d420e440aea9e932e86e0a70e5dcf50
train_003.jsonl
1561905900
The letters shop showcase is a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $$$s$$$.There are $$$m$$$ friends, the $$$i$$$-th of them is named $$$t_i$$$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount. For example, for $$$s$$$="arrayhead" and $$$t_i$$$="arya" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="harry" $$$6$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="ray" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="r" $$$2$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="areahydra" all $$$9$$$ letters have to be bought ("arrayhead"). It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class training { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String s = sc.next(); int m = sc.nextInt(); String t; ArrayList<ArrayList<Integer>> arr=new ArrayList<>(); for(int i=0 ; i<26 ; i++) arr.add(new ArrayList<>()); for (int i = 0; i < s.length(); i++) { arr.get(s.charAt(i)-'a').add(i); // arr[s.charAt(i) - 'a']++; } // for(int i=0 ; i<26 ; i++){ // System.out.println(""); // System.out.print((char)(i+'a')+" "); // // for(int j=0 ; j<arr.get(i).size() ; j++) // System.out.print(arr.get(i).get(j)); // } int arr2[] = new int[26]; while (m-- > 0) { t = sc.next(); int max = 0; arr2=new int[26]; for (int i = 0; i < t.length(); i++) { arr2[t.charAt(i) - 'a']++; } for (int i = 0; i < 26; i++) { if(arr2[i]!=0){ // System.out.println("i "+(char)(i+'a')); if(arr.get(i).get(arr2[i]-1)>max) max=arr.get(i).get(arr2[i]-1); } } System.out.println(max+1); } } // int n=sc.nextInt(); // int m=sc.nextInt(); // int maxCorrect=0, minWrong=Integer.MAX_VALUE ,minCorrect=0; // int c; // for(int i=0 ; i<n ; i++){ // c=sc.nextInt(); // if(c>maxCorrect) // maxCorrect=c; // if(c<minCorrect) // minCorrect=c; // } // for(int i=0 ; i<m ; i++){ // c=sc.nextInt(); // if(c<minWrong) // minWrong=c; // } // if(minWrong<=maxCorrect) // System.out.println("-1"); // else if(maxCorrect+maxCorrect/2>=minWrong) // System.out.println("-1"); // else // System.out.println(maxCorrect); // // } }
Java
["9\narrayhead\n5\narya\nharry\nray\nr\nareahydra"]
2 seconds
["5\n6\n5\n2\n9"]
null
Java 8
standard input
[ "binary search", "implementation", "strings" ]
8736df815ea0fdf390cc8d500758bf84
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of showcase string $$$s$$$. The second line contains string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains one integer $$$m$$$ ($$$1 \le m \le 5 \cdot 10^4$$$) — the number of friends. The $$$i$$$-th of the next $$$m$$$ lines contains $$$t_i$$$ ($$$1 \le |t_i| \le 2 \cdot 10^5$$$) — the name of the $$$i$$$-th friend. It is guaranteed that $$$\sum \limits_{i=1}^m |t_i| \le 2 \cdot 10^5$$$.
1,300
For each friend print the length of the shortest prefix of letters from $$$s$$$ s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount. It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.
standard output
PASSED
3778d91b2e0a8bda1e7e9dcf7cb31cfc
train_003.jsonl
1561905900
The letters shop showcase is a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $$$s$$$.There are $$$m$$$ friends, the $$$i$$$-th of them is named $$$t_i$$$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount. For example, for $$$s$$$="arrayhead" and $$$t_i$$$="arya" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="harry" $$$6$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="ray" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="r" $$$2$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="areahydra" all $$$9$$$ letters have to be bought ("arrayhead"). It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
256 megabytes
//package cf; import java.util.*; import java.io.*; public class Cf{ static class Node{ int sum,occur; Node(int sum){ this.sum=sum; } } public static void main(String[]args){ Scanner in=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); long t=1;//in.nextLong(); out: while(t-->0){ int n=in.nextInt(); char [] s=in.next().toCharArray(); Vector<Integer>[] an = (Vector<Integer>[]) new Vector[26]; for(int i = 0; i <26; i++) an[i] = new Vector<Integer>(); for(int i=0;i<n;i++){ an[s[i]-'a'].add(i+1); } long m=in.nextInt(); while(m-->0){ char ch[]=in.next().toCharArray(); int mm[]=new int[26]; for(int i=0;i<ch.length;i++){ mm[ch[i]-'a']++; } int count=0; for(int i=0;i<26;i++){ if(mm[i]>0) count=Math.max(count,an[i].get(mm[i]-1)); } Vector<Integer>v=new Vector<>(); out.println(count); } //int a[]=new int[n]; //TreeSet<Integer>ts=new TreeSet<Integer>(); //for(int i=0;i<n;i++){} //for(int i=0;i<n;a[i++]=in.nextInt()){} // if(flag) out.println("YES"); // else out.println("NO"); // TreeMap<Integer,Integer>tm=new TreeMap<>(); // for(int i=0;i<n;i++){ // if(tm.containsKey(i)){ // int val=tm.get(i); // tm.replace(i, val, val+1); // } // else tm.put(i, 1); // } } in.close(); out.close(); } }
Java
["9\narrayhead\n5\narya\nharry\nray\nr\nareahydra"]
2 seconds
["5\n6\n5\n2\n9"]
null
Java 8
standard input
[ "binary search", "implementation", "strings" ]
8736df815ea0fdf390cc8d500758bf84
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of showcase string $$$s$$$. The second line contains string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains one integer $$$m$$$ ($$$1 \le m \le 5 \cdot 10^4$$$) — the number of friends. The $$$i$$$-th of the next $$$m$$$ lines contains $$$t_i$$$ ($$$1 \le |t_i| \le 2 \cdot 10^5$$$) — the name of the $$$i$$$-th friend. It is guaranteed that $$$\sum \limits_{i=1}^m |t_i| \le 2 \cdot 10^5$$$.
1,300
For each friend print the length of the shortest prefix of letters from $$$s$$$ s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount. It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.
standard output
PASSED
3ba638c9fde61c6b206bb9c83d2f7d84
train_003.jsonl
1561905900
The letters shop showcase is a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $$$s$$$.There are $$$m$$$ friends, the $$$i$$$-th of them is named $$$t_i$$$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount. For example, for $$$s$$$="arrayhead" and $$$t_i$$$="arya" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="harry" $$$6$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="ray" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="r" $$$2$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="areahydra" all $$$9$$$ letters have to be bought ("arrayhead"). It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int l = sc.nextInt(); String word = sc.next(); int cases = sc.nextInt(); int[] num = new int[26]; //how much each letter appears int[][] loc = new int[26][l]; //the order of where it appears. for(int i = 0; i < l; i++) { char ch = word.charAt(i); loc[ch - 'a'][num[ch - 'a']] = i + 1; num[ch - 'a']++; } //System.out.println(Arrays.toString(num)); //System.out.println(Arrays.deepToString(loc)); for(int i = 0; i < cases; i++) { String str = sc.next(); num = new int[26]; int index, max = 1; //index is highest index for a letter. for(int j = 0; j < str.length(); j++) { char ch = str.charAt(j); index = loc[ch - 'a'][num[ch - 'a']]; num[ch - 'a']++; if(index > max) max = index; } System.out.println(max); } } }
Java
["9\narrayhead\n5\narya\nharry\nray\nr\nareahydra"]
2 seconds
["5\n6\n5\n2\n9"]
null
Java 8
standard input
[ "binary search", "implementation", "strings" ]
8736df815ea0fdf390cc8d500758bf84
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of showcase string $$$s$$$. The second line contains string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains one integer $$$m$$$ ($$$1 \le m \le 5 \cdot 10^4$$$) — the number of friends. The $$$i$$$-th of the next $$$m$$$ lines contains $$$t_i$$$ ($$$1 \le |t_i| \le 2 \cdot 10^5$$$) — the name of the $$$i$$$-th friend. It is guaranteed that $$$\sum \limits_{i=1}^m |t_i| \le 2 \cdot 10^5$$$.
1,300
For each friend print the length of the shortest prefix of letters from $$$s$$$ s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount. It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.
standard output
PASSED
f2315caa0422933b8a8ed5a5ad8c3a83
train_003.jsonl
1561905900
The letters shop showcase is a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $$$s$$$.There are $$$m$$$ friends, the $$$i$$$-th of them is named $$$t_i$$$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount. For example, for $$$s$$$="arrayhead" and $$$t_i$$$="arya" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="harry" $$$6$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="ray" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="r" $$$2$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="areahydra" all $$$9$$$ letters have to be bought ("arrayhead"). It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.PrintStream; import java.util.Arrays; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); char[] a = in.next().toCharArray(); int[][] id = new int[26][n]; for (int[] x : id) Arrays.fill(x, -1); int[] ptr = new int[26]; for (int i = 0; i < n; i++) { int let = a[i] - 'a'; id[let][ptr[let]++] = i; } int m = in.nextInt(); for (int i = 0; i < m; i++) { char[] x = in.next().toCharArray(); int[] f = new int[26]; for (int j = 0; j < x.length; j++) f[x[j] - 'a']++; int res = 0; for (int j = 0; j < 26; j++) { if (f[j] > 0) res = Math.max(res, id[j][f[j] - 1]); } System.out.println(res + 1); } } } }
Java
["9\narrayhead\n5\narya\nharry\nray\nr\nareahydra"]
2 seconds
["5\n6\n5\n2\n9"]
null
Java 8
standard input
[ "binary search", "implementation", "strings" ]
8736df815ea0fdf390cc8d500758bf84
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of showcase string $$$s$$$. The second line contains string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains one integer $$$m$$$ ($$$1 \le m \le 5 \cdot 10^4$$$) — the number of friends. The $$$i$$$-th of the next $$$m$$$ lines contains $$$t_i$$$ ($$$1 \le |t_i| \le 2 \cdot 10^5$$$) — the name of the $$$i$$$-th friend. It is guaranteed that $$$\sum \limits_{i=1}^m |t_i| \le 2 \cdot 10^5$$$.
1,300
For each friend print the length of the shortest prefix of letters from $$$s$$$ s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount. It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.
standard output
PASSED
84d42d55c4902347610beb3e922231f7
train_003.jsonl
1561905900
The letters shop showcase is a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $$$s$$$.There are $$$m$$$ friends, the $$$i$$$-th of them is named $$$t_i$$$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount. For example, for $$$s$$$="arrayhead" and $$$t_i$$$="arya" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="harry" $$$6$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="ray" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="r" $$$2$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="areahydra" all $$$9$$$ letters have to be bought ("arrayhead"). It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
256 megabytes
//package com.company; import java.io.*; import java.util.*; public class Main { private static HashMap<Character,Integer> [] line = new HashMap[2000000]; public static void main(String[] args) throws IOException { // write your code here BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw =new PrintWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(br.readLine()); String Line = br.readLine(); line[0]= new HashMap<>(); line[0].put(Line.charAt(0),1); // for(int i=1;i<Line.length();i++){ line[i] = (HashMap)line[i-1].clone(); if (line[i-1].containsKey(Line.charAt(i))) { line[i].replace(Line.charAt(i),line[i].get(Line.charAt(i))+1); } else{ line[i].put(Line.charAt(i),1); } } // System.out.println(Arrays.toString(line)); int m = Integer.parseInt(br.readLine()); while (m-->0){ String word = br.readLine(); HashMap<Character,Integer> target =new HashMap<>(); for (int i=0;i<word.length();i++) if (target.containsKey(word.charAt(i))) target.replace(word.charAt(i),target.get(word.charAt(i))+1); else target.put(word.charAt(i),1); // pw.println(target); int left =0; int right = n-1; int mid = 0; while (left<=right){ // System.out.println(mid); mid = (left+right)/2; if (compare(target,mid)>=1) left = mid+1; else right = mid-1; } pw.println(right+2); } pw.flush(); } public static int compare(HashMap<Character,Integer> target,int mid){ Iterator it = target.entrySet().iterator(); int numberOfElementisGreater =0; int numerOfElementisLessThan =0; int equalAmount = 0; int unknonw = 0; while (it.hasNext()){ Map.Entry pair = (Map.Entry)it.next(); // System.out.println(line[mid]); if (line[mid].get((char)pair.getKey())!=null) { int value = line[mid].get((char)pair.getKey()); if (value > (int) pair.getValue()) numberOfElementisGreater++; else if (line[mid].get(pair.getKey()) == (int) pair.getValue()) equalAmount++; else numerOfElementisLessThan++; } else return 1; } //a lot fo less than if (numerOfElementisLessThan>=1) return 1; return 0; } }
Java
["9\narrayhead\n5\narya\nharry\nray\nr\nareahydra"]
2 seconds
["5\n6\n5\n2\n9"]
null
Java 8
standard input
[ "binary search", "implementation", "strings" ]
8736df815ea0fdf390cc8d500758bf84
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of showcase string $$$s$$$. The second line contains string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains one integer $$$m$$$ ($$$1 \le m \le 5 \cdot 10^4$$$) — the number of friends. The $$$i$$$-th of the next $$$m$$$ lines contains $$$t_i$$$ ($$$1 \le |t_i| \le 2 \cdot 10^5$$$) — the name of the $$$i$$$-th friend. It is guaranteed that $$$\sum \limits_{i=1}^m |t_i| \le 2 \cdot 10^5$$$.
1,300
For each friend print the length of the shortest prefix of letters from $$$s$$$ s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount. It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.
standard output
PASSED
ca4c1c2f3300780d0af0cdc9fbe93076
train_003.jsonl
1561905900
The letters shop showcase is a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $$$s$$$.There are $$$m$$$ friends, the $$$i$$$-th of them is named $$$t_i$$$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount. For example, for $$$s$$$="arrayhead" and $$$t_i$$$="arya" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="harry" $$$6$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="ray" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="r" $$$2$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="areahydra" all $$$9$$$ letters have to be bought ("arrayhead"). It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
256 megabytes
import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Scanner; public class Scratch { private static class Data { final List<Integer> positions; Integer currentIdx; private Data(List<Integer> positions) { this.positions = positions; this.currentIdx = 0; } public List<Integer> getPositions() { return positions; } public Integer getCurrentIdx() { return currentIdx; } public void setCurrentIdx(Integer currentIdx) { this.currentIdx = currentIdx; } } public static void main(String[] args) { final Scanner sc = new Scanner(System.in); sc.nextInt(); String s = sc.next(); Map<Character, Data> map = new HashMap<>(); char[] charArray = s.toCharArray(); for (int i = 0; i < charArray.length; i++) { char c = charArray[i]; map.putIfAbsent(c, new Data(new ArrayList<>())); map.get(c).positions.add(i + 1); } int m = sc.nextInt(); for (int i = 0; i < m; i++) { map.keySet().forEach(c -> map.get(c).setCurrentIdx(0)); int max = 0; String t = sc.next(); for (char c : t.toCharArray()) { Data d = map.get(c); max = Math.max(d.positions.get(d.currentIdx++), max); } System.out.println(max); } } }
Java
["9\narrayhead\n5\narya\nharry\nray\nr\nareahydra"]
2 seconds
["5\n6\n5\n2\n9"]
null
Java 8
standard input
[ "binary search", "implementation", "strings" ]
8736df815ea0fdf390cc8d500758bf84
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of showcase string $$$s$$$. The second line contains string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains one integer $$$m$$$ ($$$1 \le m \le 5 \cdot 10^4$$$) — the number of friends. The $$$i$$$-th of the next $$$m$$$ lines contains $$$t_i$$$ ($$$1 \le |t_i| \le 2 \cdot 10^5$$$) — the name of the $$$i$$$-th friend. It is guaranteed that $$$\sum \limits_{i=1}^m |t_i| \le 2 \cdot 10^5$$$.
1,300
For each friend print the length of the shortest prefix of letters from $$$s$$$ s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount. It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.
standard output
PASSED
22d5b60bd7cad034ff52cf2800bf20f5
train_003.jsonl
1561905900
The letters shop showcase is a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $$$s$$$.There are $$$m$$$ friends, the $$$i$$$-th of them is named $$$t_i$$$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount. For example, for $$$s$$$="arrayhead" and $$$t_i$$$="arya" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="harry" $$$6$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="ray" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="r" $$$2$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="areahydra" all $$$9$$$ letters have to be bought ("arrayhead"). It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
256 megabytes
import java.util.*; public class B1187 { static void init(List<ArrayList<Integer>> arr, char s[]) { for(int i = 0; i<26; i++) { arr.add(new ArrayList<Integer>()); } for(int i = 0; i < s.length; i++) { arr.get(s[i] - 'a').add(i+1); } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); char s[] = sc.next().toCharArray(); int m = sc.nextInt(); List<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>(); init(arr, s); while(m-- > 0) { int res = 0; char cs[] = sc.next().toCharArray(); int carr[] = new int[26]; for(int i = 0; i < cs.length; i++) { carr[cs[i] - 'a']++; } for(int i = 0; i < 26; i++) { if(carr[i] > 0) { int index = arr.get(i).get(carr[i] - 1); if(res < index) { res = index; } } } System.out.println(res); } } }
Java
["9\narrayhead\n5\narya\nharry\nray\nr\nareahydra"]
2 seconds
["5\n6\n5\n2\n9"]
null
Java 8
standard input
[ "binary search", "implementation", "strings" ]
8736df815ea0fdf390cc8d500758bf84
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of showcase string $$$s$$$. The second line contains string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains one integer $$$m$$$ ($$$1 \le m \le 5 \cdot 10^4$$$) — the number of friends. The $$$i$$$-th of the next $$$m$$$ lines contains $$$t_i$$$ ($$$1 \le |t_i| \le 2 \cdot 10^5$$$) — the name of the $$$i$$$-th friend. It is guaranteed that $$$\sum \limits_{i=1}^m |t_i| \le 2 \cdot 10^5$$$.
1,300
For each friend print the length of the shortest prefix of letters from $$$s$$$ s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount. It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.
standard output
PASSED
4e717b3aba2a135881f03f394f72f53b
train_003.jsonl
1561905900
The letters shop showcase is a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $$$s$$$.There are $$$m$$$ friends, the $$$i$$$-th of them is named $$$t_i$$$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount. For example, for $$$s$$$="arrayhead" and $$$t_i$$$="arya" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="harry" $$$6$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="ray" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="r" $$$2$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="areahydra" all $$$9$$$ letters have to be bought ("arrayhead"). It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileInputStream; 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.HashMap; import java.util.Scanner; import java.util.StringTokenizer; public class B { public static void main(String[] args) { Kattio sc = new Kattio(System.in, System.out); int n = sc.getInt(); String s = sc.getWord(); HashMap<Integer,ArrayList<Integer>> H = new HashMap<Integer,ArrayList<Integer>>(); for(int i=0;i<n;i++) { int c = s.charAt(i); if(!H.containsKey(c)) H.put(c, new ArrayList<Integer>()); ArrayList<Integer> a = H.get(c); a.add(i+1); H.put(c, a); } int m = sc.getInt(); for(int i=0;i<m;i++) { String st = sc.getWord(); int max = 0; HashMap<Integer,Integer> h = new HashMap<Integer,Integer>(); for(int j=0;j<st.length();j++) { if(!h.containsKey((int) st.charAt(j))) { h.put((int)st.charAt(j), 1); }else { h.put((int)st.charAt(j), h.get((int)st.charAt(j))+1); } } for(int j=0;j<st.length();j++) { int ind = h.get((int)st.charAt(j)); int d = H.get((int)st.charAt(j)).get(ind-1); if(d>max) max = d; /*System.out.println(i); System.out.println(H); System.out.println(h);*/ } sc.write(max+"\n"); sc.flush(); } } static class Kattio extends PrintWriter { private BufferedReader r; private String line; private StringTokenizer st; private String token; public Kattio(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); } public Kattio(InputStream i, OutputStream o) { super(new BufferedOutputStream(o)); r = new BufferedReader(new InputStreamReader(i)); } public Kattio(FileInputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); } public Kattio(FileInputStream i, OutputStream o) { super(new BufferedOutputStream(o)); r = new BufferedReader(new InputStreamReader(i)); } public boolean hasMoreTokens() { return peekToken() != null; } public int getInt() { return Integer.parseInt(nextToken()); } public double getDouble() { return Double.parseDouble(nextToken()); } public long getLong() { return Long.parseLong(nextToken()); } public String getWord() { return nextToken(); } public String getLine() { st=null; String l = null; try { l=r.readLine(); }catch(IOException e) {} return l; } private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; } private String nextToken() { String ans = peekToken(); token = null; return ans; } } }
Java
["9\narrayhead\n5\narya\nharry\nray\nr\nareahydra"]
2 seconds
["5\n6\n5\n2\n9"]
null
Java 8
standard input
[ "binary search", "implementation", "strings" ]
8736df815ea0fdf390cc8d500758bf84
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of showcase string $$$s$$$. The second line contains string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains one integer $$$m$$$ ($$$1 \le m \le 5 \cdot 10^4$$$) — the number of friends. The $$$i$$$-th of the next $$$m$$$ lines contains $$$t_i$$$ ($$$1 \le |t_i| \le 2 \cdot 10^5$$$) — the name of the $$$i$$$-th friend. It is guaranteed that $$$\sum \limits_{i=1}^m |t_i| \le 2 \cdot 10^5$$$.
1,300
For each friend print the length of the shortest prefix of letters from $$$s$$$ s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount. It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.
standard output
PASSED
21099d2b84d9e3654c6aa7795c935823
train_003.jsonl
1561905900
The letters shop showcase is a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $$$s$$$.There are $$$m$$$ friends, the $$$i$$$-th of them is named $$$t_i$$$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount. For example, for $$$s$$$="arrayhead" and $$$t_i$$$="arya" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="harry" $$$6$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="ray" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="r" $$$2$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="areahydra" all $$$9$$$ letters have to be bought ("arrayhead"). It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Iterator; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author aryssoncf */ 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 { final int N = 26; public void solve(int testNumber, InputReader in, OutputWriter out) { try { int n = in.readInt(); char[] str = in.readCharArray(n); int[][] freq = new int[N][n]; for (int i = 0; i < N; i++) { for (int j = 0; j < n; j++) { if (str[j] - 'a' == i) { freq[i][j]++; } } } long[][] sum = new long[N][]; for (int i = 0; i < N; i++) { sum[i] = ArrayUtils.partialSums(freq[i]); } int m = in.readInt(); for (int i = 0; i < m; i++) { str = in.readString().toCharArray(); int res = 0; for (int j = 0; j < N; j++) { int finalJ = j; int count = ArrayUtils.count(str, (char) ('a' + j)), pos = (int) MiscUtils.binarySearch(0, n, k -> sum[finalJ][(int) k] >= count); res = Math.max(res, pos); } out.printLine(res); } } catch (Exception e) { e.printStackTrace(); } } } static interface CharStream extends Iterable<Character>, Comparable<CharStream> { CharIterator charIterator(); default Iterator<Character> iterator() { return new Iterator<Character>() { private CharIterator it = charIterator(); public boolean hasNext() { return it.isValid(); } public Character next() { char result = it.value(); it.advance(); return result; } }; } default int compareTo(CharStream c) { CharIterator it = charIterator(); CharIterator jt = c.charIterator(); while (it.isValid() && jt.isValid()) { char i = it.value(); char j = jt.value(); if (i < j) { return -1; } else if (i > j) { return 1; } it.advance(); jt.advance(); } if (it.isValid()) { return 1; } if (jt.isValid()) { return -1; } return 0; } default int count(char value) { int result = 0; for (CharIterator it = charIterator(); it.isValid(); it.advance()) { if (it.value() == value) { result++; } } return result; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public char[] readCharArray(int size) { char[] array = new char[size]; for (int i = 0; i < size; i++) { array[i] = readCharacter(); } return array; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char readCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public interface SpaceCharFilter { boolean isSpaceChar(int ch); } } static abstract class CharAbstractStream implements CharStream { public String toString() { StringBuilder builder = new StringBuilder(); boolean first = true; for (CharIterator it = charIterator(); it.isValid(); it.advance()) { if (first) { first = false; } else { builder.append(' '); } builder.append(it.value()); } return builder.toString(); } public boolean equals(Object o) { if (!(o instanceof CharStream)) { return false; } CharStream c = (CharStream) o; CharIterator it = charIterator(); CharIterator jt = c.charIterator(); while (it.isValid() && jt.isValid()) { if (it.value() != jt.value()) { return false; } it.advance(); jt.advance(); } return !it.isValid() && !jt.isValid(); } public int hashCode() { int result = 0; for (CharIterator it = charIterator(); it.isValid(); it.advance()) { result *= 31; result += it.value(); } return result; } } static interface LongFilter { public boolean accept(long value); } static interface CharList extends CharReversableCollection { public abstract char get(int index); public abstract void removeAt(int index); default public CharIterator charIterator() { return new CharIterator() { private int at; private boolean removed; public char value() { if (removed) { throw new IllegalStateException(); } return get(at); } public boolean advance() { at++; removed = false; return isValid(); } public boolean isValid() { return !removed && at < size(); } public void remove() { removeAt(at); at--; removed = true; } }; } } static interface CharIterator { public char value() throws NoSuchElementException; public boolean advance(); public boolean isValid(); } static class ArrayUtils { public static long[] partialSums(int[] array) { long[] result = new long[array.length + 1]; for (int i = 0; i < array.length; i++) { result[i + 1] = result[i] + array[i]; } return result; } public static int count(char[] array, char value) { return new CharArray(array).count(value); } } static interface CharReversableCollection extends CharCollection { } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } static interface CharCollection extends CharStream { public int size(); } static class MiscUtils { public static long binarySearch(long from, long to, LongFilter function) { while (from < to) { long argument = from + ((to - from) >> 1); if (function.accept(argument)) { to = argument; } else { from = argument + 1; } } return from; } } static class CharArray extends CharAbstractStream implements CharList { private char[] data; public CharArray(char[] arr) { data = arr; } public int size() { return data.length; } public char get(int at) { return data[at]; } public void removeAt(int index) { throw new UnsupportedOperationException(); } } }
Java
["9\narrayhead\n5\narya\nharry\nray\nr\nareahydra"]
2 seconds
["5\n6\n5\n2\n9"]
null
Java 8
standard input
[ "binary search", "implementation", "strings" ]
8736df815ea0fdf390cc8d500758bf84
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of showcase string $$$s$$$. The second line contains string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains one integer $$$m$$$ ($$$1 \le m \le 5 \cdot 10^4$$$) — the number of friends. The $$$i$$$-th of the next $$$m$$$ lines contains $$$t_i$$$ ($$$1 \le |t_i| \le 2 \cdot 10^5$$$) — the name of the $$$i$$$-th friend. It is guaranteed that $$$\sum \limits_{i=1}^m |t_i| \le 2 \cdot 10^5$$$.
1,300
For each friend print the length of the shortest prefix of letters from $$$s$$$ s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount. It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.
standard output
PASSED
1b646435d94398ab9897a961668da70b
train_003.jsonl
1561905900
The letters shop showcase is a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $$$s$$$.There are $$$m$$$ friends, the $$$i$$$-th of them is named $$$t_i$$$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount. For example, for $$$s$$$="arrayhead" and $$$t_i$$$="arya" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="harry" $$$6$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="ray" $$$5$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="r" $$$2$$$ letters have to be bought ("arrayhead"). For example, for $$$s$$$="arrayhead" and $$$t_i$$$="areahydra" all $$$9$$$ letters have to be bought ("arrayhead"). It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.StringTokenizer; public class Solution implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) { new Thread(null, new Solution(), "", 256 * (1L << 20)).start(); } public void run() { try { long t1 = System.currentTimeMillis(); //if (System.getProperty("ONLINE_JUDGE") != null) { 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"); // } Locale.setDefault(Locale.US); solve(); in.close(); out.close(); long t2 = System.currentTimeMillis(); //System.err.println("Time = " + (t2 - t1)); } catch (Throwable t) { t.printStackTrace(System.err); System.exit(-1); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } // solution void solve() throws IOException { long strLen = readLong(); List<List<Integer>> precom = new ArrayList<>(); for(int i=0; i<29; i++) { precom.add(new ArrayList<>()); } String s = readString(); for(int i=0; i < s.length(); i++) { int index = s.charAt(i) - 'a'; precom.get(index).add(i); } long nameCnt = readLong(); for(int i=0; i < nameCnt; i++) { String name = readString(); int prefix = getPrefix(precom, name); out.println(prefix); } } private int getPrefix(List<List<Integer>> precom, String name) { int[] usedIndexes = new int[29]; int pl = 0; for (char c : name.toCharArray()) { List<Integer> indexes = precom.get(c - 'a'); int index = indexes.get(usedIndexes[c - 'a']); usedIndexes[c - 'a'] += 1; pl = pl < index ? index : pl; } return pl + 1; } }
Java
["9\narrayhead\n5\narya\nharry\nray\nr\nareahydra"]
2 seconds
["5\n6\n5\n2\n9"]
null
Java 8
standard input
[ "binary search", "implementation", "strings" ]
8736df815ea0fdf390cc8d500758bf84
The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of showcase string $$$s$$$. The second line contains string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains one integer $$$m$$$ ($$$1 \le m \le 5 \cdot 10^4$$$) — the number of friends. The $$$i$$$-th of the next $$$m$$$ lines contains $$$t_i$$$ ($$$1 \le |t_i| \le 2 \cdot 10^5$$$) — the name of the $$$i$$$-th friend. It is guaranteed that $$$\sum \limits_{i=1}^m |t_i| \le 2 \cdot 10^5$$$.
1,300
For each friend print the length of the shortest prefix of letters from $$$s$$$ s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount. It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.
standard output
PASSED
9db158a169f24133bd973a604d5644c2
train_003.jsonl
1606633500
There is a prison that can be represented as a rectangular matrix with $$$n$$$ rows and $$$m$$$ columns. Therefore, there are $$$n \cdot m$$$ prison cells. There are also $$$n \cdot m$$$ prisoners, one in each prison cell. Let's denote the cell in the $$$i$$$-th row and the $$$j$$$-th column as $$$(i, j)$$$.There's a secret tunnel in the cell $$$(r, c)$$$, that the prisoners will use to escape! However, to avoid the risk of getting caught, they will escape at night.Before the night, every prisoner is in his own cell. When night comes, they can start moving to adjacent cells. Formally, in one second, a prisoner located in cell $$$(i, j)$$$ can move to cells $$$( i - 1 , j )$$$ , $$$( i + 1 , j )$$$ , $$$( i , j - 1 )$$$ , or $$$( i , j + 1 )$$$, as long as the target cell is inside the prison. They can also choose to stay in cell $$$(i, j)$$$.The prisoners want to know the minimum number of seconds needed so that every prisoner can arrive to cell $$$( r , c )$$$ if they move optimally. Note that there can be any number of prisoners in the same cell at the same time.
256 megabytes
import java.util.*; public class PrisonBreak { static long getTime(long n, long m, long r, long c) { long c1[] = new long[] { 1, 1 }; long c2[] = new long[] { 1, m }; long c3[] = new long[] { n, 1 }; long c4[] = new long[] { n, m }; long d1 = Math.abs(r - c1[0]) + Math.abs(c - c1[1]); long d2 = Math.abs(r - c2[0]) + Math.abs(c - c2[1]); long d3 = Math.abs(r - c3[0]) + Math.abs(c - c3[1]); long d4 = Math.abs(r - c4[0]) + Math.abs(c - c4[1]); // System.out.println(d1 + " d2 " + d2 + " d3 " + d3 + " d4 " + d4); return Math.max(d1, Math.max(d2, Math.max(d3, d4))); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); long tc = sc.nextLong(); while (tc-- > 0) { long n = sc.nextLong(); long m = sc.nextLong(); long r = sc.nextLong(); long c = sc.nextLong(); long time = getTime(n, m, r, c); System.out.println(time); } } }
Java
["3\n10 10 1 1\n3 5 2 4\n10 2 5 1"]
1 second
["18\n4\n6"]
null
Java 8
standard input
[ "brute force", "math" ]
3a3fbb61c7e1ccda69cd6d186da653ae
The first line contains an integer $$$t$$$ $$$(1 \le t \le 10^4)$$$, the number of test cases. Each of the next $$$t$$$ lines contains four space-separated integers $$$n$$$, $$$m$$$, $$$r$$$, $$$c$$$ ($$$1 \le r \le n \le 10^9$$$, $$$1 \le c \le m \le 10^9$$$).
null
Print $$$t$$$ lines, the answers for each test case.
standard output
PASSED
8885173056f1ff20cf5473e8985999f7
train_003.jsonl
1606633500
There is a prison that can be represented as a rectangular matrix with $$$n$$$ rows and $$$m$$$ columns. Therefore, there are $$$n \cdot m$$$ prison cells. There are also $$$n \cdot m$$$ prisoners, one in each prison cell. Let's denote the cell in the $$$i$$$-th row and the $$$j$$$-th column as $$$(i, j)$$$.There's a secret tunnel in the cell $$$(r, c)$$$, that the prisoners will use to escape! However, to avoid the risk of getting caught, they will escape at night.Before the night, every prisoner is in his own cell. When night comes, they can start moving to adjacent cells. Formally, in one second, a prisoner located in cell $$$(i, j)$$$ can move to cells $$$( i - 1 , j )$$$ , $$$( i + 1 , j )$$$ , $$$( i , j - 1 )$$$ , or $$$( i , j + 1 )$$$, as long as the target cell is inside the prison. They can also choose to stay in cell $$$(i, j)$$$.The prisoners want to know the minimum number of seconds needed so that every prisoner can arrive to cell $$$( r , c )$$$ if they move optimally. Note that there can be any number of prisoners in the same cell at the same time.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class TechnoCupA { static FastScanner in; static PrintWriter out; static class FastScanner{ StringTokenizer st; BufferedReader br; FastScanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } } public static void main(String[] args) throws IOException { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.flush(); out.close(); } private static void solve() throws IOException { int t = in.nextInt(); for (int i = 0; i < t; i++) { int n = in.nextInt() - 1, m = in.nextInt() - 1; int r = in.nextInt() - 1, c = in.nextInt() - 1; if (Math.abs(r) > Math.abs(r - n)){ if (Math.abs(c) > Math.abs(c - m)){ out.println(r + c); } else { out.println(r + m - c); } } else { if (Math.abs(c) > Math.abs(c - m)) { out.println(c + n - r); } else { out.println(n + m - r - c); } } } } }
Java
["3\n10 10 1 1\n3 5 2 4\n10 2 5 1"]
1 second
["18\n4\n6"]
null
Java 8
standard input
[ "brute force", "math" ]
3a3fbb61c7e1ccda69cd6d186da653ae
The first line contains an integer $$$t$$$ $$$(1 \le t \le 10^4)$$$, the number of test cases. Each of the next $$$t$$$ lines contains four space-separated integers $$$n$$$, $$$m$$$, $$$r$$$, $$$c$$$ ($$$1 \le r \le n \le 10^9$$$, $$$1 \le c \le m \le 10^9$$$).
null
Print $$$t$$$ lines, the answers for each test case.
standard output
PASSED
71d3199cd6208e09120d7b7aed3328c0
train_003.jsonl
1606633500
There is a prison that can be represented as a rectangular matrix with $$$n$$$ rows and $$$m$$$ columns. Therefore, there are $$$n \cdot m$$$ prison cells. There are also $$$n \cdot m$$$ prisoners, one in each prison cell. Let's denote the cell in the $$$i$$$-th row and the $$$j$$$-th column as $$$(i, j)$$$.There's a secret tunnel in the cell $$$(r, c)$$$, that the prisoners will use to escape! However, to avoid the risk of getting caught, they will escape at night.Before the night, every prisoner is in his own cell. When night comes, they can start moving to adjacent cells. Formally, in one second, a prisoner located in cell $$$(i, j)$$$ can move to cells $$$( i - 1 , j )$$$ , $$$( i + 1 , j )$$$ , $$$( i , j - 1 )$$$ , or $$$( i , j + 1 )$$$, as long as the target cell is inside the prison. They can also choose to stay in cell $$$(i, j)$$$.The prisoners want to know the minimum number of seconds needed so that every prisoner can arrive to cell $$$( r , c )$$$ if they move optimally. Note that there can be any number of prisoners in the same cell at the same time.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class A1 { public static PrintWriter out; public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int r = sc.nextInt(); int l = sc.nextInt(); int a, b, c, d; a = r - 1 + l - 1; b = n - r + l - 1; c = n - r + m - l; d = r - 1 + m - l; out.println(Math.max(Math.max(a, b), Math.max(c, d))); } out.close(); } public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n10 10 1 1\n3 5 2 4\n10 2 5 1"]
1 second
["18\n4\n6"]
null
Java 8
standard input
[ "brute force", "math" ]
3a3fbb61c7e1ccda69cd6d186da653ae
The first line contains an integer $$$t$$$ $$$(1 \le t \le 10^4)$$$, the number of test cases. Each of the next $$$t$$$ lines contains four space-separated integers $$$n$$$, $$$m$$$, $$$r$$$, $$$c$$$ ($$$1 \le r \le n \le 10^9$$$, $$$1 \le c \le m \le 10^9$$$).
null
Print $$$t$$$ lines, the answers for each test case.
standard output
PASSED
de2b383ecde556f29e9e1d822e4ccc64
train_003.jsonl
1606633500
There is a prison that can be represented as a rectangular matrix with $$$n$$$ rows and $$$m$$$ columns. Therefore, there are $$$n \cdot m$$$ prison cells. There are also $$$n \cdot m$$$ prisoners, one in each prison cell. Let's denote the cell in the $$$i$$$-th row and the $$$j$$$-th column as $$$(i, j)$$$.There's a secret tunnel in the cell $$$(r, c)$$$, that the prisoners will use to escape! However, to avoid the risk of getting caught, they will escape at night.Before the night, every prisoner is in his own cell. When night comes, they can start moving to adjacent cells. Formally, in one second, a prisoner located in cell $$$(i, j)$$$ can move to cells $$$( i - 1 , j )$$$ , $$$( i + 1 , j )$$$ , $$$( i , j - 1 )$$$ , or $$$( i , j + 1 )$$$, as long as the target cell is inside the prison. They can also choose to stay in cell $$$(i, j)$$$.The prisoners want to know the minimum number of seconds needed so that every prisoner can arrive to cell $$$( r , c )$$$ if they move optimally. Note that there can be any number of prisoners in the same cell at the same time.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * Place here class purpose. * * @author Kirill * @since 29.11.2020 */ public class TaskARule { public static void main(String[] args) throws IOException { TaskARule task = new TaskARule(); task.resolve(); } private void resolve() throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); int testCount = Integer.parseInt(bufferedReader.readLine()); StringBuilder answer = new StringBuilder(); for (int i = 0; i < testCount; i++) { String[] strings = bufferedReader.readLine().split(" "); int height = Integer.parseInt(strings[0]); int width = Integer.parseInt(strings[1]); int exitY = Integer.parseInt(strings[2]); int exitX = Integer.parseInt(strings[3]); long sum1 = exitX + exitY-2; long sum2 = width - exitX + exitY - 1; long sum3 = exitX + height - exitY - 1; long sum4 = width - exitX + height - exitY; answer.append(Math.max(Math.max(sum1, sum2), Math.max(sum3, sum4))).append("\n"); } System.out.println(answer.toString()); } }
Java
["3\n10 10 1 1\n3 5 2 4\n10 2 5 1"]
1 second
["18\n4\n6"]
null
Java 8
standard input
[ "brute force", "math" ]
3a3fbb61c7e1ccda69cd6d186da653ae
The first line contains an integer $$$t$$$ $$$(1 \le t \le 10^4)$$$, the number of test cases. Each of the next $$$t$$$ lines contains four space-separated integers $$$n$$$, $$$m$$$, $$$r$$$, $$$c$$$ ($$$1 \le r \le n \le 10^9$$$, $$$1 \le c \le m \le 10^9$$$).
null
Print $$$t$$$ lines, the answers for each test case.
standard output
PASSED
a1b4389e0789dd8b9030370757598092
train_003.jsonl
1606633500
There is a prison that can be represented as a rectangular matrix with $$$n$$$ rows and $$$m$$$ columns. Therefore, there are $$$n \cdot m$$$ prison cells. There are also $$$n \cdot m$$$ prisoners, one in each prison cell. Let's denote the cell in the $$$i$$$-th row and the $$$j$$$-th column as $$$(i, j)$$$.There's a secret tunnel in the cell $$$(r, c)$$$, that the prisoners will use to escape! However, to avoid the risk of getting caught, they will escape at night.Before the night, every prisoner is in his own cell. When night comes, they can start moving to adjacent cells. Formally, in one second, a prisoner located in cell $$$(i, j)$$$ can move to cells $$$( i - 1 , j )$$$ , $$$( i + 1 , j )$$$ , $$$( i , j - 1 )$$$ , or $$$( i , j + 1 )$$$, as long as the target cell is inside the prison. They can also choose to stay in cell $$$(i, j)$$$.The prisoners want to know the minimum number of seconds needed so that every prisoner can arrive to cell $$$( r , c )$$$ if they move optimally. Note that there can be any number of prisoners in the same cell at the same time.
256 megabytes
import java.io.*; import java.util.*; public class A { private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer st = null; private static int nextInt() throws IOException { return Integer.parseInt(next()); } private static String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public static void main(String[] args) throws IOException { int t = nextInt(); for (int q = 0; q < t; q++) { int n = nextInt(), m = nextInt(), r = nextInt(), c = nextInt(); System.out.println(Math.max(r - 1, n - r) + Math.max(c - 1, m - c)); } } }
Java
["3\n10 10 1 1\n3 5 2 4\n10 2 5 1"]
1 second
["18\n4\n6"]
null
Java 8
standard input
[ "brute force", "math" ]
3a3fbb61c7e1ccda69cd6d186da653ae
The first line contains an integer $$$t$$$ $$$(1 \le t \le 10^4)$$$, the number of test cases. Each of the next $$$t$$$ lines contains four space-separated integers $$$n$$$, $$$m$$$, $$$r$$$, $$$c$$$ ($$$1 \le r \le n \le 10^9$$$, $$$1 \le c \le m \le 10^9$$$).
null
Print $$$t$$$ lines, the answers for each test case.
standard output
PASSED
cfb7ff11471a802951b1efb27a0cd4ef
train_003.jsonl
1606633500
There is a prison that can be represented as a rectangular matrix with $$$n$$$ rows and $$$m$$$ columns. Therefore, there are $$$n \cdot m$$$ prison cells. There are also $$$n \cdot m$$$ prisoners, one in each prison cell. Let's denote the cell in the $$$i$$$-th row and the $$$j$$$-th column as $$$(i, j)$$$.There's a secret tunnel in the cell $$$(r, c)$$$, that the prisoners will use to escape! However, to avoid the risk of getting caught, they will escape at night.Before the night, every prisoner is in his own cell. When night comes, they can start moving to adjacent cells. Formally, in one second, a prisoner located in cell $$$(i, j)$$$ can move to cells $$$( i - 1 , j )$$$ , $$$( i + 1 , j )$$$ , $$$( i , j - 1 )$$$ , or $$$( i , j + 1 )$$$, as long as the target cell is inside the prison. They can also choose to stay in cell $$$(i, j)$$$.The prisoners want to know the minimum number of seconds needed so that every prisoner can arrive to cell $$$( r , c )$$$ if they move optimally. Note that there can be any number of prisoners in the same cell at the same time.
256 megabytes
import java.util.Scanner; public class PrisionBreak { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); int m = sc.nextInt(); int r = sc.nextInt(); int c = sc.nextInt(); System.out.println(Math.max(r-1, n-r)+Math.max(c-1, m-c)); } } }
Java
["3\n10 10 1 1\n3 5 2 4\n10 2 5 1"]
1 second
["18\n4\n6"]
null
Java 8
standard input
[ "brute force", "math" ]
3a3fbb61c7e1ccda69cd6d186da653ae
The first line contains an integer $$$t$$$ $$$(1 \le t \le 10^4)$$$, the number of test cases. Each of the next $$$t$$$ lines contains four space-separated integers $$$n$$$, $$$m$$$, $$$r$$$, $$$c$$$ ($$$1 \le r \le n \le 10^9$$$, $$$1 \le c \le m \le 10^9$$$).
null
Print $$$t$$$ lines, the answers for each test case.
standard output
PASSED
6e64bb05a9080474e6d7c807bcbc4820
train_003.jsonl
1606633500
There is a prison that can be represented as a rectangular matrix with $$$n$$$ rows and $$$m$$$ columns. Therefore, there are $$$n \cdot m$$$ prison cells. There are also $$$n \cdot m$$$ prisoners, one in each prison cell. Let's denote the cell in the $$$i$$$-th row and the $$$j$$$-th column as $$$(i, j)$$$.There's a secret tunnel in the cell $$$(r, c)$$$, that the prisoners will use to escape! However, to avoid the risk of getting caught, they will escape at night.Before the night, every prisoner is in his own cell. When night comes, they can start moving to adjacent cells. Formally, in one second, a prisoner located in cell $$$(i, j)$$$ can move to cells $$$( i - 1 , j )$$$ , $$$( i + 1 , j )$$$ , $$$( i , j - 1 )$$$ , or $$$( i , j + 1 )$$$, as long as the target cell is inside the prison. They can also choose to stay in cell $$$(i, j)$$$.The prisoners want to know the minimum number of seconds needed so that every prisoner can arrive to cell $$$( r , c )$$$ if they move optimally. Note that there can be any number of prisoners in the same cell at the same time.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class R687A { public static void main(String[] args) { // TODO Auto-generated method stub int t = scn.nextInt(); while (t > 0) { int n = scn.nextInt(); int m = scn.nextInt(); int r = scn.nextInt(); int c = scn.nextInt(); int tl = Math.abs(1 - r) + Math.abs(1 - c); int tr = Math.abs(1 - r) + Math.abs(m - c); int bl = Math.abs(n - r) + Math.abs(1 - c); int br = Math.abs(n - r) + Math.abs(c - m); int ans = Math.max(tl, Math.max(tr, Math.max(bl, br))); out.println(ans); t--; } out.close(); } static FastScanner scn = new FastScanner(); static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n10 10 1 1\n3 5 2 4\n10 2 5 1"]
1 second
["18\n4\n6"]
null
Java 8
standard input
[ "brute force", "math" ]
3a3fbb61c7e1ccda69cd6d186da653ae
The first line contains an integer $$$t$$$ $$$(1 \le t \le 10^4)$$$, the number of test cases. Each of the next $$$t$$$ lines contains four space-separated integers $$$n$$$, $$$m$$$, $$$r$$$, $$$c$$$ ($$$1 \le r \le n \le 10^9$$$, $$$1 \le c \le m \le 10^9$$$).
null
Print $$$t$$$ lines, the answers for each test case.
standard output
PASSED
1785a31bec101d4229b3e41a7112f47e
train_003.jsonl
1606633500
There is a prison that can be represented as a rectangular matrix with $$$n$$$ rows and $$$m$$$ columns. Therefore, there are $$$n \cdot m$$$ prison cells. There are also $$$n \cdot m$$$ prisoners, one in each prison cell. Let's denote the cell in the $$$i$$$-th row and the $$$j$$$-th column as $$$(i, j)$$$.There's a secret tunnel in the cell $$$(r, c)$$$, that the prisoners will use to escape! However, to avoid the risk of getting caught, they will escape at night.Before the night, every prisoner is in his own cell. When night comes, they can start moving to adjacent cells. Formally, in one second, a prisoner located in cell $$$(i, j)$$$ can move to cells $$$( i - 1 , j )$$$ , $$$( i + 1 , j )$$$ , $$$( i , j - 1 )$$$ , or $$$( i , j + 1 )$$$, as long as the target cell is inside the prison. They can also choose to stay in cell $$$(i, j)$$$.The prisoners want to know the minimum number of seconds needed so that every prisoner can arrive to cell $$$( r , c )$$$ if they move optimally. Note that there can be any number of prisoners in the same cell at the same time.
256 megabytes
import java.util.*; import java.lang.Math; public class A{ public static void main(String asfasaa[]){ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int m=sc.nextInt(); int r=sc.nextInt(); int c=sc.nextInt(); int s=Math.max(n-r,r-1)+Math.max(m-c,c-1); System.out.println(s); } } }
Java
["3\n10 10 1 1\n3 5 2 4\n10 2 5 1"]
1 second
["18\n4\n6"]
null
Java 8
standard input
[ "brute force", "math" ]
3a3fbb61c7e1ccda69cd6d186da653ae
The first line contains an integer $$$t$$$ $$$(1 \le t \le 10^4)$$$, the number of test cases. Each of the next $$$t$$$ lines contains four space-separated integers $$$n$$$, $$$m$$$, $$$r$$$, $$$c$$$ ($$$1 \le r \le n \le 10^9$$$, $$$1 \le c \le m \le 10^9$$$).
null
Print $$$t$$$ lines, the answers for each test case.
standard output
PASSED
c7b1773e17a24b653be084abb3271c9d
train_003.jsonl
1606633500
There is a prison that can be represented as a rectangular matrix with $$$n$$$ rows and $$$m$$$ columns. Therefore, there are $$$n \cdot m$$$ prison cells. There are also $$$n \cdot m$$$ prisoners, one in each prison cell. Let's denote the cell in the $$$i$$$-th row and the $$$j$$$-th column as $$$(i, j)$$$.There's a secret tunnel in the cell $$$(r, c)$$$, that the prisoners will use to escape! However, to avoid the risk of getting caught, they will escape at night.Before the night, every prisoner is in his own cell. When night comes, they can start moving to adjacent cells. Formally, in one second, a prisoner located in cell $$$(i, j)$$$ can move to cells $$$( i - 1 , j )$$$ , $$$( i + 1 , j )$$$ , $$$( i , j - 1 )$$$ , or $$$( i , j + 1 )$$$, as long as the target cell is inside the prison. They can also choose to stay in cell $$$(i, j)$$$.The prisoners want to know the minimum number of seconds needed so that every prisoner can arrive to cell $$$( r , c )$$$ if they move optimally. Note that there can be any number of prisoners in the same cell at the same time.
256 megabytes
import java.util.Arrays; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = Integer.parseInt(in.nextLine()); int[] result = new int[t]; for (int i = 0; i < t; i++) { List<String> data = Arrays.asList(in.nextLine().split(" ")); int n = Integer.parseInt(data.get(0)); int m = Integer.parseInt(data.get(1)); int r = Integer.parseInt(data.get(2)); int c = Integer.parseInt(data.get(3)); int max = 0; if(Math.abs(1-r) + Math.abs(1-c) > max) { max = Math.abs(1-r) + Math.abs(1-c); } if(Math.abs(n-r) + Math.abs(1-c) > max) { max = Math.abs(n-r) + Math.abs(1-c); } if(Math.abs(1-r) + Math.abs(m-c) > max) { max = Math.abs(1-r) + Math.abs(m-c); } if(Math.abs(n-r) + Math.abs(m-c) > max) { max = Math.abs(n-r) + Math.abs(m-c); } result[i] = max; } for (Integer res : result) { System.out.println(res.toString()); } } }
Java
["3\n10 10 1 1\n3 5 2 4\n10 2 5 1"]
1 second
["18\n4\n6"]
null
Java 8
standard input
[ "brute force", "math" ]
3a3fbb61c7e1ccda69cd6d186da653ae
The first line contains an integer $$$t$$$ $$$(1 \le t \le 10^4)$$$, the number of test cases. Each of the next $$$t$$$ lines contains four space-separated integers $$$n$$$, $$$m$$$, $$$r$$$, $$$c$$$ ($$$1 \le r \le n \le 10^9$$$, $$$1 \le c \le m \le 10^9$$$).
null
Print $$$t$$$ lines, the answers for each test case.
standard output
PASSED
a728abff91401d6a85d4d2fa33f291a0
train_003.jsonl
1606633500
There is a prison that can be represented as a rectangular matrix with $$$n$$$ rows and $$$m$$$ columns. Therefore, there are $$$n \cdot m$$$ prison cells. There are also $$$n \cdot m$$$ prisoners, one in each prison cell. Let's denote the cell in the $$$i$$$-th row and the $$$j$$$-th column as $$$(i, j)$$$.There's a secret tunnel in the cell $$$(r, c)$$$, that the prisoners will use to escape! However, to avoid the risk of getting caught, they will escape at night.Before the night, every prisoner is in his own cell. When night comes, they can start moving to adjacent cells. Formally, in one second, a prisoner located in cell $$$(i, j)$$$ can move to cells $$$( i - 1 , j )$$$ , $$$( i + 1 , j )$$$ , $$$( i , j - 1 )$$$ , or $$$( i , j + 1 )$$$, as long as the target cell is inside the prison. They can also choose to stay in cell $$$(i, j)$$$.The prisoners want to know the minimum number of seconds needed so that every prisoner can arrive to cell $$$( r , c )$$$ if they move optimally. Note that there can be any number of prisoners in the same cell at the same time.
256 megabytes
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class TaskA { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int cnt = scanner.nextInt(); List<Integer> list = new ArrayList<>(); for (int i = 0; i < cnt; i++) { int n = scanner.nextInt(); int m = scanner.nextInt(); int r = scanner.nextInt(); int c = scanner.nextInt(); int max = r-1+c-1; max = Math.max(max, r-1+c-1); max = Math.max(max, r-1+m-c); max = Math.max(max, n-r+c-1); max = Math.max(max, n-r+m-c); list.add(max); } list.forEach(max -> System.out.println(max)); } }
Java
["3\n10 10 1 1\n3 5 2 4\n10 2 5 1"]
1 second
["18\n4\n6"]
null
Java 8
standard input
[ "brute force", "math" ]
3a3fbb61c7e1ccda69cd6d186da653ae
The first line contains an integer $$$t$$$ $$$(1 \le t \le 10^4)$$$, the number of test cases. Each of the next $$$t$$$ lines contains four space-separated integers $$$n$$$, $$$m$$$, $$$r$$$, $$$c$$$ ($$$1 \le r \le n \le 10^9$$$, $$$1 \le c \le m \le 10^9$$$).
null
Print $$$t$$$ lines, the answers for each test case.
standard output
PASSED
8bc3c3dcc1caf31247c7fcac591a6384
train_003.jsonl
1606633500
There is a prison that can be represented as a rectangular matrix with $$$n$$$ rows and $$$m$$$ columns. Therefore, there are $$$n \cdot m$$$ prison cells. There are also $$$n \cdot m$$$ prisoners, one in each prison cell. Let's denote the cell in the $$$i$$$-th row and the $$$j$$$-th column as $$$(i, j)$$$.There's a secret tunnel in the cell $$$(r, c)$$$, that the prisoners will use to escape! However, to avoid the risk of getting caught, they will escape at night.Before the night, every prisoner is in his own cell. When night comes, they can start moving to adjacent cells. Formally, in one second, a prisoner located in cell $$$(i, j)$$$ can move to cells $$$( i - 1 , j )$$$ , $$$( i + 1 , j )$$$ , $$$( i , j - 1 )$$$ , or $$$( i , j + 1 )$$$, as long as the target cell is inside the prison. They can also choose to stay in cell $$$(i, j)$$$.The prisoners want to know the minimum number of seconds needed so that every prisoner can arrive to cell $$$( r , c )$$$ if they move optimally. Note that there can be any number of prisoners in the same cell at the same time.
256 megabytes
import java.awt.event.MouseAdapter; import java.io.*; import java.lang.reflect.Array; import java.util.StringTokenizer; import java.util.*; public class Main { public static void main(String[] args) throws IOException { int t = nextInt(); for (int i = 0; i < t; i++) { int n = nextInt(); int m = nextInt(); int r= nextInt(); int c = nextInt(); int x = 1; int y = 1; if (c-1<m-c) x =m; if (r-1<n-r) y =n; out.println(Math.abs(x-c)+Math.abs(y-r)); } out.close(); } // private static boolean hasNext() throws IOException { // if (in.hasMoreTokens()) return true; // String s; // while ((s =br.readLine()) != null) { // in = new StringTokenizer(s); // if (in.hasMoreTokens()) return true; // } // return false; // } // static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter out = new PrintWriter(System.out); // static BufferedReader br; // // static { // try { // br = new BufferedReader(new FileReader("string.in")); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } // } // // static PrintWriter out; // // static { // try { // out = new PrintWriter("string.out"); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } // } public static String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } static StringTokenizer in = new StringTokenizer(""); public static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public static long nextLong() throws IOException { return Long.parseLong(nextToken()); } }
Java
["3\n10 10 1 1\n3 5 2 4\n10 2 5 1"]
1 second
["18\n4\n6"]
null
Java 8
standard input
[ "brute force", "math" ]
3a3fbb61c7e1ccda69cd6d186da653ae
The first line contains an integer $$$t$$$ $$$(1 \le t \le 10^4)$$$, the number of test cases. Each of the next $$$t$$$ lines contains four space-separated integers $$$n$$$, $$$m$$$, $$$r$$$, $$$c$$$ ($$$1 \le r \le n \le 10^9$$$, $$$1 \le c \le m \le 10^9$$$).
null
Print $$$t$$$ lines, the answers for each test case.
standard output
PASSED
35da4f6065300b40591b40cd72d39cb6
train_003.jsonl
1606633500
There is a prison that can be represented as a rectangular matrix with $$$n$$$ rows and $$$m$$$ columns. Therefore, there are $$$n \cdot m$$$ prison cells. There are also $$$n \cdot m$$$ prisoners, one in each prison cell. Let's denote the cell in the $$$i$$$-th row and the $$$j$$$-th column as $$$(i, j)$$$.There's a secret tunnel in the cell $$$(r, c)$$$, that the prisoners will use to escape! However, to avoid the risk of getting caught, they will escape at night.Before the night, every prisoner is in his own cell. When night comes, they can start moving to adjacent cells. Formally, in one second, a prisoner located in cell $$$(i, j)$$$ can move to cells $$$( i - 1 , j )$$$ , $$$( i + 1 , j )$$$ , $$$( i , j - 1 )$$$ , or $$$( i , j + 1 )$$$, as long as the target cell is inside the prison. They can also choose to stay in cell $$$(i, j)$$$.The prisoners want to know the minimum number of seconds needed so that every prisoner can arrive to cell $$$( r , c )$$$ if they move optimally. Note that there can be any number of prisoners in the same cell at the same time.
256 megabytes
//SHIVAM GARG import java.util.*; import java.lang.*; import java.io.*; public class Codechef { public static HashMap<Integer, Integer> tracker; public static void main (String[] args) throws java.lang.Exception { FastReader reader = new FastReader(); int tests = reader.nextInt(); for(int test =0; test < tests; test++){ int n = reader.nextInt(); int m = reader.nextInt(); int x = reader.nextInt(); int y = reader.nextInt(); System.out.println( Math.max(x-1, n-x ) + Math.max(y-1, m-y ) ); } } static int[] primes; public static void sieve(){ primes = new int[100002]; // 0 means prime and 1 means Not prime int temp = 2; while(temp < primes.length ){ primes[temp] = 1; temp = temp+2; } primes[2] = 0; for(int i = 3; i < primes.length; i = i+2){ if(primes[i] == 0 ){ temp = i+i; while(temp < primes.length ){ primes[temp] = 1; temp = temp+i; } } } } public static HashMap<Integer, Integer> getFactors(long n){ long ori = n; HashMap<Integer, Integer> factors = new HashMap<Integer, Integer>(); int temp =0; while(n % 2 == 0 ){ temp++; n = n/2; } if(temp >0){ factors.put(2, temp); // System.out.println( ori+" ==> " + 2 +" :: " + temp); } long sqrt = (long) Math.sqrt(n); for(int i= 3;(i <= sqrt) && i<=n ; i = i+2){ if(primes[i] == 0 ){ temp = 0; while(n % i == 0 ){ temp++; n = n/i; } if(temp > 0){ // System.out.println( ori+" ==> " + i +" :: " + temp); factors.put(i, temp); } } } return factors; } /* Iterative Function to calculate (x^y)%p in O(log y) */ public static long prime = 1000000007; public static long[] fact; static long power(long x, long y) { // Initialize result long res = 1; // Update x if it is more than or // equal to p x = x % prime; while (y > 0) { // If y is odd, multiply x with result if (y % 2 == 1) res = (res * x) % prime; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % prime; } return res; } // Returns n^(-1) mod p static long modInverse(long n) { return power(n, prime-2); } // Returns nCr % p using Fermat's little theorem. static long nCrModPFermat(int n, int r) { // Base case if (r == 0) return 1; long a1 = fact[n]; long a2 = modInverse(fact[r]) % prime; long a3 = modInverse(fact[n-r]) % prime; return ((fact[n] * a2)%prime * a3) % prime; } 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()); } int[] nextIntArray(int n){ int[] arr = new int[n]; for(int ii=0; ii<n; ii++){ arr[ii] = this.nextInt(); } return arr; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try{ str = br.readLine(); } catch (IOException e) { //e.printStackTrace(); } return str; } } }
Java
["3\n10 10 1 1\n3 5 2 4\n10 2 5 1"]
1 second
["18\n4\n6"]
null
Java 8
standard input
[ "brute force", "math" ]
3a3fbb61c7e1ccda69cd6d186da653ae
The first line contains an integer $$$t$$$ $$$(1 \le t \le 10^4)$$$, the number of test cases. Each of the next $$$t$$$ lines contains four space-separated integers $$$n$$$, $$$m$$$, $$$r$$$, $$$c$$$ ($$$1 \le r \le n \le 10^9$$$, $$$1 \le c \le m \le 10^9$$$).
null
Print $$$t$$$ lines, the answers for each test case.
standard output
PASSED
4b8b1bddcb4f9ff6391a17da8464baad
train_003.jsonl
1592921100
Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"...The game is a one versus one game. It has $$$t$$$ rounds, each round has two integers $$$s_i$$$ and $$$e_i$$$ (which are determined and are known before the game begins, $$$s_i$$$ and $$$e_i$$$ may differ from round to round). The integer $$$s_i$$$ is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was $$$a$$$) and will choose to write either $$$2 \cdot a$$$ or $$$a + 1$$$ instead. Whoever writes a number strictly greater than $$$e_i$$$ loses that round and the other one wins that round.Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's $$$s_i$$$ and $$$e_i$$$ in advance. Lee will start the first round, the loser of each round will start the next round.The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game.Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not.
256 megabytes
// upsolve with kaiboy, coached by rainboy import java.io.*; import java.util.*; public class CF1369F extends PrintWriter { CF1369F() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1369F o = new CF1369F(); o.main(); o.flush(); } int test(long a, long b, int x, int e) { return e == 0 ? 1 : (int) (b - a & 1) ^ x; } int solve(long a, long b, int x, int e) { while (true) { if (a == b) return x; long b_ = b / 2; if (a > b_) return test(a, b, x, e); int x1 = test(b_ + 1, b, x, e); int x2 = test(b_ * 2, b, x, e); x = x1 & x2 ^ 1; e = x2; b = b_; } } int can_win(long a, long b) { return solve(a, b, 0, 1); } int can_lose(long a, long b) { return solve(a, b, 1, 0); } void main() { int n = sc.nextInt(); long[] aa = new long[n]; long[] bb = new long[n]; for (int i = 0; i < n; i++) { aa[i] = sc.nextLong(); bb[i] = sc.nextLong(); } long a = aa[n - 1], b = bb[n - 1]; int w_ = can_win(a, b); int l_ = can_lose(a, b); for (int i = n - 2; i >= 0; i--) { a = aa[i]; b = bb[i]; int w = can_win(a, b); int l = can_lose(a, b); int w2 = l & w_ | w & (w_ ^ 1); int l2 = l & l_ | w & (l_ ^ 1); w_ = w2; l_ = l2; } println(w_ + " " + l_); } }
Java
["3\n5 8\n1 4\n3 10", "4\n1 2\n2 3\n3 4\n4 5", "1\n1 1", "2\n1 9\n4 5", "2\n1 2\n2 8", "6\n216986951114298167 235031205335543871\n148302405431848579 455670351549314242\n506251128322958430 575521452907339082\n1 768614336404564650\n189336074809158272 622104412002885672\n588320087414024192 662540324268197150"]
2 seconds
["1 1", "0 0", "0 1", "0 0", "1 0", "1 0"]
NoteRemember, whoever writes an integer greater than $$$e_i$$$ loses.
Java 11
standard input
[ "dp", "dfs and similar", "games" ]
a0376bf145f4d9b5fbc1683956c203df
The first line contains the integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of rounds the game has. Then $$$t$$$ lines follow, each contains two integers $$$s_i$$$ and $$$e_i$$$ ($$$1 \le s_i \le e_i \le 10^{18}$$$) — the $$$i$$$-th round's information. The rounds are played in the same order as given in input, $$$s_i$$$ and $$$e_i$$$ for all rounds are known to everyone before the game starts.
2,700
Print two integers. The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise. The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise.
standard output
PASSED
b21e9472fd8177dcf4ac50cdebce1129
train_003.jsonl
1592921100
Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"...The game is a one versus one game. It has $$$t$$$ rounds, each round has two integers $$$s_i$$$ and $$$e_i$$$ (which are determined and are known before the game begins, $$$s_i$$$ and $$$e_i$$$ may differ from round to round). The integer $$$s_i$$$ is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was $$$a$$$) and will choose to write either $$$2 \cdot a$$$ or $$$a + 1$$$ instead. Whoever writes a number strictly greater than $$$e_i$$$ loses that round and the other one wins that round.Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's $$$s_i$$$ and $$$e_i$$$ in advance. Lee will start the first round, the loser of each round will start the next round.The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game.Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class F { static final boolean RUN_TIMING = false; static char[] inputBuffer = new char[1 << 20]; static PushbackReader in = new PushbackReader(new BufferedReader(new InputStreamReader(System.in)), 1 << 20); static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); public void go() throws IOException { // in = new PushbackReader(new BufferedReader(new FileReader(new File("test.txt"))), 1 << 20); // out = new PrintWriter(new FileWriter(new File("output.txt"))); // int test = 256; // out.println(Integer.toBinaryString(test)); // for (int i = 1; i <= test; i++) { // out.print(win(i, test) ? 1 : 0); // if (group(i, test) != group(i+1, test)) { // out.println(); // } // } // out.println(); // for (int i = 1; i <= test; i++) { // out.print(winSlow(i, test) ? 1 : 0); // if (group(i, test) != group(i+1, test)) { // out.println(); // } // } // out.println(); int n = ipar(); boolean[] state = {false, true}; for (int i = 0; i < n; i++) { // out.printf(" %d %d%n", state[0] ? 1 : 0, state[1] ? 1 : 0); if (!state[0] && !state[1]) { break; } long s = lpar(); long e = lpar(); boolean[] next = {false, false}; if (state[0]) { next[0] |= !win(s, e); next[1] |= s <= e/2 && !win(s, e/2); } if (state[1]) { next[0] |= win(s, e); next[1] |= s > e/2 || win(s, e/2); } state = next; } out.printf("%d %d%n", state[0] ? 1 : 0, state[1] ? 1 : 0); } public boolean win(long s, long e) { if (e % 2 == 1) { return s % 2 == 0; } if (s*2 > e) { return s % 2 == 1; } if (s*2 > e/2) { return true; } return win(s, e/4); } public boolean winSlow(long s, long e) { if (e % 2 == 1) { return s % 2 == 0; } if (s == e) { return false; } if (s*2 <= e && !winSlow(s*2, e)) { return true; } if (s+1 <= e && !winSlow(s+1, e)) { return true; } return false; } public int group(long s, long e) { int g = 0; while (s <= e) { g++; s *= 2; } return g; } public int ipar() throws IOException { return Integer.parseInt(spar()); } public int[] iapar(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = ipar(); } return arr; } public long lpar() throws IOException { return Long.parseLong(spar()); } public long[] lapar(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = lpar(); } return arr; } public double dpar() throws IOException { return Double.parseDouble(spar()); } public String spar() throws IOException { int len = 0; int c; do { c = in.read(); } while (Character.isWhitespace(c) && c != -1); if (c == -1) { throw new NoSuchElementException("Reached EOF"); } do { inputBuffer[len] = (char)c; len++; c = in.read(); } while (!Character.isWhitespace(c) && c != -1); while (c != '\n' && Character.isWhitespace(c) && c != -1) { c = in.read(); } if (c != -1 && c != '\n') { in.unread(c); } return new String(inputBuffer, 0, len); } public String linepar() throws IOException { int len = 0; int c; while ((c = in.read()) != '\n' && c != -1) { if (c == '\r') { continue; } inputBuffer[len] = (char)c; len++; } return new String(inputBuffer, 0, len); } public boolean haspar() throws IOException { String line = linepar(); if (line.isEmpty()) { return false; } in.unread('\n'); in.unread(line.toCharArray()); return true; } public static void main(String[] args) throws IOException { long time = 0; time -= System.nanoTime(); new F().go(); time += System.nanoTime(); if (RUN_TIMING) { System.out.printf("%.3f ms%n", time / 1000000.0); } out.flush(); in.close(); } }
Java
["3\n5 8\n1 4\n3 10", "4\n1 2\n2 3\n3 4\n4 5", "1\n1 1", "2\n1 9\n4 5", "2\n1 2\n2 8", "6\n216986951114298167 235031205335543871\n148302405431848579 455670351549314242\n506251128322958430 575521452907339082\n1 768614336404564650\n189336074809158272 622104412002885672\n588320087414024192 662540324268197150"]
2 seconds
["1 1", "0 0", "0 1", "0 0", "1 0", "1 0"]
NoteRemember, whoever writes an integer greater than $$$e_i$$$ loses.
Java 11
standard input
[ "dp", "dfs and similar", "games" ]
a0376bf145f4d9b5fbc1683956c203df
The first line contains the integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of rounds the game has. Then $$$t$$$ lines follow, each contains two integers $$$s_i$$$ and $$$e_i$$$ ($$$1 \le s_i \le e_i \le 10^{18}$$$) — the $$$i$$$-th round's information. The rounds are played in the same order as given in input, $$$s_i$$$ and $$$e_i$$$ for all rounds are known to everyone before the game starts.
2,700
Print two integers. The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise. The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise.
standard output
PASSED
9dea083b45a36f4b9dfbbb1dbdbe9e5b
train_003.jsonl
1592921100
Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"...The game is a one versus one game. It has $$$t$$$ rounds, each round has two integers $$$s_i$$$ and $$$e_i$$$ (which are determined and are known before the game begins, $$$s_i$$$ and $$$e_i$$$ may differ from round to round). The integer $$$s_i$$$ is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was $$$a$$$) and will choose to write either $$$2 \cdot a$$$ or $$$a + 1$$$ instead. Whoever writes a number strictly greater than $$$e_i$$$ loses that round and the other one wins that round.Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's $$$s_i$$$ and $$$e_i$$$ in advance. Lee will start the first round, the loser of each round will start the next round.The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game.Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not.
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.StringTokenizer; public class F { public static void main(String[] args) { FastScanner fs=new FastScanner(); int rounds=fs.nextInt(); long[] small=new long[rounds]; long[] big=new long[rounds]; for (int i=0; i<rounds; i++) { small[i]=fs.nextLong(); big[i]=fs.nextLong(); } boolean canWin=false; boolean canLose=true; for (int r=rounds-1; r>=0; r--) { boolean winNow=play(big[r], small[r], false); boolean loseNow=play(big[r], small[r], true); boolean nextWin=(canWin&&loseNow) || (winNow && !canWin); boolean nextLose=(canLose&&loseNow) || (winNow && !canLose); canWin=nextWin; canLose=nextLose; } System.out.println((canWin?'1':'0')+" "+(canLose?"1":"0")); } //returns whether small is a one static boolean play(long big, long small, boolean startOnes) { if (big%2==1 && !startOnes) { //alternates forever return (big-small)%2!=0; } else if (!startOnes && big%2==0) { long half=big/2; if (small>half) { return (big-small)%2!=0; } else { return play(half, small, true); } } //TODO: handle last case if (startOnes) { //startOnes assumes that odd above is all zero long nextRelevant=big/2; if (small>nextRelevant) { return true; } else { return play(nextRelevant, small, false); } } throw null; } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n5 8\n1 4\n3 10", "4\n1 2\n2 3\n3 4\n4 5", "1\n1 1", "2\n1 9\n4 5", "2\n1 2\n2 8", "6\n216986951114298167 235031205335543871\n148302405431848579 455670351549314242\n506251128322958430 575521452907339082\n1 768614336404564650\n189336074809158272 622104412002885672\n588320087414024192 662540324268197150"]
2 seconds
["1 1", "0 0", "0 1", "0 0", "1 0", "1 0"]
NoteRemember, whoever writes an integer greater than $$$e_i$$$ loses.
Java 11
standard input
[ "dp", "dfs and similar", "games" ]
a0376bf145f4d9b5fbc1683956c203df
The first line contains the integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of rounds the game has. Then $$$t$$$ lines follow, each contains two integers $$$s_i$$$ and $$$e_i$$$ ($$$1 \le s_i \le e_i \le 10^{18}$$$) — the $$$i$$$-th round's information. The rounds are played in the same order as given in input, $$$s_i$$$ and $$$e_i$$$ for all rounds are known to everyone before the game starts.
2,700
Print two integers. The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise. The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise.
standard output
PASSED
6bbd86e4fe30ce347abc199c9eb7fbd2
train_003.jsonl
1592921100
Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"...The game is a one versus one game. It has $$$t$$$ rounds, each round has two integers $$$s_i$$$ and $$$e_i$$$ (which are determined and are known before the game begins, $$$s_i$$$ and $$$e_i$$$ may differ from round to round). The integer $$$s_i$$$ is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was $$$a$$$) and will choose to write either $$$2 \cdot a$$$ or $$$a + 1$$$ instead. Whoever writes a number strictly greater than $$$e_i$$$ loses that round and the other one wins that round.Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's $$$s_i$$$ and $$$e_i$$$ in advance. Lee will start the first round, the loser of each round will start the next round.The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game.Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not.
256 megabytes
//package round652; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class F { InputStream is; PrintWriter out; String INPUT = ""; void solve() { // e s // for(int i = 10;i < 1000;i++){ // boolean[] win = new boolean[i+1]; // for(int j = i;j >= 0;j--){ // win[j] = !((j*2 > i ? true : win[j*2]) && (j+1 > i ? true : win[j+1])); // } // boolean[] aa = new boolean[i+1]; // for(int j = i;j > 0;j--){ // aa[j] = fw(j, i); // } // tr(i); // tf(win); // tf(aa); // for(int j = 1;j <= i;j++){ // assert aa[j] == win[j]; // } // } // for(int i = 1;i < 120;i++){ // boolean[] win = new boolean[i+1]; // for(int j = i;j >= 0;j--){ // win[j] = !((j*2 > i ? false : win[j*2]) && (j+1 > i ? false : win[j+1])); // tr(i, j); // if(j > 0)assert win[j] == fl(j, i); // } // boolean[] aa = new boolean[i+1]; // for(int j = i;j > 0;j--){ // aa[j] = fl(j, i); // } // tr(i); // tf(win); // tf(aa); // } int n = ni(); boolean[] fw = new boolean[n]; boolean[] fl = new boolean[n]; for(int i = 0;i < n;i++){ long S = nl(), E = nl(); fw[i] = fw(S, E); fl[i] = fl(S, E); } { boolean win = true, lose = false; for(int i = n-1;i >= 0;i--){ boolean plose = false; boolean pwin = false; if(fw[i] && win){ plose = true; } if(!fw[i] && win){ pwin = true; } if(fl[i] && lose){ plose = true; } if(!fl[i] && lose){ pwin = true; } lose = plose; win = pwin; } if(lose){ out.print(1); }else{ out.print(0); } } out.print(" "); { boolean win = false, lose = true; for(int i = n-1;i >= 0;i--){ boolean plose = false; boolean pwin = false; if(fw[i] && win){ plose = true; } if(!fw[i] && win){ pwin = true; } if(fl[i] && lose){ plose = true; } if(!fl[i] && lose){ pwin = true; } lose = plose; win = pwin; } if(lose){ out.print(1); }else{ out.print(0); } } out.println(); } boolean fw(long S, long E) { int p = 0; for(;;p ^= 1, E/=2){ if(p == 0 && E % 2 == 1){ return (E-S) % 2 == 1; } if(S >= E/2+1){ return p == 1 || (E-S) % 2 == 1; } } } boolean fl(long S, long E) { for(int p = 0;;p ^= 1, E/=2){ if(p == 1 && E % 2 == 1){ return (E-S) % 2 == 1; } if(S >= E/2+1){ return p == 0 || (E-S) % 2 == 1; } } } public static void tf(boolean... r) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } public static void tf(boolean[]... b) { for(boolean[] r : b) { for(boolean x : r)System.out.print(x?'#':'.'); System.out.println(); } System.out.println(); } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new F().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["3\n5 8\n1 4\n3 10", "4\n1 2\n2 3\n3 4\n4 5", "1\n1 1", "2\n1 9\n4 5", "2\n1 2\n2 8", "6\n216986951114298167 235031205335543871\n148302405431848579 455670351549314242\n506251128322958430 575521452907339082\n1 768614336404564650\n189336074809158272 622104412002885672\n588320087414024192 662540324268197150"]
2 seconds
["1 1", "0 0", "0 1", "0 0", "1 0", "1 0"]
NoteRemember, whoever writes an integer greater than $$$e_i$$$ loses.
Java 11
standard input
[ "dp", "dfs and similar", "games" ]
a0376bf145f4d9b5fbc1683956c203df
The first line contains the integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of rounds the game has. Then $$$t$$$ lines follow, each contains two integers $$$s_i$$$ and $$$e_i$$$ ($$$1 \le s_i \le e_i \le 10^{18}$$$) — the $$$i$$$-th round's information. The rounds are played in the same order as given in input, $$$s_i$$$ and $$$e_i$$$ for all rounds are known to everyone before the game starts.
2,700
Print two integers. The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise. The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise.
standard output
PASSED
82c38993241e4959f5c8c60521418dfc
train_003.jsonl
1592921100
Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"...The game is a one versus one game. It has $$$t$$$ rounds, each round has two integers $$$s_i$$$ and $$$e_i$$$ (which are determined and are known before the game begins, $$$s_i$$$ and $$$e_i$$$ may differ from round to round). The integer $$$s_i$$$ is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was $$$a$$$) and will choose to write either $$$2 \cdot a$$$ or $$$a + 1$$$ instead. Whoever writes a number strictly greater than $$$e_i$$$ loses that round and the other one wins that round.Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's $$$s_i$$$ and $$$e_i$$$ in advance. Lee will start the first round, the loser of each round will start the next round.The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game.Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayDeque; import java.util.Queue; public class Main { public static void main(final String[] args) throws Exception { final FastScanner scanner = new FastScanner(); final Solution solver = new Solution(); // main logic long[][] pairs = new long[scanner.nextInt()][2]; for (int i = 0; i < pairs.length; ++i) { pairs[i][0] = scanner.nextLong(); pairs[i][1] = scanner.nextLong(); } boolean[] res = solver.solve(pairs); System.out.print(res[0] ? 1 : 0); System.out.print(' '); System.out.print(res[1] ? 1 : 0); } } class Solution { public boolean[] solve(long[][] pairs) { boolean sureWin = false; boolean sureLose = true; for (long[] pair : pairs) { if (sureWin == sureLose) { break; } if (sureLose) { sureWin = canSureWin(pair[0], pair[1]); sureLose = canSureLose(pair[0], pair[1]); } else { sureWin = !canSureWin(pair[0], pair[1]); sureLose = !canSureLose(pair[0], pair[1]); } } return new boolean[] { sureWin, sureLose }; } private boolean canSureWin(final long start, final long end) { if (start == end) { return false; } if (end % 2 == 1) { return start % 2 == 0; } if (end < 2 * start) { return start % 2 == 1; } if (end < 4 * start) { return true; } return canSureWin(start, end / 4); } private boolean canSureLose(final long start, final long end) { return end < 2 * start || canSureWin(start, end / 2); } } class FastScanner { private final BufferedReader reader; private final Queue<String> queue; public FastScanner() { this.reader = new BufferedReader(new InputStreamReader(System.in)); this.queue = new ArrayDeque<>(); } public String next() throws Exception { if (queue.isEmpty()) { final String line = reader.readLine(); for (final String word : line.split(" ")) { queue.offer(word); } } return queue.poll(); } public int nextInt() throws Exception { return Integer.parseInt(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } }
Java
["3\n5 8\n1 4\n3 10", "4\n1 2\n2 3\n3 4\n4 5", "1\n1 1", "2\n1 9\n4 5", "2\n1 2\n2 8", "6\n216986951114298167 235031205335543871\n148302405431848579 455670351549314242\n506251128322958430 575521452907339082\n1 768614336404564650\n189336074809158272 622104412002885672\n588320087414024192 662540324268197150"]
2 seconds
["1 1", "0 0", "0 1", "0 0", "1 0", "1 0"]
NoteRemember, whoever writes an integer greater than $$$e_i$$$ loses.
Java 11
standard input
[ "dp", "dfs and similar", "games" ]
a0376bf145f4d9b5fbc1683956c203df
The first line contains the integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of rounds the game has. Then $$$t$$$ lines follow, each contains two integers $$$s_i$$$ and $$$e_i$$$ ($$$1 \le s_i \le e_i \le 10^{18}$$$) — the $$$i$$$-th round's information. The rounds are played in the same order as given in input, $$$s_i$$$ and $$$e_i$$$ for all rounds are known to everyone before the game starts.
2,700
Print two integers. The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise. The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise.
standard output
PASSED
8f1719f5bf735aa19a2f7c2d3cea5c5f
train_003.jsonl
1592921100
Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"...The game is a one versus one game. It has $$$t$$$ rounds, each round has two integers $$$s_i$$$ and $$$e_i$$$ (which are determined and are known before the game begins, $$$s_i$$$ and $$$e_i$$$ may differ from round to round). The integer $$$s_i$$$ is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was $$$a$$$) and will choose to write either $$$2 \cdot a$$$ or $$$a + 1$$$ instead. Whoever writes a number strictly greater than $$$e_i$$$ loses that round and the other one wins that round.Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's $$$s_i$$$ and $$$e_i$$$ in advance. Lee will start the first round, the loser of each round will start the next round.The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game.Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not.
256 megabytes
import java.io.*; import java.util.*; public class SolutionF { static Random random; static boolean benchmark = false; static long timeStamp; public static void main(String[] args) { FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); random = new Random(); if(benchmark) timeStamp = System.currentTimeMillis(); Solver solver = new Solver(); solver.solve(in, out); out.close(); if(benchmark) System.err.println("\033[0;31m"+(System.currentTimeMillis()-timeStamp)+" ms"+"\033[0m"); } /* ------------------------------------- START -------------------------------------------- */ static class Solver { public void solve(FastScanner in, PrintWriter out) { int n = in.nextInt(); long [] L = new long[n], R = new long[n]; for(int i = 0; i<n; i++){ L[i] = in.nextLong(); R[i] = in.nextLong(); } out.print(getAnsFor(true, L, R)? 1 : 0); out.print(' '); out.println(getAnsFor(false, L, R)? 1 : 0); } private boolean getAnsFor(boolean win, long[] L, long[] R) { for(int i = R.length-1; i>=0; i--){ long r = R[i], l = R[i]/2 + 1; boolean allWin = !win; while(l > L[i]){ // new Debugger().d("inter. range", l, r).d("allwin", allWin).d(); if(allWin) allWin = false; else if(r % 2 == 0) allWin = true; else { allWin = false; if(l % 2 == 1) l++; } r = l-1; l = r/2+1; } win = (allWin || (r % 2 != L[i] %2)); // new Debugger().d("range", L[i], R[i]).d("win", win).d(); win = !win; } return !win; } } /* -------------------------------------- END --------------------------------------------- */ /* Shuffle function to shuffle before Arrays.sort */ static void shuffle(int[] arr){ int swapTemp; for(int i = arr.length-1; i>= 1; i--){ int pos = random.nextInt(i+1); if(pos == i) continue; {swapTemp = arr[i]; arr[i] = arr[pos]; arr[pos] = swapTemp;} } } /* Fast Input reader */ static class FastScanner { BufferedReader reader; StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = new StringTokenizer(""); } String next() { while (!tokenizer.hasMoreTokens()) { try{ tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return tokenizer.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String nextLine() { String string = ""; try { string = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return string; } } }
Java
["3\n5 8\n1 4\n3 10", "4\n1 2\n2 3\n3 4\n4 5", "1\n1 1", "2\n1 9\n4 5", "2\n1 2\n2 8", "6\n216986951114298167 235031205335543871\n148302405431848579 455670351549314242\n506251128322958430 575521452907339082\n1 768614336404564650\n189336074809158272 622104412002885672\n588320087414024192 662540324268197150"]
2 seconds
["1 1", "0 0", "0 1", "0 0", "1 0", "1 0"]
NoteRemember, whoever writes an integer greater than $$$e_i$$$ loses.
Java 11
standard input
[ "dp", "dfs and similar", "games" ]
a0376bf145f4d9b5fbc1683956c203df
The first line contains the integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of rounds the game has. Then $$$t$$$ lines follow, each contains two integers $$$s_i$$$ and $$$e_i$$$ ($$$1 \le s_i \le e_i \le 10^{18}$$$) — the $$$i$$$-th round's information. The rounds are played in the same order as given in input, $$$s_i$$$ and $$$e_i$$$ for all rounds are known to everyone before the game starts.
2,700
Print two integers. The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise. The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise.
standard output
PASSED
9f8115300649bc74e8a2c16ee083047e
train_003.jsonl
1592921100
Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"...The game is a one versus one game. It has $$$t$$$ rounds, each round has two integers $$$s_i$$$ and $$$e_i$$$ (which are determined and are known before the game begins, $$$s_i$$$ and $$$e_i$$$ may differ from round to round). The integer $$$s_i$$$ is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was $$$a$$$) and will choose to write either $$$2 \cdot a$$$ or $$$a + 1$$$ instead. Whoever writes a number strictly greater than $$$e_i$$$ loses that round and the other one wins that round.Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's $$$s_i$$$ and $$$e_i$$$ in advance. Lee will start the first round, the loser of each round will start the next round.The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game.Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Queue; import java.util.Random; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; public class Main { public static void main(String[] args){ new Thread(null, null, "Anshum Gupta", 99999999) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static final long mxx = (long)(1e18 + 5); static final int mxN = (int)(1e6); static final int mxV = (int)(1e6), log = 18; static final long MOD = 998244353; static final int INF = (int)1e9; static boolean[]vis; static ArrayList<ArrayList<Integer>> adj; static int n, m, q, k; static char[]str; public static void solve() throws Exception { // solve the problem here s = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out), true); // out = new PrintWriter("output.txt"); int tc = 1;//s.nextInt(); for(int i=1; i<=tc; i++) { // out.print("Case #" + i + ": "); testcase(); } out.flush(); out.close(); } static void testcase() { int numRounds = s.nextInt(); long[] starts = new long[numRounds], ends = new long[numRounds]; for(int i = 0; i < numRounds; i++) { starts[i] = s.nextLong(); ends[i] = s.nextLong(); } int win = 1, lose = 0; for(int i = 0; i < numRounds; i++) { if((win == 1 && lose == 1) || (win == 0 && lose == 0))break; int curWin = playWin(starts[i], ends[i]) ? 1 : 0, curLose = playLose(starts[i], ends[i]) ? 1 : 0; if(lose == 1) { curWin ^= 1; curLose ^= 1; } win = curLose; lose = curWin; } out.println(lose + " " + win); } // check if static boolean playWin(long s, long e) { if(e == s)return false; if(e == s + 1)return true; if(e % 2 != 0) return s % 2 == 0; else { if(s <= e / 4) return playWin(s, e / 4); if(s > e / 2) return (e - s) % 2 == 1; return true; } } static boolean playLose(long s, long e) { if(s > e / 2) return true; return playWin(s, e / 2); } public static PrintWriter out; public static MyScanner s; static void shuffleArray(int[] a) { Random random = new Random(); for (int i = a.length-1; i > 0; i--) { int index = random.nextInt(i + 1); int tmp = a[index]; a[index] = a[i]; a[i] = tmp; } } static void shuffleSort(int[] a) { shuffleArray(a); Arrays.parallelSort(a); } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public MyScanner(String fileName) { try { br = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } } 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()); } int[] nextIntArray(int n){ int[]a = new int[n]; for(int i=0; i<n; i++) { a[i] = this.nextInt(); } return a; } long[] nextlongArray(int n) { long[]a = new long[n]; for(int i=0; i<n; i++) { a[i] = this.nextLong(); } return a; } Integer[] nextIntegerArray(int n){ Integer[]a = new Integer[n]; for(int i=0; i<n; i++) { a[i] = this.nextInt(); } return a; } Long[] nextLongArray(int n) { Long[]a = new Long[n]; for(int i=0; i<n; i++) { a[i] = this.nextLong(); } return a; } char[][] next2DCharArray(int n, int m){ char[][]arr = new char[n][m]; for(int i=0; i<n; i++) { arr[i] = this.next().toCharArray(); } return arr; } ArrayList<ArrayList<Integer>> readUndirectedUnweightedGraph(int n, int m) { ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>(); for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>()); for(int i=0; i<m; i++) { int u = s.nextInt(); int v = s.nextInt(); adj.get(u).add(v); adj.get(v).add(u); } return adj; } ArrayList<ArrayList<Integer>> readDirectedUnweightedGraph(int n, int m) { ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>(); for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>()); for(int i=0; i<m; i++) { int u = s.nextInt(); int v = s.nextInt(); adj.get(u).add(v); } return adj; } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n5 8\n1 4\n3 10", "4\n1 2\n2 3\n3 4\n4 5", "1\n1 1", "2\n1 9\n4 5", "2\n1 2\n2 8", "6\n216986951114298167 235031205335543871\n148302405431848579 455670351549314242\n506251128322958430 575521452907339082\n1 768614336404564650\n189336074809158272 622104412002885672\n588320087414024192 662540324268197150"]
2 seconds
["1 1", "0 0", "0 1", "0 0", "1 0", "1 0"]
NoteRemember, whoever writes an integer greater than $$$e_i$$$ loses.
Java 11
standard input
[ "dp", "dfs and similar", "games" ]
a0376bf145f4d9b5fbc1683956c203df
The first line contains the integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of rounds the game has. Then $$$t$$$ lines follow, each contains two integers $$$s_i$$$ and $$$e_i$$$ ($$$1 \le s_i \le e_i \le 10^{18}$$$) — the $$$i$$$-th round's information. The rounds are played in the same order as given in input, $$$s_i$$$ and $$$e_i$$$ for all rounds are known to everyone before the game starts.
2,700
Print two integers. The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise. The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise.
standard output
PASSED
8d872d716da6ea7644c8130cd2148a3b
train_003.jsonl
1592921100
Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"...The game is a one versus one game. It has $$$t$$$ rounds, each round has two integers $$$s_i$$$ and $$$e_i$$$ (which are determined and are known before the game begins, $$$s_i$$$ and $$$e_i$$$ may differ from round to round). The integer $$$s_i$$$ is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was $$$a$$$) and will choose to write either $$$2 \cdot a$$$ or $$$a + 1$$$ instead. Whoever writes a number strictly greater than $$$e_i$$$ loses that round and the other one wins that round.Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's $$$s_i$$$ and $$$e_i$$$ in advance. Lee will start the first round, the loser of each round will start the next round.The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game.Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not.
256 megabytes
import java.io.*; import java.text.*; import java.util.*; import java.math.*; public class template { public static void main(String[] args) throws Exception { new template().run(); } public void run() throws Exception { FastScanner f = new FastScanner(); PrintWriter out = new PrintWriter(System.out); /// int n = f.nextInt(); boolean win = false, lose = true; for(int i = 0; i < n; i++) { long a = f.nextLong(), b = f.nextLong(); boolean nwin = lose && canWin(a,b) || win && canWin(a+1, b) && canWin(2*a, b); boolean nlose = lose && canLose(a,b) || win && canLose(a+1, b) && canLose(2*a, b); win = nwin; lose = nlose; } out.print(win ? 1 : 0); out.print(" "); out.print(lose ? 1 : 0); /// out.flush(); } public boolean canWin(long a, long b) { if(a > b) return true; if(a == b) return false; if(2*a > b) return a%2 != b%2; if(b%2 == 1) return can1(a, b/2); else return can0(a, b/2); } public boolean canLose(long a, long b) { if(a > b) return false; if(a == b) return true; if(2*a > b) return true; return canWin(a, b/2); } public boolean can0(long a, long b) { if(2*a > b) return true; return canWin(a, b/2); } public boolean can1(long a, long b) { return a%2 == 0; } /// static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { 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()); } public String nextLine() { try { return reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
Java
["3\n5 8\n1 4\n3 10", "4\n1 2\n2 3\n3 4\n4 5", "1\n1 1", "2\n1 9\n4 5", "2\n1 2\n2 8", "6\n216986951114298167 235031205335543871\n148302405431848579 455670351549314242\n506251128322958430 575521452907339082\n1 768614336404564650\n189336074809158272 622104412002885672\n588320087414024192 662540324268197150"]
2 seconds
["1 1", "0 0", "0 1", "0 0", "1 0", "1 0"]
NoteRemember, whoever writes an integer greater than $$$e_i$$$ loses.
Java 11
standard input
[ "dp", "dfs and similar", "games" ]
a0376bf145f4d9b5fbc1683956c203df
The first line contains the integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of rounds the game has. Then $$$t$$$ lines follow, each contains two integers $$$s_i$$$ and $$$e_i$$$ ($$$1 \le s_i \le e_i \le 10^{18}$$$) — the $$$i$$$-th round's information. The rounds are played in the same order as given in input, $$$s_i$$$ and $$$e_i$$$ for all rounds are known to everyone before the game starts.
2,700
Print two integers. The first one should be 1 if Lee can be the winner independent of Ice Bear's moves, and 0 otherwise. The second one should be 1 if Lee can be the loser independent of Ice Bear's moves, and 0 otherwise.
standard output
PASSED
d0d7128970406e27f75c659ea2ed63b1
train_003.jsonl
1367769900
Yaroslav likes algorithms. We'll describe one of his favorite algorithms. The algorithm receives a string as the input. We denote this input string as a. The algorithm consists of some number of command. Сommand number i looks either as si &gt;&gt; wi, or as si &lt;&gt; wi, where si and wi are some possibly empty strings of length at most 7, consisting of digits and characters "?". At each iteration, the algorithm looks for a command with the minimum index i, such that si occurs in a as a substring. If this command is not found the algorithm terminates. Let's denote the number of the found command as k. In string a the first occurrence of the string sk is replaced by string wk. If the found command at that had form sk &gt;&gt; wk, then the algorithm continues its execution and proceeds to the next iteration. Otherwise, the algorithm terminates. The value of string a after algorithm termination is considered to be the output of the algorithm. Yaroslav has a set of n positive integers, he needs to come up with his favorite algorithm that will increase each of the given numbers by one. More formally, if we consider each number as a string representing the decimal representation of the number, then being run on each of these strings separately, the algorithm should receive the output string that is a recording of the corresponding number increased by one.Help Yaroslav.
256 megabytes
/** * Created with IntelliJ IDEA. * User: svasilinets * Date: 05.05.13 * Time: 22:07 */ public class E { public static void main(String[] args) { System.out.println("9??>>??0"); System.out.println("8??<>9"); System.out.println("7??<>8"); System.out.println("6??<>7"); System.out.println("5??<>6"); System.out.println("4??<>5"); System.out.println("3??<>4"); System.out.println("2??<>3"); System.out.println("1??<>2"); System.out.println("0??<>1"); System.out.println("??<>1"); System.out.println("?9>>9?"); System.out.println("?8>>8?"); System.out.println("?7>>7?"); System.out.println("?6>>6?"); System.out.println("?5>>5?"); System.out.println("?4>>4?"); System.out.println("?3>>3?"); System.out.println("?2>>2?"); System.out.println("?1>>1?"); System.out.println("?0>>0?"); System.out.println("?>>??"); System.out.println(">>?"); } }
Java
["2\n10\n79"]
2 seconds
["10&lt;&gt;11\n79&lt;&gt;80"]
null
Java 6
standard input
[]
90929863d289a475b766d5f2b0cd7c61
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the set. The next n lines contains one positive integer each. All the given numbers are less than 1025.
2,500
Print the algorithm which can individually increase each number of the set. In the i-th line print the command number i without spaces. Your algorithm will be launched for each of these numbers. The answer will be considered correct if:   Each line will a correct algorithm command (see the description in the problem statement). The number of commands should not exceed 50. The algorithm will increase each of the given numbers by one. To get a respond, the algorithm will perform no more than 200 iterations for each number.
standard output
PASSED
7814bc8663eba9e577997e07ddc846a3
train_003.jsonl
1367769900
Yaroslav likes algorithms. We'll describe one of his favorite algorithms. The algorithm receives a string as the input. We denote this input string as a. The algorithm consists of some number of command. Сommand number i looks either as si &gt;&gt; wi, or as si &lt;&gt; wi, where si and wi are some possibly empty strings of length at most 7, consisting of digits and characters "?". At each iteration, the algorithm looks for a command with the minimum index i, such that si occurs in a as a substring. If this command is not found the algorithm terminates. Let's denote the number of the found command as k. In string a the first occurrence of the string sk is replaced by string wk. If the found command at that had form sk &gt;&gt; wk, then the algorithm continues its execution and proceeds to the next iteration. Otherwise, the algorithm terminates. The value of string a after algorithm termination is considered to be the output of the algorithm. Yaroslav has a set of n positive integers, he needs to come up with his favorite algorithm that will increase each of the given numbers by one. More formally, if we consider each number as a string representing the decimal representation of the number, then being run on each of these strings separately, the algorithm should receive the output string that is a recording of the corresponding number increased by one.Help Yaroslav.
256 megabytes
import java.util.*; //Scanner; import java.io.PrintWriter; //PrintWriter public class R182_Div2_E //Name: Yaroslav and Algorithm { public static void main(String[] args) { Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); solve(in, out); out.close(); in.close(); } public static void solve(Scanner in, PrintWriter out) { int n = in.nextInt(); String s; for (int i = 0; i < n; i++) s = in.next(); for (int i = 0; i < 10; i++) out.println("??" + i + ">>" + i + "??"); out.println("??>>?"); for (int i = 0; i < 9; i++) out.println(i + "?<>" + (i + 1)); out.println("9?>>?0"); out.println("?<>1"); out.println(">>??"); } }
Java
["2\n10\n79"]
2 seconds
["10&lt;&gt;11\n79&lt;&gt;80"]
null
Java 7
standard input
[]
90929863d289a475b766d5f2b0cd7c61
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the set. The next n lines contains one positive integer each. All the given numbers are less than 1025.
2,500
Print the algorithm which can individually increase each number of the set. In the i-th line print the command number i without spaces. Your algorithm will be launched for each of these numbers. The answer will be considered correct if:   Each line will a correct algorithm command (see the description in the problem statement). The number of commands should not exceed 50. The algorithm will increase each of the given numbers by one. To get a respond, the algorithm will perform no more than 200 iterations for each number.
standard output
PASSED
21e2fa514a14467c86f6d4cbccf0fd21
train_003.jsonl
1367769900
Yaroslav likes algorithms. We'll describe one of his favorite algorithms. The algorithm receives a string as the input. We denote this input string as a. The algorithm consists of some number of command. Сommand number i looks either as si &gt;&gt; wi, or as si &lt;&gt; wi, where si and wi are some possibly empty strings of length at most 7, consisting of digits and characters "?". At each iteration, the algorithm looks for a command with the minimum index i, such that si occurs in a as a substring. If this command is not found the algorithm terminates. Let's denote the number of the found command as k. In string a the first occurrence of the string sk is replaced by string wk. If the found command at that had form sk &gt;&gt; wk, then the algorithm continues its execution and proceeds to the next iteration. Otherwise, the algorithm terminates. The value of string a after algorithm termination is considered to be the output of the algorithm. Yaroslav has a set of n positive integers, he needs to come up with his favorite algorithm that will increase each of the given numbers by one. More formally, if we consider each number as a string representing the decimal representation of the number, then being run on each of these strings separately, the algorithm should receive the output string that is a recording of the corresponding number increased by one.Help Yaroslav.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author vadimmm */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } } class TaskE { public void solve(int testNumber, InputReader in, PrintWriter out) { for (int i = 0; i < 9; ++i) out.printf("%d??<>%d\n", i, i + 1); out.printf("9??>>??0\n"); out.printf("??<>1\n"); for (int i = 0; i < 10; ++i) out.printf("?%d>>%d?\n", i, i); out.printf(">>?\n"); } } class InputReader { private static BufferedReader bufferedReader; private static StringTokenizer stringTokenizer; public InputReader(InputStream inputStream) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); stringTokenizer = null; } }
Java
["2\n10\n79"]
2 seconds
["10&lt;&gt;11\n79&lt;&gt;80"]
null
Java 7
standard input
[]
90929863d289a475b766d5f2b0cd7c61
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the set. The next n lines contains one positive integer each. All the given numbers are less than 1025.
2,500
Print the algorithm which can individually increase each number of the set. In the i-th line print the command number i without spaces. Your algorithm will be launched for each of these numbers. The answer will be considered correct if:   Each line will a correct algorithm command (see the description in the problem statement). The number of commands should not exceed 50. The algorithm will increase each of the given numbers by one. To get a respond, the algorithm will perform no more than 200 iterations for each number.
standard output
PASSED
b60900dce81873661aed31b4aed01a2d
train_003.jsonl
1367769900
Yaroslav likes algorithms. We'll describe one of his favorite algorithms. The algorithm receives a string as the input. We denote this input string as a. The algorithm consists of some number of command. Сommand number i looks either as si &gt;&gt; wi, or as si &lt;&gt; wi, where si and wi are some possibly empty strings of length at most 7, consisting of digits and characters "?". At each iteration, the algorithm looks for a command with the minimum index i, such that si occurs in a as a substring. If this command is not found the algorithm terminates. Let's denote the number of the found command as k. In string a the first occurrence of the string sk is replaced by string wk. If the found command at that had form sk &gt;&gt; wk, then the algorithm continues its execution and proceeds to the next iteration. Otherwise, the algorithm terminates. The value of string a after algorithm termination is considered to be the output of the algorithm. Yaroslav has a set of n positive integers, he needs to come up with his favorite algorithm that will increase each of the given numbers by one. More formally, if we consider each number as a string representing the decimal representation of the number, then being run on each of these strings separately, the algorithm should receive the output string that is a recording of the corresponding number increased by one.Help Yaroslav.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class E { private static StringTokenizer tokenizer; private static BufferedReader bf; private static PrintWriter out; private static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } @SuppressWarnings("unused") private static long nextLong() throws IOException { return Long.parseLong(nextToken()); } private static String nextToken() throws IOException { while(tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(bf.readLine()); } return tokenizer.nextToken(); } public static void main(String[] args) throws IOException { bf = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); out.println("9??>>??0"); out.println("8??<>9"); out.println("7??<>8"); out.println("6??<>7"); out.println("5??<>6"); out.println("4??<>5"); out.println("3??<>4"); out.println("2??<>3"); out.println("1??<>2"); out.println("0??<>1"); out.println("??<>1"); out.println("?9>>9?"); out.println("?8>>8?"); out.println("?7>>7?"); out.println("?6>>6?"); out.println("?5>>5?"); out.println("?4>>4?"); out.println("?3>>3?"); out.println("?2>>2?"); out.println("?1>>1?"); out.println("?0>>0?"); out.println("?>>??"); out.println(">>?"); out.close(); } }
Java
["2\n10\n79"]
2 seconds
["10&lt;&gt;11\n79&lt;&gt;80"]
null
Java 7
standard input
[]
90929863d289a475b766d5f2b0cd7c61
The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the set. The next n lines contains one positive integer each. All the given numbers are less than 1025.
2,500
Print the algorithm which can individually increase each number of the set. In the i-th line print the command number i without spaces. Your algorithm will be launched for each of these numbers. The answer will be considered correct if:   Each line will a correct algorithm command (see the description in the problem statement). The number of commands should not exceed 50. The algorithm will increase each of the given numbers by one. To get a respond, the algorithm will perform no more than 200 iterations for each number.
standard output